Compare commits
588 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| a76fba8408 | |||
| b97685f238 | |||
| 198a967e52 | |||
| 871b45e2de | |||
| 8d9920a3a4 | |||
| 4061f19dff | |||
| 6c6d411f9d | |||
| 21b060e7ad | |||
| e67a25bdbf | |||
| a796bb31ee | |||
| 109fb27e00 | |||
| b0cfe20952 | |||
| f6d5ea7b98 | |||
| 6b4b5d188b | |||
| f07303cd09 | |||
| 16076fa40f | |||
| 4719c9289e | |||
| a7dbaaabb2 | |||
| b5685225e0 | |||
| cfdc10d78c | |||
| fc7f3e96e2 | |||
| 4734167be6 | |||
| 01e0a35372 | |||
| 4ebe36edef | |||
| ed1c62ac8a | |||
| 854747f68d | |||
| 8bbc07d9e9 | |||
| d9ea961ca6 | |||
| 2feda33ec6 | |||
| f1a84307be | |||
| f351e14683 | |||
| b2bc0a966f | |||
| 27ebf64eeb | |||
| 3b322596c2 | |||
| 2020a4f04f | |||
| 950f06c0be | |||
| 63b0759e2a | |||
| de0dad7d58 | |||
| 5a1a615f87 | |||
| be21dbc400 | |||
| 415f7752c0 | |||
| cb15824487 | |||
| b93c318080 | |||
| 9f9dfc7245 | |||
| 326b239b24 | |||
| fdb13957ab | |||
| 3766e880ca | |||
| 42b6caf2dc | |||
| 15d53b37b8 | |||
| a1adbbfd8b | |||
| 6f8a650ac0 | |||
| 72fd688d81 | |||
| a845c91217 | |||
| 7598584ed5 | |||
| 0721bd13e8 | |||
| 95fb95350b | |||
| 6dff757ff4 | |||
| e560a74445 | |||
| 6a054159ae | |||
| 11e613d083 | |||
| f3bfff1af4 | |||
| 7cf4f54c90 | |||
| cf9f6b9e7a | |||
| 0292c1a55c | |||
| 5c306fdd51 | |||
| 2d3f3adebc | |||
| 2f2a770392 | |||
| 3ef8c196cd | |||
| 39437cef6a | |||
| 50a98c2262 | |||
| 37dfa0fd5a | |||
| fcdc008977 | |||
| 569456f24e | |||
| 346f56b193 | |||
| 201aa02c3e | |||
| 87287dcb71 | |||
| 9e64f834df | |||
| f8fbf3a4d4 | |||
| e7c505bf60 | |||
| fe5a6a4391 | |||
| e5c5970915 | |||
| dcd4dad0eb | |||
| 1ce34e2084 | |||
| 996e33d550 | |||
| d31cec5118 | |||
| 86fda17c88 | |||
| 1ee4bdbcdb | |||
| a1dff580c5 | |||
| e149e70608 | |||
| 229a77ddcb | |||
| fee0422a0d | |||
| db459982ee | |||
| 6f8d9aacd5 | |||
| 9b219c402e | |||
| 4cc9953836 | |||
| afa1fcf014 | |||
| 7e13778191 | |||
| 3c1cc85f34 | |||
| 0aedb5f5e9 | |||
| 3ec67085c5 | |||
| 95566e7225 | |||
| 13344170ef | |||
| b2a277b642 | |||
| 8f02d11096 | |||
| b346a3572e | |||
| dde06fc465 | |||
| b1913ed65d | |||
| 2157f5927d | |||
| 97e76dd1ce | |||
| 53014f849c | |||
| bc2cc2c68e | |||
| 8cee26b1d6 | |||
| 745818826a | |||
| d18441ba89 | |||
| 2630291af2 | |||
| e694e4154e | |||
| b02bdd0bf4 | |||
| a83003980c | |||
| 4cda8551b4 | |||
| 9ca791435f | |||
| 298fb41fed | |||
| affe56b074 | |||
| dd30a1199a | |||
| 324d65007f | |||
| e2e3569e1f | |||
| 4e728df7cc | |||
| 885396370a | |||
| 6a8bbcfff9 | |||
| c386163a5f | |||
| 60a00ce54f | |||
| 030e29a52d | |||
| 9de87e04cf | |||
| 75b0e46326 | |||
| 2c6e0633cf | |||
| a984e98e0a | |||
| dd56ad8fdd | |||
| 28d027ffef | |||
| c1133edf39 | |||
| efed78bf5e | |||
| 642a8bc80b | |||
| 8da25d8c55 | |||
| acbe3ec8b5 | |||
| 1c5551a145 | |||
| 56ac929634 | |||
| e2cb4a26f8 | |||
| fb764a7549 | |||
| 9c2f982741 | |||
| 05efbb1d8a | |||
| 53ed5150be | |||
| 77fef49fce | |||
| c7f6099945 | |||
| 45276fc3bf | |||
| 243cd676f8 | |||
| 0050cd6772 | |||
| a9ec529158 | |||
| 083cc782d0 | |||
| 08c5625ac7 | |||
| 37db225514 | |||
| 5cc37dd861 | |||
| a69cfd2624 | |||
| 84aa3e6b20 | |||
| 737d58ad9f | |||
| e67c882a08 | |||
| e58c98a30f | |||
| 527aef3495 | |||
| 1fca6137c2 | |||
| 6240f82857 | |||
| 7d440c6ee1 | |||
| 8a2dbd70f1 | |||
| 382472bd39 | |||
| c7c5ec083f | |||
| d95c8548aa | |||
| 50249b1a59 | |||
| 7d3906181b | |||
| 3efbca09f0 | |||
| ccf9c00e9c | |||
| 3bac4c4df4 | |||
| 8055a33b48 | |||
| 4c8dbe8da2 | |||
| d3071455d8 | |||
| dbe7bd3abd | |||
| 51949a06dd | |||
| 96aebc74a0 | |||
| c1978a4738 | |||
| fbe753e1b5 | |||
| 26826685e2 | |||
| 9ae7b07620 | |||
| c28fac088d | |||
| 88f1671388 | |||
| eb4dc7ab72 | |||
| 12ed8053df | |||
| 1881190be9 | |||
| a3ecbacaab | |||
| fc3170e0ec | |||
| 6b8f55136b | |||
| 12d6d75462 | |||
| c7333c05ee | |||
| 8c9bf090f1 | |||
| 946daf5e3f | |||
| 60353275f6 | |||
| 1fc91a5535 | |||
| f35e525b9c | |||
| 35907caefa | |||
| 5e5eea21e5 | |||
| da1ef19795 | |||
| f33704872f | |||
| 5062a97158 | |||
| 24efce674c | |||
| aa062da0bd | |||
| 471350d388 | |||
| 13d8b167a7 | |||
| 1b8142e7e5 | |||
| cefb297e14 | |||
| f199118e74 | |||
| 9ea4f0abf6 | |||
| 7b86497a93 | |||
| a483e8d637 | |||
| aff4ba6651 | |||
| 4f0f801ba0 | |||
| 897c6e9552 | |||
| c2c5d4b885 | |||
| 7426f84aff | |||
| 894f99e55b | |||
| a58a0a8262 | |||
| c14707da54 | |||
| 3f5e0bb1ae | |||
| 6750d24c6d | |||
| d983d0ef11 | |||
| 961d8e6bfb | |||
| 6bb432f52a | |||
| 88d146aeda | |||
| 17b46d80e8 | |||
| 8154026efc | |||
| 9bf32c6b44 | |||
| 2f2fb60626 | |||
| 8260a54969 | |||
| 1d39416481 | |||
| 8e2cfa59a9 | |||
| 94dd717b51 | |||
| 95fd2588c0 | |||
| fe916873f6 | |||
| 5ce2feec1a | |||
| 04a92346a3 | |||
| d489ad75a1 | |||
| 44acfee149 | |||
| 4a4dadeec7 | |||
| ee9da2fb07 | |||
| fb8ba8a187 | |||
| e360c0ca87 | |||
| c7af0ff900 | |||
| 4d4abd208f | |||
| 8c082eec1c | |||
| f54d6b5ff8 | |||
| b5637320fc | |||
| 673165d650 | |||
| 7e54a67b87 | |||
| 2cbf57cbd5 | |||
| c6930745a3 | |||
| f5e3f7f10c | |||
| 0047b8c624 | |||
| f735a8ad80 | |||
| 57e67f8f0a | |||
| 95e613380b | |||
| 26fb73f8eb | |||
| 54bc5df401 | |||
| 83df315f48 | |||
| 3531995d21 | |||
| 21e0843f12 | |||
| 54cec00d85 | |||
| 7146b447ab | |||
| 9e984572c2 | |||
| 22c3dbfa33 | |||
| fb32976336 | |||
| de6d218ca1 | |||
| bdf081aadd | |||
| b65c23582f | |||
| 5baedb58df | |||
| 6425d42ee7 | |||
| c63d2fe850 | |||
| d9d8491493 | |||
| 381be8f930 | |||
| db2f38749c | |||
| f3b9378e9f | |||
| 8e63fa0f0b | |||
| f948839eec | |||
| 0a2a2711dc | |||
| b95f2c89cf | |||
| bed98f5306 | |||
| f24754ed43 | |||
| b6ca06c790 | |||
| e99d640b51 | |||
| 12f743c629 | |||
| 4749bb7fa6 | |||
| e80114d068 | |||
| 7828fe1edf | |||
| 4f7ac81a93 | |||
| 9a757f849f | |||
| 8ec4bfa336 | |||
| b6c42bbf48 | |||
| 96b93d7852 | |||
| e5d82308c8 | |||
| ffc524975f | |||
| edbe3af024 | |||
| f807bc8bd5 | |||
| 5da1a3e407 | |||
| 24f0b29303 | |||
| c8757a96f6 | |||
| 406feffbce | |||
| 31f202650b | |||
| 809a1ed23b | |||
| 124dc16459 | |||
| ed300dd630 | |||
| 847ba14aa0 | |||
| da55c778ed | |||
| 6b0aac6198 | |||
| 5ba01eefae | |||
| 01bba7f4a5 | |||
| 83c31db36b | |||
| 86b42e57dd | |||
| 0c5f362295 | |||
| 2154c8bf28 | |||
| f7b5f3ac1e | |||
| dd8d6a519b | |||
| dd5cce9367 | |||
| f8f87dfdd1 | |||
| f99588cc45 | |||
| 44f3e57708 | |||
| 970f80a210 | |||
| 0488189f8a | |||
| 1dd5c7bb72 | |||
| 9c6cc055e3 | |||
| 72ad23f7c2 | |||
| d23a2f4837 | |||
| cf243cc72c | |||
| d14e854879 | |||
| 19baebd388 | |||
| 3afc075079 | |||
| a6207e55c0 | |||
| a43ef188d3 | |||
| 0d85574a98 | |||
| a48ac5c16a | |||
| c28f4ecf6b | |||
| 2e046a976f | |||
| 3b5ddd145c | |||
| eb65cef466 | |||
| f60d646dfd | |||
| f75408fba2 | |||
| aec15ccca7 | |||
| 915b9683d2 | |||
| 47347ad0b0 | |||
| 69ffd6c1a1 | |||
| 8e1cd07402 | |||
| 8d321e6ae2 | |||
| dd4219e253 | |||
| d1d7c56bed | |||
| d69d7010a0 | |||
| 42a569a10c | |||
| c132f736e2 | |||
| 5af00ee603 | |||
| b04874bda3 | |||
| 3cdf130bf0 | |||
| ba7047d889 | |||
| 0331a6d45e | |||
| 732c4a45b4 | |||
| c1ea5c4127 | |||
| 3766aed995 | |||
| b3a843a313 | |||
| 68adaf316c | |||
| 82789d34fa | |||
| 7b38aed614 | |||
| 7f7d5d259f | |||
| 38c2e24f96 | |||
| d3613f45d4 | |||
| ae7c332ba3 | |||
| 5f7d34b87d | |||
| 9f75fe8c51 | |||
| 848e25a36e | |||
| d85b7a5ba0 | |||
| 38405b859a | |||
| dbdae79272 | |||
| bb354001fe | |||
| 2fed341c1b | |||
| b9584369ea | |||
| ccae14f1f0 | |||
| a7625512b3 | |||
| 91d29fc843 | |||
| 09f2d71910 | |||
| bea0716bf5 | |||
| c039ee35ce | |||
| c736861272 | |||
| 9d74a5c54e | |||
| 8f272dd87a | |||
| ce1ee9b6d2 | |||
| e9365c26fc | |||
| 31ec74498c | |||
| 61b7b44243 | |||
| b39bf5065e | |||
| 41b3f4705b | |||
| 07b88542ef | |||
| 2cd26461e8 | |||
| e906ebc87b | |||
| d1435684df | |||
| 50e8056f4d | |||
| 28cbea70d4 | |||
| 74b7f4a4b9 | |||
| 2d46aa3b8f | |||
| fdc3bc38d4 | |||
| 45b4030347 | |||
| 03cccd24f4 | |||
| 0eb97e9e88 | |||
| 80f1cc2dc9 | |||
| 09fb7dcdd5 | |||
| 74d9df412e | |||
| 4eec8d74ff | |||
| 9252884a55 | |||
| 1839c8a19e | |||
| 387c22087c | |||
| 8b3da15658 | |||
| c42e6fe18f | |||
| 5699eb931f | |||
| 5e4f2a21a5 | |||
| aacd5e42c2 | |||
| 9465075d3e | |||
| 3b416168e1 | |||
| fb720b57e3 | |||
| 002fb5aede | |||
| ef7066cf03 | |||
| 2f46a13e5d | |||
| 160b1dae5f | |||
| 6340e5a993 | |||
| 6d5d19bd69 | |||
| 1568b3888d | |||
| f8123c304b | |||
| 9d0b1fd810 | |||
| 835ffe422c | |||
| a60cefd283 | |||
| 4c0c28f888 | |||
| d1d80d8069 | |||
| 0e7f5895bb | |||
| 0267de9abb | |||
| cd3684e720 | |||
| 8e8503345b | |||
| 8e03bac176 | |||
| 07386de747 | |||
| a5e6e92f22 | |||
| 7bf437e75b | |||
| b37b2e91f7 | |||
| 5a481d3ebf | |||
| e7ff869398 | |||
| 796d7d4901 | |||
| 2f9812dc58 | |||
| e1ea066e12 | |||
| 7b62881eae | |||
| eb54a58656 | |||
| 76eb0c77b9 | |||
| 66a0696c2b | |||
| 6096f7d279 | |||
| 3f0f329ef9 | |||
| 89c88b5163 | |||
| b712076144 | |||
| 798dfd781e | |||
| c0dba6625c | |||
| c12a4109f9 | |||
| 9aa0e0bb3d | |||
| 5544605006 | |||
| 7fad122df6 | |||
| 5b5e01ed9d | |||
| b79eb74e00 | |||
| 872ffd3f67 | |||
| b436d2756d | |||
| d104ea0b33 | |||
| 4620d2e29b | |||
| 6ccd5b190f | |||
| aca7594658 | |||
| 236ee08a59 | |||
| 8aa09a8f2b | |||
| b9f65aac20 | |||
| 990963d586 | |||
| 9fb811c10a | |||
| 52c7ae5bf8 | |||
| 40b2ed90cb | |||
| c94a64a501 | |||
| 0bfbea22cd | |||
| ad06d08a46 | |||
| ffcdfeaefd | |||
| f6f4b41739 | |||
| f9ca0cbe74 | |||
| ec3b584ced | |||
| 96a3f845d1 | |||
| 3da416bd70 | |||
| f34320270c | |||
| 7ba3d0325b | |||
| 0370adf1fc | |||
| a11c4a443b | |||
| 4530b40b88 | |||
| f49bd7018b | |||
| e1707183fd | |||
| f51900106f | |||
| 872cc373c1 | |||
| e40a6910e0 | |||
| 91d6c47af7 | |||
| c41b6f2351 | |||
| dd9e7a3ade | |||
| db0e126c0e | |||
| 34ac56813f | |||
| 57ddf715b3 | |||
| 6bd150c820 | |||
| 56a2985a6f | |||
| a2212fe1f8 | |||
| d42c99c37d | |||
| 211524196b | |||
| dc844030fa | |||
| d9ab58b2c5 | |||
| 8589d3aef8 | |||
| 426cb82d92 | |||
| 88b5478c1f | |||
| 7a8df5f2da | |||
| e77c6de621 | |||
| 8b2d89fa15 | |||
| 43aa6ec4df | |||
| c729a130a6 | |||
| 765705e3ca | |||
| bef4bb0ef8 | |||
| a32f3edb1f | |||
| 4b3f545158 | |||
| c135e2141e | |||
| 23efe40404 | |||
| 13dae8ac2d | |||
| 01a7c9d51b | |||
| df2c28e703 | |||
| ce9eaf6114 | |||
| d5f5af48b9 | |||
| f5b3ba0a5d | |||
| 041fb8b98d | |||
| ce9c96c57c | |||
| 2c39de2b48 | |||
| 4c0b7b5fe7 | |||
| 39acf6dff0 | |||
| 70ad9a9caa | |||
| f8131946ae | |||
| a6a5f99bfe | |||
| 1514327d34 | |||
| dbf3c6e27a | |||
| 9f80bfb9de | |||
| fa53ae6137 | |||
| 8e221712cb | |||
| 00446be689 | |||
| f385b563f0 | |||
| d0ce3b2690 | |||
| 6f328d1c40 | |||
| 86b9a85b92 | |||
| 49c91df534 | |||
| 2c0e505574 | |||
| c26f19bf4b | |||
| 9f9bb77524 | |||
| 4ff316884e | |||
| 2a321aeaa8 | |||
| 4e71611e59 | |||
| e39f7c3eeb | |||
| f118809d85 | |||
| be2d96a808 | |||
| 2f3b2f0f6c | |||
| 471b86db5e | |||
| c260a24ff7 | |||
| 8cc2ad05d0 | |||
| 83d3325471 | |||
| 000c76d8b6 | |||
| 4c0f593a6a | |||
| 9dc4d80740 | |||
| 02216fc6e9 | |||
| 5876248afe | |||
| 6ddcbaf961 | |||
| 4a8236e751 | |||
| c5ebc54f60 | |||
| e93359a635 | |||
| 2bd29db69c | |||
| e1852ef390 | |||
| 8585257e84 | |||
| 4e0437ee58 | |||
| 7b5fe7d78d | |||
| cdb120c780 | |||
| e99ae11f74 | |||
| 8135bef08a | |||
| 093e75a9af | |||
| 3b3bf1a543 | |||
| acb95f7ead | |||
| 59ef9e209b | |||
| 8e6b7239b3 |
@@ -1,3 +1,3 @@
|
||||
{
|
||||
"model": "claude-fable-5-1"
|
||||
"model": "claude-opus-5-5"
|
||||
}
|
||||
|
||||
+43
-4
@@ -10,7 +10,6 @@
|
||||
!CLAUDE.md
|
||||
!README.md
|
||||
!settings.json
|
||||
!statusline.sh
|
||||
!todo.md
|
||||
|
||||
!.claude/
|
||||
@@ -18,15 +17,55 @@
|
||||
!agents/
|
||||
!agents/*.md
|
||||
!bin/
|
||||
!bin/*
|
||||
!bin/claude_code/
|
||||
!bin/claude_code/*.py
|
||||
!bin/comprehension_history.py
|
||||
!bin/failure.py
|
||||
!bin/file_writes.py
|
||||
!bin/git_command.py
|
||||
!bin/larv-review
|
||||
!bin/larv_review/
|
||||
!bin/larv_review/*.py
|
||||
!bin/loop-claude
|
||||
!bin/loop_claude/
|
||||
!bin/loop_claude/**/
|
||||
!bin/loop_claude/**/*.py
|
||||
!bin/markdown_text.py
|
||||
!bin/metric-bench
|
||||
!bin/metric_bench/
|
||||
!bin/metric_bench/*.py
|
||||
!bin/project_key.py
|
||||
!bin/rank_todo.py
|
||||
!bin/reading-cost
|
||||
!bin/reading_cost/
|
||||
!bin/reading_cost/*.py
|
||||
!bin/repo_checks/
|
||||
!bin/repo_checks/*.py
|
||||
!bin/rule-hook
|
||||
!bin/rule_hook/
|
||||
!bin/rule_hook/*.py
|
||||
!bin/shell_command.py
|
||||
!bin/statusline.py
|
||||
!bin/test_*.py
|
||||
!bin/todo_table.py
|
||||
!bin/transcript_archive/
|
||||
!bin/transcript_archive/*.py
|
||||
!bin/utc_stamp.py
|
||||
!docs/
|
||||
!docs/*.md
|
||||
!principles/
|
||||
!principles/*.md
|
||||
!rules/
|
||||
!rules/*.md
|
||||
!skills/
|
||||
!skills/comprehension-panel/
|
||||
!skills/comprehension-panel/**
|
||||
!skills/comprehension-panel/*.md
|
||||
!skills/larv-review/
|
||||
!skills/larv-review/**
|
||||
!skills/larv-review/*.md
|
||||
!skills/larv-review/standards/
|
||||
!skills/larv-review/standards/*.md
|
||||
!workflow-bench/
|
||||
!workflow-bench/bench.py
|
||||
!workflow-bench/compare-prompt.md
|
||||
!workflow-bench/compare.py
|
||||
!workflow-bench/run-prompt.md
|
||||
|
||||
@@ -1,36 +1,47 @@
|
||||
# Working here
|
||||
|
||||
**⚠️ THE REBUILD NEVER MERGES INTO MAIN WITHOUT THE HUMAN'S EXPLICIT APPROVAL.** Every rebuild chunk is a worktree based on `origin/rebuild` with its PR into `rebuild`, never into main. Other sessions run on `~/.claude` main throughout; only the human merges `rebuild` into main, once they have approved the finished whole. larv-review leaves a PR from `rebuild` into main ready and unmerged.
|
||||
|
||||
Decisions live in `docs/decisions.md`:
|
||||
|
||||
- larv-review: a project under the comprehension floor is fixed at the capping dimension
|
||||
- loop-claude: a judge decides interrupts, not the worker's self-report
|
||||
- loop-claude: one session per project, at a fixed id from its full path, and a second loop refuses to start
|
||||
- loop-claude: the trust file is rewritten before an interrupt
|
||||
- loop-claude: every worktree of the checkout is trusted before an interrupt
|
||||
- bin/: the Python floor is README's Install prerequisite
|
||||
- bin/: host python, no container
|
||||
- comprehension floor: every dimension and the overall at 7.0 or above, and 0.1.0 waits on it
|
||||
- vocabulary: the concept words are defined under `CLAUDE.md` → "Vocabulary" and cited by a bare link
|
||||
- loop-claude: a reload into an older file is unsupported
|
||||
- loop-claude: a CR-only README.md is reported at line 1
|
||||
- loop-claude: each project's model lives in loop-claude's own file
|
||||
- rebuild: loop-claude and the review process are rebuilt on `rebuild` and merge to main whole
|
||||
- review: the round cap counts a pass's rounds per chunk
|
||||
- review: a 🟢's or ❓'s fix re-enters like any fix
|
||||
- review: only a record older than the chunk lets a pass skip
|
||||
- loop-claude: the judge is retried alone, on its own counter
|
||||
- loop-claude: the judge loads `CLAUDE.md`
|
||||
- larv-review: a project under the comprehension floor is fixed at the lowest dimension
|
||||
- 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: one session per project, its id derived from the checkout's path relative to `~/code`, or to `/` outside it
|
||||
- loop-claude: before an interrupt, it marks the checkout and each of its worktrees trusted in `~/.claude.json`
|
||||
- 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
|
||||
- comprehension floor: every dimension and the overall at 7.0 or above, and 0.3.0 waits on it
|
||||
- loop-claude: each project's model lives in `~/.claude/loop-claude-models.json`, which only loop-claude writes
|
||||
- review: a pass gets at most three rounds per chunk; instead of a fourth, the run asks the human
|
||||
- review: a fix for a 🔴 or 🟡 reruns the pass that found it and each pass whose trigger names fixes like it; a fix for a 🟢, a ❓ or a prose finding reruns none
|
||||
- review: a paired ruling against the last measured commit decides the ratchet, and counts as worse when a dimension it rules fallen is under the floor; the four-seat scoring run checks the floor when a release's items run out or an item names the floor, and also runs when a ruling names a fallen dimension
|
||||
- review: a project decision may suspend the comprehension check for the plan items it names
|
||||
- review: a project decision may opt every chunk out of the architect, the product-owner pass or the comprehension check
|
||||
- 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
|
||||
- loop-claude: the archive keeps the raw transcript, and a failed archive stops the loop
|
||||
- loop-claude: a loop running main's script stops once at the cut-over
|
||||
- rebuild: a chunk into `rebuild` takes no comprehension scoring run
|
||||
- loop-claude: a `claude` that cannot start is a failed worker run, retried
|
||||
- bin/: mypy checks `loop_claude`'s types in the tests
|
||||
- rebuild: rebuild's larv-review reviews a chunk into `rebuild`
|
||||
- review: an ask no user answers leaves the PR unmerged
|
||||
- review: the architecture pass audits every principle and goal over the whole project, and a release's last chunk fires it
|
||||
- loop-claude: every claude it starts bypasses permissions inside its sandbox
|
||||
- stats: a chunk's cost and review numbers are kept in the transcript archive
|
||||
- bench: a workflow change merges only once three benches rule it better
|
||||
- chunk: as large as one purpose allows
|
||||
- review: `/security-review` is the security pass of record, except where the full scan runs on the same change and replaces it
|
||||
- review: the premises chunk's whole review is the human's approval
|
||||
- workflow-bench/: the remote may show the bench cases' names and commit SHAs
|
||||
- settings.json: Claude Code runs in auto mode with the dangerous-mode prompt skipped
|
||||
- the repo may name bender, bender-infra and ai-sandbox
|
||||
- todo.md: one table of items scored by the formula and goal weights it states, held to its bar, ranked by `bin/rank_todo.py`
|
||||
- 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
|
||||
- reading cost: a rise is the last 5 chunks' median above the 5 before them, and files or refreshes one plan item
|
||||
- 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
|
||||
- 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
|
||||
- worker: a chunk's worker writes the simplest change that solves its item, test first wherever a test can check the change, and reads a technical principle only where the item, a finding or its own record names it; larv-review's reviewers hold the change to the principles and to the standards in `skills/larv-review/standards/`
|
||||
|
||||
## Working rules
|
||||
|
||||
- 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. When it 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
|
||||
|
||||
The project values for `skills/comprehension-panel/seat-prompts.md`:
|
||||
|
||||
- `{language}`: Python
|
||||
- `{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
|
||||
|
||||
+47
-2
@@ -2,16 +2,61 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
- A session no longer reads the technical principles before writing code. It writes the simplest change that solves its item, test first wherever a test can check the change, and reads a principle only when the item changes it, a finding names it, or a decision or `todo.md` item it writes cites it. larv-review's reviewers hold the change to the principles, and a finding against one names it. Expect more findings from the prose and stability reviewers, since sessions no longer load the rules for comments and READMEs.
|
||||
- The rules for comments and READMEs, "Quality" and the examples behind "Prose" moved to `skills/larv-review/standards/`, which the prose and stability reviewers and `loop-claude`'s judge read. `CLAUDE.md` keeps a short core of "Prose"; sorting where order carries no meaning lives only in the technical principles.
|
||||
- A session no longer points out a preference you have repeated or asks you to write it up, and no longer restructures `CLAUDE.md` and `rules/` after changing them.
|
||||
- A `todo.md` item names a release whose version bump fits the item under strict semver: a major for a change to what exists (a minor before 1.0.0), a minor for an addition, a patch for a fix.
|
||||
- `CLAUDE.md` keeps only the rules no file path can scope. The rules for `todo.md` items, decisions and a README's Goals and Audience moved to files under `rules/`. Claude Code loads each one when a session reads or writes a matching file. `loop-claude`'s judge reads them beside `CLAUDE.md`.
|
||||
- A README no longer holds cross-cutting decisions; `docs/decisions.md` does.
|
||||
- A technical principle, "Prefer deep modules": a module puts a small, intuitive interface in front of a lot of hidden work, and hides how it works but never what it depends on. It wins over "Explicit over implicit" unless hiding the work makes it harder for someone new to the project to tell what a call does. "Functional core, imperative shell" moves up to second place, a core rule beside "Compose, do not entangle" that no other principle overrides. The systems architect holds every module to it.
|
||||
- A hook blocks each Bash, Edit, MultiEdit and Write call that breaks a rule a program can check: a commit message that is not one line passed with `-m`, a Claude or Anthropic attribution, a container image short of a full patch version, an Action pinned to anything but a semver tag, an unsorted block in an ignore file, and a commit of a `todo.md` that `rank_todo.py --check` rejects. `CLAUDE.md` states those rules only where the hook cannot check them; `~/.claude/bin/rule-hook --help` states what it checks. A call overrides a rule with `# rule-override <rule>: <reason>`. larv-review's new overrides pass, run before stability, accepts or rejects each override the chunk logged, and the PR body lists each with its ruling; a rejected override means the chunk keeps the rule. An override that touches a credential, a security rule or a production system, or cannot be undone, is asked of you.
|
||||
- A project may opt out of larv-review's architect, product-owner pass or comprehension check in every chunk, through a `docs/decisions.md` entry titled `review opt-out: …` that names the goal that skipping them serves. A project without such an entry is reviewed as before. Opting out of the comprehension check also skips the scoring run due at a release's end, so the floor blocks nothing; the opt-out ends with a chunk that ships a plan item naming the floor, which removes the comprehension check from the entry. The principles audit always runs.
|
||||
- A README goal states the project's aim and intent, and no longer names a step of the work, such as "kill weak candidates early". Such steps go in a method section further down the README and name the goal they serve.
|
||||
- The stability reviewer keeps its scratch work in a directory it creates for the run, deletes that directory afterwards, and deletes nothing else.
|
||||
- larv-review's mechanical rules run in the new, tested `bin/larv-review`: the paired ruling's base (`ruling-base`), each pass's round count (`round-count`, which ignores case in a round's commit title, counts a repeated round number as a round of its own, and says to ask you before another round once a pass is at or past the cap), the scoring run's trigger (`needs-scoring-run <item ID>...`), and the vote count, means and history format (`record-ruling <votes file> [<scores file>]` and `record-scoring <scores file> [<item ID>...]`, which append to `docs/comprehension-history.md` and refuse a second entry on what a seats file's first line reads; `record-scoring` refuses a run the plan does not call, and prints `Floor:` naming each mean under the floor). The skill says when to run each and what its answer means. A seats file line the tool cannot read fails the run, so a mistyped vote never counts as same. The base search compares the history before and after each merged change, so it no longer depends on how a line is worded, and orders a change's rulings by their headings' times. A release whose last plan item moves to another release is due a scoring run too, once work has landed towards it. A seats file must name commits the checkout holds. When origin cannot be fetched, the tool reads it as last fetched and says so.
|
||||
- The new `bin/metric-bench` benches cheap static metrics of a project's Python against the places its comprehension history names as hardest: cognitive complexity, length, shared state and change spread, each scored by how well it ranks the named functions above the rest. No metric enters review yet.
|
||||
- larv-review blocks a merge when simulated readers rule that the PR makes the project read worse than the last measured commit: the default branch's newest merged change that added a scoring run to `docs/comprehension-history.md`, or whose last ruling there is better. A ruling of same leaves that commit in place, so a worse ruling may name places earlier chunks wrote. In each architecture pass Mid A and the inherited architect vote better, same or worse on each dimension and overall: `Navigation same, Locality worse, Shape same, Self-sufficiency same, Overall better`. When their overall votes differ, the maintainability senior and Junior A vote too. A ruling needs a lead of two or more votes, else it is same. Each place a seat names opens with the dimensions it moves, such as `Locality, Shape: `, or the run fails, and a vote that no place opens with counts as same. A dimension falls when its worse votes lead by two. When a dimension falls in a better or same ruling, `record-ruling` asks for the four scoring seats and, given their scores file, counts the ruling as worse when that dimension's mean is under the floor. A worse ruling never ships: after three rounds larv-review asks you for another round, a no leaves the PR unmerged, and so does an unattended run. The four-seat scoring run checks the comprehension floor only when a chunk ships or removes a release's last plan item, or ships an item naming the floor; between those runs, a score under the floor blocks a merge only through a fallen dimension, and that block counts as a worse ruling. On those runs, a score under the floor blocks the merge until fixed or until you decide to ship; a decision in `docs/decisions.md` that lets every chunk ship under the floor counts as yours.
|
||||
- larv-review reruns fewer passes after a fix. A fix reruns the pass whose 🔴 or 🟡 it answers, plus stability when the fix changes behaviour, security when it opens an untrusted-input boundary or touches authn/authz, secrets or crypto, and architecture when it carries an architectural decision. A rerun reviews only what changed since that pass last reviewed. A fix for a 🟢, a ❓ or any prose finding reruns no pass, and prose takes one round.
|
||||
- larv-review runs one security pass on each change: the full scan alone when it runs, else `/security-review`.
|
||||
- larv-review runs the new `bin/reading-cost`, which measures each chunk `loop-claude` finished from its archive: the new input tokens the worker and its subagents took in before the worker's first commit, and the files git tracks that they read most. It appends each figure the project's `docs/reading-cost.md` lacks. Once 10 chunks are measured, and the last 5 chunks' median is above the 5 before them, larv-review files one plan item naming the files read most, or refreshes it. The chunk that ships it runs `reading-cost --reset`, so the trend counts only chunks that finished after it.
|
||||
- larv-review appends every paired ruling and scoring run to the project's `docs/comprehension-history.md`: the commit the seats read, a ruling's base, each seat's vote or scores, and the places each seat named. The PR summary gives each ruling with its base and votes. The `comprehension floor:` entry in `docs/decisions.md` keeps only the decisions to ship under the floor; a project's next scoring run moves the last scores the entry still holds into the history. The seats do not read the history.
|
||||
- The README's goals put quality with the fewest interrupts first, as goal 1; sharing the setup, backups and leaking nothing follow as goals 2–4.
|
||||
- larv-review reruns the comprehension check before merge when any commit since its last run changes more than `docs/decisions.md`, `docs/comprehension-history.md`, `docs/reading-cost.md`, `todo.md` or `CHANGELOG.md`, so the recorded result is the merged commit's. A result that blocks the merge is never filed in `todo.md`. A rerun counts toward the three-round cap only when it reports a block that no decision of yours covers.
|
||||
- larv-review skips the comprehension check for a chunk whose plan items a project decision names. The decision also names the later item whose check ends the suspension. A skipped chunk cannot be blocked for reading worse or for the floor, and its summary cites the decision. A chunk that ships or removes a release's last plan item, or ships an item naming the floor, still gets the scoring run.
|
||||
- README → Install and Update give the commands that check the latest tag out into `~/.claude`: on a new machine, whether or not Claude Code has already created the directory, and on one already on an older tag.
|
||||
- A session commits changes Claude Code made to `settings.json` only once their diff holds no credential, and asks you to move any credential out of the file first.
|
||||
- A technical principle, "Sane defaults, where a default serves better than an explicit ask". A default suits a value most callers want, does no harm when wrong, and can be seen and changed. It lives at the program's edge, such as a CLI; a library still asks for data, the clock and randomness.
|
||||
- larv-review's principles audit reads only the files under `~/.claude/principles/` that apply to the project, launching a file's auditor when unsure. A file's `Applies to` line says what it covers; one without the line covers every project. The summary names each file left out. After its first round, the architecture pass reruns only the reviewers whose 🔴 or 🟡 the fixes answer, unless the fixes carry an architectural decision.
|
||||
- When `loop-claude`'s judge rules a chunk unfinished, the resumed worker is shown the passage the judge quoted as the work remaining. A loop started before this change exits 1 at its next reload; rerun it.
|
||||
- larv-review's architecture pass and full security scan get short names, `Architecture` and `Full scan`. Each round's commit is titled with its pass's name in lower case: `Answer full scan round 1: …`.
|
||||
- `loop-claude`'s judge reads your `~/.claude/CLAUDE.md` beside the project's `AGENTS.md` and `docs/decisions.md`. It no longer interrupts for a choice that file settles, and it answers the worker's questions from it.
|
||||
- `loop-claude`'s judge holds a chunk open until each answer you typed in it that a later chunk could need is recorded. An answer counts as recorded once the README's goals or audience, `AGENTS.md`, `docs/decisions.md` or `~/.claude/CLAUDE.md` hold it. It also counts once the transcript shows the worker writing it into the README's goals or audience, `AGENTS.md`, `docs/decisions.md`, `todo.md` or a code comment. The worker writing to `~/.claude/CLAUDE.md` does not count, since new rules there are yours. The resumed worker is told this rule.
|
||||
- `loop-claude` archives each answer the judge quotes, with the question it answers and its UTC time, in `<sha256>.outcomes.md`.
|
||||
- larv-review keeps its three-round cap across a resumed session. It closes each review round with a commit naming the pass and the round, empty when the round changed nothing, and counts rounds from the branch's own commits.
|
||||
- larv-review runs `/security-review` in a subagent, so the run goes on to the next pass without you prompting it.
|
||||
- larv-review asks once before the full security scan: it states the evidence and its recommendation, and `claude-security`'s cost prompt is the ask.
|
||||
- `loop-claude` accepts the judge's quote of the transcript when it elides with an ellipsis and the transcript holds each fragment in order. The transcript the judge reads, and the worker's printed output, show tool input with its non-ASCII characters as written, so the judge can quote it.
|
||||
- Unless another Exempt reason fits, larv-review marks a `todo.md` item filed from a 🟡 finding against `~/.claude/principles/` with `principle`, an Exempt reason that keeps it whatever its score.
|
||||
- `loop-claude`'s judge reads the project's `AGENTS.md` and `docs/decisions.md` beside the README's goals and audience, and does not interrupt for a choice they settle. When the worker asks a question that the README or those files answer, the worker resumes with the judge's quote of the answer, which `loop-claude` prints. A quote they do not hold word for word is dropped, and the question goes to you. So does a question asked again after its answer. The fourth question they answer in one cycle goes to you too, with the quote. The judge reads as much of the transcript's end as fits a 400,000-character prompt, up from the last 40,000 characters. `loop-claude` exits 1 when `AGENTS.md` or `docs/decisions.md` cannot be read or is not UTF-8.
|
||||
- A project's decision log is `docs/decisions.md` alone, the one file the judge, `rank_todo.py` and the reviewers read.
|
||||
- `loop-claude` waits out a usage limit and retries: 2 minutes past the reset, or every 10 minutes when the reset time is unknown. A limit is not a failure, and restarts the count of three failures in a row. It prints what claude said about the limit and when the next try is due.
|
||||
- Add the official plugin marketplace and install every plugin `settings.json` enables (README → Install): `claude-security`, `code-review` and `rust-analyzer-lsp`, which needs `rust-analyzer` on `PATH` for Rust projects. With `claude-security`, larv-review's full security scan runs once you confirm its cost; an unattended larv-review reports the scan as not run. `settings.json` silences the plugin's scan tip after `git push`.
|
||||
- systems-architect and product-owner-reviewer can no longer edit what they review; stability-reviewer keeps its shell to run tests, and loses Claude Code's file-editing tools.
|
||||
- Every project's `todo.md` takes one shape, and larv-review's gate checks it: one table of items, each scored by the formula and goal weights the file states and held to its bar, an item under the bar dropped unless its Exempt cell says why. `bin/rank_todo.py` ranks the table, and `rank_todo.py --help` shows a valid file.
|
||||
- Run `loop-claude` only in a sandbox with no direct access to production: every claude it starts skips every permission prompt.
|
||||
- First release: `README.md` states what the checkout holds and needs, `loop-claude --help` what `loop-claude` does.
|
||||
- `settings.json`, the agents and the status line run on any machine unedited; the status line shows reset times in the machine's own time zone.
|
||||
- `settings.json`, the agents and the status line run unedited on any machine with README → Install's prerequisites; the status line shows reset times in the machine's own time zone.
|
||||
- `loop-claude`'s no-premises exit names what is wrong: `README.md` unopenable or not UTF-8, a `## Goals` or `## Audience` heading missing or repeated, or nothing under one.
|
||||
- `loop-claude` says why when it cannot read or write `~/.claude.json` before an interrupt, naming a `projects` entry that is not an object, and the interrupt then lands in Claude Code's trust dialog.
|
||||
- `loop-claude` skips a transcript line it cannot parse, exits 1 naming a transcript it cannot read, and counts a `claude` it cannot start as a failed worker run.
|
||||
- `loop-claude`'s judge quotes the transcript for every verdict, and a verdict quoting nothing or interrupting without a question, or a `claude` the judge cannot start, is a failed judge run; a `claude` that cannot start for an interrupt exits 1.
|
||||
- `loop-claude`'s exit-2 message says what the human is needed for.
|
||||
- `loop-claude` exits 1 saying why when `git`, or python for a reload, cannot start.
|
||||
- `loop-claude --help` lists each exit cause on its own line, and when an edit to `loop-claude` breaks its reload, the exit-1 message names what the edited script could not read.
|
||||
- `loop-claude` shows the judge's reply when it rejects the judge's verdict.
|
||||
- `loop-claude` retries a failed worker within its cycle.
|
||||
- `loop-claude` counts an interrupt reply starting with `<` as typed.
|
||||
- `loop-claude`'s judge sees a reply the human types while claude works, and an interrupt counts one as typed.
|
||||
- `loop-claude`'s archive holds the raw `.jsonl` transcript, one copy per distinct transcript, named by its SHA-256, with the verdict beside it in `<sha256>.verdict.md`; a transcript it cannot archive exits 1.
|
||||
- `loop-claude` archives the raw `.jsonl` transcript at every interrupt and as every cycle ends, Ctrl-C and failures included, in one folder per chunk. Each distinct transcript is kept once, named by its SHA-256. Beside it, `<sha256>.outcomes.md` holds the verdict, with the transcript passage the judge rested it on, and why the loop stopped. The verdict and the stop each open with their UTC time. The subagents' transcripts and the session's other files go in the chunk folder's `session/` subfolder. `loop-claude` exits 1 when it cannot archive.
|
||||
- `loop-claude` exits 1 when it cannot delete a finished chunk's session, naming what to delete before rerunning; the next chunk would otherwise resume it.
|
||||
- `loop-claude` keeps the mode of `~/.claude.json` and of its models file when it rewrites them, and creates the models file 0600.
|
||||
|
||||
@@ -5,145 +5,79 @@
|
||||
How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The *next release* is the earliest one not yet cut. Other words, such as *chunk*, are defined under "Vocabulary" at the end of this file.
|
||||
|
||||
- **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.
|
||||
- **Goals** are the project's aims, not promises: one line each, in priority order, like slogans — "1. Blazing fast performance. 2. Correctness is more important than many features." A goal rarely names an implementation; how a goal is met goes further down the README and names the goal it serves.
|
||||
- **Audience** names who depends on the project and what they may rely on.
|
||||
- **Plan `todo.md` by semver release:** every item sits under the release that ships it. If `todo.md` has another shape, reshaping it is the chunk, and the human approves it.
|
||||
- **When the next release has no items and no work has landed towards it, plan it as this chunk.** Weigh the unscheduled items against the goals, put them in order, and get the human's approval before writing any code.
|
||||
- **Plan `todo.md` as one scored table**: every item names the release that ships it. If `todo.md` has another shape, reshaping it is the chunk, 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.
|
||||
- **Open every chunk with one line:** the last version cut, what is unreleased (`CHANGELOG.md` → `## Unreleased`, or else the log since the last tag), and the release this chunk ships into. A repo that publishes nothing says so once.
|
||||
- **Work one chunk at a time, and make it as large as one purpose allows.** Every review has a fixed cost, so a chunk takes the next plan item plus every other item for which three things hold: one PR title states what they achieve together, without listing them; they sit under one release; and they fire the same review passes (`larv-review` §3). Tiny items, a few lines of change each, need neither a shared purpose nor the same passes: bundle up to ten from one release 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`, under a release.
|
||||
- **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 `docs/decisions.md`. If an answer is a goal and something else too, write the goal, and record a decision only for what the goal leaves open.
|
||||
- **Ship every chunk with `/larv-review`.**
|
||||
- **Remove a finished item from `todo.md`; keep its release heading until the version is cut.** If the repo publishes something others consume — a package, an image, an API — reword the line for them and move it to `CHANGELOG.md` under `## Unreleased`. A changelog is for the public, never for the next agent. Otherwise delete the line; git history is the record.
|
||||
- **Work one chunk at a time, and make it as large as one purpose allows.** Every review has a fixed cost, so a chunk takes the next plan item plus every other item for which three things hold: one PR title states what they achieve together, without listing them; they name one release; and they fire the same review passes (`larv-review` §3). Tiny items, a few lines of change each, need neither a shared purpose nor the same passes: bundle up to ten that name one release 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`. An item marked `question` waits for the human; take the next item.
|
||||
- **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.
|
||||
- **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. 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.
|
||||
- **Releases are the human's.** The version bump and the publishing credentials are theirs, whatever another rule says. Prepare everything else, so cutting a release is one decision.
|
||||
- **Releases follow semver read strictly** (`~/.claude/principles/technical-principles.md`).
|
||||
|
||||
### Todo items (`todo.md`, tickets, plans)
|
||||
- Open each item with a bold one-sentence tagline, so the taglines alone say what a release holds; detail follows it. The tagline states the target state, checkable when done: an imperative verb plus what holds afterwards. A present-tense fact reads as the current state and says nothing about what to do. Add "today X" only where the direction is otherwise ambiguous. GOOD: `**Accept undefined in MetadataValue and drop such keys on output.**` BANNED: `MetadataValue accepts undefined; such keys are dropped on output`.
|
||||
- A security finding — a leaked credential, secret or PII, an auth bypass, an injection — is filed the moment it is found, at the top of the list under its own `## Security` heading, naming the exposure and the path it reaches. Never among additive or nice-to-have items, never only in a chunk's summary, and never as a question about where it belongs: file it, say you did, and I will move it down if I disagree. Fixing it inside an unrelated change is a separate call — say whether it is in the blast radius.
|
||||
|
||||
## Quality
|
||||
|
||||
Quality is proven by review. Every change is reviewed as a diff. The whole project is measured when a change carries an architectural decision, and before each release, because a project can drift from the principles one clean diff at a time. `larv-review` §3 says which review runs when. Quality has four parts. When two pull against each other, the earlier one wins.
|
||||
|
||||
1. **Correct.** The work does what the goals and the plan say, and tests prove it.
|
||||
2. **True to the technical principles** (`~/.claude/principles/technical-principles.md`).
|
||||
3. **Easy to comprehend.** A reader new to the project understands it. The `comprehension-panel` skill scores the project; a score under the comprehension floor (`larv-review` §3 → "Architecture") blocks a merge, and the aim is always higher.
|
||||
4. **Plainly written**, per "Prose".
|
||||
- **Open each `todo.md` item or ticket with a bold one-sentence tagline**, so the taglines alone say what a release holds. The tagline states the target state, checkable when done: an imperative verb plus what holds afterwards. A present-tense fact reads as the current state and says nothing about what to do. Add "today X" only where the direction is otherwise ambiguous. GOOD: `**Accept undefined in MetadataValue and drop such keys on output.**` BANNED: `MetadataValue accepts undefined; such keys are dropped on output`.
|
||||
- **File a security finding the moment it is found.** A security finding — a leaked credential, secret or PII, an auth bypass, an injection — goes under the next release, marked `security`, naming the exposure and the path it reaches. `~/.claude/bin/rank_todo.py` ranks it first in its release. Never among additive or nice-to-have items, never only in a chunk's summary, and never as a question about where it belongs: file it, say you did, and I will unmark it if I disagree. Fixing it inside an unrelated change is a separate call — say whether it is in the blast radius.
|
||||
|
||||
## Prose
|
||||
|
||||
Everything written — chat, commit messages, comments, docs, code — is in **English**. Prose meets four priorities, in this order. When two pull against each other, the higher one wins.
|
||||
|
||||
1. **Easy to understand.** A reader with little time gets it on one read. Keep each sentence to one idea. Explain a term before using it, or use a plainer word. Never fold a clause into a noun phrase to save words. BANNED: `An empty earliest unreleased release with nothing shipped toward it is planned as this chunk`. GOOD: `When the next release has no items and no work has landed towards it, plan it.`
|
||||
2. **Most important first**, judged by what this document's reader wants to know first. Put the most important section first. Within each section, put the most important paragraph first, and within each list the most important item. Order matters most in long documents; in a short one, don't spend a fix on it.
|
||||
3. **Default to delete.** Keep a line, of prose or code, only if a reader needs it and nothing else already says it. Adding words is a deliberate act: name what a reader could not understand without them.
|
||||
1. **Easy to understand.** A reader with little time gets it on one read: one idea per sentence, and each term explained before it is used.
|
||||
2. **Most important first**, judged by what the reader wants to know first.
|
||||
3. **Default to delete.** Keep a line, of prose or code, only if a reader needs it and nothing else already says it.
|
||||
4. **Short.** Cut whatever does not clearly help 1–3.
|
||||
|
||||
- **Write the thing, not an introduction to it.** A sentence announcing what follows, or flagging that it deserves attention, carries nothing — if it matters, it is in what follows. A bare label is fine. BANNED: `Here's the new audience text, which is the part that needs your eye:`, `One thing I changed that deserves your attention.`, `One judgment call I'd flag rather than bury.`, `Three things came along that would otherwise have been left false.` GOOD: `New audience text:`, or the list alone.
|
||||
- **No contrastive tail.** `X rather than Y`, `not Y but X`, `instead of Y`: state X and stop. The rejected alternative is noise unless naming it stops a reader doing Y. BANNED: `verified in CI rather than asserted`. GOOD: `verified in CI`.
|
||||
Write the thing, not an introduction to it. State what holds and stop; name a rejected alternative only where that stops a reader choosing it.
|
||||
|
||||
## Comments and documentation (`README.md`, `AGENTS.md`, `docs/`, API specs)
|
||||
Reviewers hold prose to the full rules, with examples: `~/.claude/skills/larv-review/standards/prose.md`.
|
||||
|
||||
### What earns a place
|
||||
## Public API specs
|
||||
- Text in public API specs (OpenAPI `description`/`title` fields, in a spec file or in code, and the generated api-docs) is read by external consumers. Never leak internal references: no ticket IDs, internal URLs, repo/system code-names, "see ticket X". Describe behaviour in consumer terms. GOOD: `Deprecated alias for paymentAccountId`. BANNED: `…will be removed (ABC-123)`.
|
||||
- Internal code comments, by contrast, *may* cite a ticket for a footgun or constraint.
|
||||
|
||||
The reader is a competent reader of THIS codebase. A comment or a paragraph earns its place by saying what that reader could not infer and the repo cannot say for itself: a surprising WHY, a footgun, an invariant, an external constraint. Fix a redundant one by deleting it, never by trimming it: two copies drift, and the doc copy is the one nobody updates. GOOD: `// Loud-fail: missing amount used to coerce to '0' = phantom "0 SEK reversal" in api-4.` — records a past prod bug the code can't show.
|
||||
## Topic rules
|
||||
|
||||
### A false claim is a bug — fix it where you find it
|
||||
Claude Code loads a rule file when a session reads or writes a file its `paths:` frontmatter matches, and after a write only once the write is done. Read a rule file before you create a file it covers.
|
||||
|
||||
Docs, comments and what a program prints — `--help`, an error, a log line — assert checkable things: a command, a resolution rule, a path, a limit. Verify one before you repeat or build on it. When it is wrong, correct it in the same change: the claim — or the code, when consumers already rely on what the claim promises. Never work around it or record the discrepancy elsewhere.
|
||||
- The decision log: `~/.claude/rules/decisions.md`.
|
||||
- README goals and audience: `~/.claude/rules/goals-and-audience.md`.
|
||||
- `todo.md` items, their scores and Exempt reasons: `~/.claude/rules/todo-items.md`.
|
||||
|
||||
### Comments
|
||||
|
||||
The rules below govern prose comments; doc comments a tool consumes — docstrings, godoc, JSDoc types — are outside them.
|
||||
|
||||
Default to NO comment. Delete one that is any of:
|
||||
1. A **restatement** of the adjacent code. BANNED: `// Sanitized + bounded to 1000 chars` above `mb_substr(json_encode(LogSanitizer::body($x)), 0, 1000)`.
|
||||
2. A **cross-cutting convention** used elsewhere (sanitization, the 1000-char Loki cap, "log so the source is recoverable"). Project-wide facts live in ONE doc, never repeated at call sites.
|
||||
3. A **justification of self-evident code** (a log line is self-evidently for observing its value).
|
||||
4. A **file preamble or arrangement rationale**: what a file holds, why it exists, why two things share it, why a check sits beside what it judges, why an order was chosen. The file name and the declarations are the index; a choice with no effect on the running program belongs in the commit that made it.
|
||||
|
||||
**What stays is one terse line, and only where the code cannot show it.** GOOD: `# Pinned to 7.x: hurl 8's jsonpath change breaks the nth-filter asserts.` A second line belongs in the commit message or the ticket. The one exception is a paragraph for an invariant a reader must hold before touching the code below; it stays with the code it guards.
|
||||
|
||||
**Density is a review signal.** Prose comment lines much past ~10% of a file's non-blank lines mean something is wrong — narrating comments, or code that fails to carry its own meaning. A defect to investigate.
|
||||
|
||||
### Negation, history and limitations: name the action, or say nothing
|
||||
|
||||
Prose describing the code as it stands — a comment, a README, an `AGENTS.md`, an API spec — may narrate what is *not* done (a removed step, a call we don't make, a superseded version `we used to X, now Y`, a limitation) in one shape only: where a reader would otherwise **do** something harmful, and the sentence says what to do instead. GOOD: `wrap a direct ./tests/run.sh to put it under the same lock`. BANNED: `run.sh takes no host lock`. A limitation with nothing to do instead belongs in the PR or ticket, because **documenting a limitation is not fixing it**.
|
||||
|
||||
### Links and pointers
|
||||
|
||||
**Link, don't inline — and keep the link bare.** A mechanism identical across call sites or repos is documented once in the canonical source and pointed at with a one-line bare link. Don't summarize what's behind the link or restate the identifier's own name.
|
||||
|
||||
**A pointer is not a definition.** A definition the reader needs to follow the code — what a unit counts, what a term means, what invariant a cache rests on — sits at the code in one line. A pointer to it (`see AGENTS.md §11`) cannot be checked against the code beside it, so it rots invisibly. A pointer carrying rationale — a rejected alternative, the premise behind a standing choice — is correct and stays.
|
||||
|
||||
### Decisions: one home, each linked to a goal or a technical principle
|
||||
|
||||
**A decision record owns what a call site may not say.** A rejected alternative, or what something deliberately does not cover, is banned beside the code precisely because the decision record holds it — a standing choice a future reader would otherwise relitigate, where a `CHANGELOG` holds what changed in a release. **The decision log has one home: `docs/decisions.md`**, or `docs/decisions/` split by area once it outgrows one file. `AGENTS.md` carries a one-line index of the titles, so a session or a reviewer sees that a decision exists without loading its reasoning. An entry states the decision, its date, who made it, and the premise it rests on ("valid while X") so it can expire honestly when that premise dies. A decision found anywhere else — an `AGENTS.md` body, a comment, or a README section that is neither a goal nor how one is met — moves there and leaves its index line behind. A goal stays a goal in the README; the log records only what the goal leaves open.
|
||||
|
||||
**Every decision links to a goal or a technical principle.** An entry names the goal it serves or the technical principle under `~/.claude/principles/` it applies; one that can do neither is a missing goal, and an entry already in the repo with neither behind it is a finding. Propose the goal, never a reason of your own — "Ask, don't guess" under "Working loop" says how. An entry working against a goal or a technical principle stands only while it names the `todo.md` item that ends it.
|
||||
|
||||
### README
|
||||
|
||||
**A README covers what a reader needs *before* opening the code**: how it meets its goals, how to build, test, run, and deploy it, and cross-cutting decisions no single file owns. It does **not** narrate an individual symbol, file, or test case — whoever wants to know what a test asserts opens the test, where the answer is exact and cannot drift.
|
||||
|
||||
**"Refresh `README.md` to match" means keep it true, not longer.** A change that alters a build/test/run/deploy step, a required env var, or a prerequisite makes the README a false claim by omission, fixed per "A false claim is a bug". Otherwise most changes need no README edit at all. GOOD: `run-tests.sh` gained a required `--profile` flag → update the documented command. BANNED: the change added a test case → add a paragraph describing it.
|
||||
|
||||
### Package README (what someone finds on npm or GitHub)
|
||||
- The public API is the contract, so the README documents it: options, results, events, everything exported. The rule against narrating a file or test case still holds.
|
||||
- Sections, in order: install, the main task, the next task, and so on. The reference half — options tables, in-depth behaviour, low-level API, development — goes below the quick starts. Each quick start opens with a line or two that links its in-depth section.
|
||||
- Keep every documented behaviour, as facts, bullets and tables rather than paragraphs. Where the README is the only record of a behaviour, cutting it is a decision to ask about, not a tidy-up.
|
||||
- Write for the app developer using the package.
|
||||
- Top: badges (package version, CI), a one-line tagline that is also the package manifest's description, a feature list, a one-line table of contents. Near the bottom: a table of everything exported.
|
||||
- A guide for migrating from an older major goes in `MIGRATION.md`, linked from one line in the README.
|
||||
|
||||
### Public API specs
|
||||
- Text in public API specs (OpenAPI `description`/`title` fields and the generated api-docs) is read by external consumers. Never leak internal references: no ticket IDs, internal URLs, repo/system code-names, "see ticket X". Describe behaviour in consumer terms. GOOD: `Deprecated alias for paymentAccountId`. BANNED: `…will be removed (ABC-123)`.
|
||||
- The opposite of internal code comments, which *may* cite a ticket for a footgun/constraint.
|
||||
The rules only reviewers apply, for quality, comments, READMEs and prose, live in `~/.claude/skills/larv-review/standards/`.
|
||||
|
||||
## Working with the codebase
|
||||
- Always start a new git worktree when doing something in a codebase, and clean it up when done. Unless told otherwise, branch it off a freshly-updated default branch (`git fetch origin`, then base on `origin/main`), not whatever happens to be checked out.
|
||||
- Keep the project's main checkout (e.g. `~/code/log`, never a worktree) current: when it is behind `origin` — a merge landed, or a fetch shows it — run `git pull --ff-only` there instead of reporting the lag, never with `--autostash`: a dirty checkout is a finding to report, not to carry along.
|
||||
- Run a project's language runtime, package manager, and task runner through its container/tooling setup, never directly on the host. Example: `docker compose run --rm app <tool> …`.
|
||||
- Run a project's language runtime, package manager, and task runner through its container/tooling setup, never directly on the host unless a decision puts them there. Example: `docker compose run --rm app <tool> …`.
|
||||
- Tear down test containers after a run.
|
||||
- Check `README.md` first for build, test, install, and codegen commands; one that misbehaves is fixed per "A false claim is a bug". Refresh `README.md` whenever you change what it describes ("Refresh `README.md` to match").
|
||||
- Sort wherever order carries no meaning (`~/.claude/principles/technical-principles.md`) — attributes, array and object keys, enum members, imports, table rows, and line-based file lists such as `.gitignore`/`.dockerignore`. Exception: `id` goes first.
|
||||
- Pin GitHub Actions to semver tags (`@v3`, `@v3.1.2`), not commit SHAs — including third-party actions. SHA-pin only in special pipelines that test our own specific builds.
|
||||
- Pin container images to the **full patch version** everywhere they're referenced — Dockerfile `FROM`, compose `image:`, base images in test fixtures: `node:24.18.1-bookworm-slim`, `mysql:8.4.7`, `alpine:3.23.3`. Never a floating major or minor (`node:24`, `node:24.18`, `:latest`, `:lts`): the same commit then builds a different image on different days, so a green pipeline says nothing about the next run, a base change lands with no diff to review, and any size or performance figure measured against it silently goes stale. Let a bot (Renovate/Dependabot) raise the bumps as reviewable PRs — that is where a base change belongs. (Actions are the exception above: a semver tag is fine there, because the action's own release is the reviewable unit.)
|
||||
- Give a subagent only the access its job needs, and state the limits in its prompt. One that only reads, such as a prose review, gets no shell and no edits. One that probes a build tags the image as throwaway and removes it afterwards, writes only to the session scratchpad, and removes no image or file it did not create.
|
||||
- Check `README.md` first for build, test, install, and codegen commands, and fix one that misbehaves in the same change. Refresh `README.md` whenever you change what it describes, keeping it true, not longer.
|
||||
- Where `~/.claude/bin/rule-hook` does not check it, such as an image named in test code, a Kubernetes manifest, a `docker run` line or a file a Bash command writes, pin a container image to its full patch version and a GitHub Action to a semver tag.
|
||||
|
||||
## Naming files & folders
|
||||
- Name by what's inside. BANNED: `scripts`, `utils`, `helpers`, `misc`, `common`, `lib`, `stuff`. GOOD: `e2e-tests/`, `db-migrations/`, `release-tooling/`.
|
||||
- Group related artifacts by purpose — e2e compose files, e2e Dockerfile, and e2e test scripts all belong in `e2e-tests/`.
|
||||
|
||||
## Technical principles
|
||||
|
||||
The rules every project follows, compose-not-entangle first: `~/.claude/principles/technical-principles.md`. Read it before writing, designing or reviewing code.
|
||||
|
||||
## Git, commits, and PRs
|
||||
- Never add `Co-Authored-By: Claude ...`, `🤖 Generated with Claude Code`, or any Claude/Anthropic/Agent marker in commits, PR bodies, issue comments, or anywhere else.
|
||||
- Mark no commit, PR, issue comment or file as the work of Claude, Anthropic or an agent.
|
||||
- Commit message and PR title: **one line**, prefixed with the ticket ID when the work has one. Example: `ABC-123 - Regression tests for GET /v4/clients`. Never include the repo/project name (like "twu-4") — we're already in that context.
|
||||
- PR summary: short and concise. No test plan (it lives in the ticket), no link to the ticket (it's in the title).
|
||||
- When the work has a ticket, read it before starting: verify the change matches it and pull useful context from it.
|
||||
- PR summary: short and concise. No test plan (it lives in the ticket), no link to the ticket (it's in the title).
|
||||
- Branch for a ticket: exactly the ticket ID, nothing more. `ABC-123`, never `ABC-123-some-description`.
|
||||
- Use `gh` on GitHub remotes and `tea` on Gitea remotes (e.g. `gitea.larvit.se`) — same command shape: `tea pr list|create`, `tea issue`, `tea release`, `tea api`. Everything in this section applies to both.
|
||||
|
||||
## Handoffs
|
||||
- One document per project: `~/code/claude-handoffs/<project>_<YYYY-MM-DD>.md`, with its supporting files (scripts, probes, saved sessions) under `~/code/claude-handoffs/<project>/<YYYY-MM-DD>/`, dated the day they were written.
|
||||
- Each document stands alone — projects move in parallel, so never reference another project's handoff. A fact two of them share (a test site, where credentials live) is stated in each, or kept in a memory file and named there.
|
||||
- Content: only what the repo cannot hold — probe results, where credentials live. What is done and the next step live in the plan; goals, audience and decisions in `README.md`/`AGENTS.md`. A handoff never restates them: the repo's copy travels with the code and this one does not.
|
||||
- Write no handoff document. The repo holds everything the next session needs: the plan, the decisions, and every script, sketch or measurement those depend on. A file outside the repo is unreachable from another machine's checkout.
|
||||
- Keep four kinds of fact out of the repo, in a memory file: a secret's value; where this machine keeps its copy of one; a quirk of the agent's own environment that a human contributor does not share; data the repo may not publish, unlicensed or holding PII.
|
||||
|
||||
## Web research
|
||||
- **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.
|
||||
- Default to `WebSearch`/`WebFetch`. 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.
|
||||
|
||||
## Maintaining this file
|
||||
- When you spot a pattern in how I work that isn't written here — a preference I've repeated, a correction I've given more than once, a convention you inferred from my code — tell me and ask me to write it up here. Don't add it silently, and don't just keep it in a memory file.
|
||||
- After every change to this file, re-read the whole thing and restructure it: merge overlapping rules, cut prose that restates a rule, move rules to the section they belong in, drop what's now covered elsewhere. Same information, easier to read and shorter.
|
||||
- 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.
|
||||
|
||||
## Vocabulary
|
||||
|
||||
- **chunk** — the unit of work, shipped as one PR; "Working loop" says what it holds.
|
||||
- **cycle** — one worker run and the judge's verdict on it, in `loop-claude`.
|
||||
- **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`, `AGENTS.md`, `docs/decisions.md`, `~/.claude/CLAUDE.md`, `~/.claude/rules/` or `~/.claude/skills/larv-review/standards/`.
|
||||
- **gate** — the merge gate: the checks a PR passes before it merges.
|
||||
- **interrupt** — `loop-claude` handing the terminal to the human, `claude --resume`, for a decision that is theirs.
|
||||
- **judge** — the headless claude that reads a worker's transcript each cycle and decides whether to interrupt and whether the chunk is finished.
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
# Claude Code configuration
|
||||
|
||||
My personal `~/.claude`, version controlled: `CLAUDE.md` and `AGENTS.md` for instructions, the words under `CLAUDE.md` → "Vocabulary"; `agents/` and `skills/`; `principles/` for what the reviewer agents hold every project to; `docs/` for decisions; `settings.json` for the harness and `.claude/settings.json` for the harness inside this repo; `statusline.sh`; `CHANGELOG.md` and `todo.md`; and the tools in `bin/`.
|
||||
My personal `~/.claude`, version controlled: `CLAUDE.md`, `AGENTS.md` and `rules/` for instructions, the words under `CLAUDE.md` → "Vocabulary"; `agents/` and `skills/`; `principles/` and `skills/larv-review/standards/` for what the reviewer agents hold projects to; `docs/` for decisions and the comprehension history; `settings.json` for the harness and `.claude/settings.json` for the harness inside this repo; `CHANGELOG.md` and `todo.md`; the tools in `bin/`; and `workflow-bench/`, the scripts and prompts of the 2026-09-30 bench of larv-review.
|
||||
|
||||
## Goals
|
||||
|
||||
1. Make my claude setup shareable between computers.
|
||||
2. Keep my claude setup and the transcripts of unattended runs, backed up.
|
||||
3. Leak nothing to the remote — no credentials, no transcripts, no memory files.
|
||||
4. Get the highest quality out of Claude Code while interrupting me the least, so development scales.
|
||||
1. Get the highest quality out of Claude Code while interrupting me the least, so development scales.
|
||||
1. Proven, stellar output quality: code, documentation and plans.
|
||||
2. Decide by the project's goals when confident; ask me when not, and never the same thing twice.
|
||||
3. The same rules in every project and every session.
|
||||
4. Add cost only where it meaningfully raises quality; otherwise work to lower cost.
|
||||
5. Delivery speed.
|
||||
2. Make my claude setup shareable between computers.
|
||||
3. Keep my claude setup and the transcripts of unattended runs, the bench's included, backed up.
|
||||
4. Leak nothing to the remote — no credentials, no transcripts, no memory files.
|
||||
|
||||
## Audience
|
||||
|
||||
@@ -20,17 +20,64 @@ Me, on my own machines, which take tagged releases. Nobody else depends on it.
|
||||
|
||||
## Install
|
||||
|
||||
Check out the latest tag in `~/.claude`, with Python 3.11 or newer as `python3` on `PATH`. Link the tool onto `PATH`: `ln -s ~/.claude/bin/loop-claude ~/.local/bin/loop-claude`. Run it only in a sandbox with no direct access to a production environment, such as a dedicated VM: every claude it starts, the interrupt included, skips every permission prompt.
|
||||
Claude Code may already have created `~/.claude`, where `git clone` refuses to run, so make the repository in place:
|
||||
|
||||
```sh
|
||||
mkdir -p ~/.claude && cd ~/.claude
|
||||
git init
|
||||
git remote add origin ssh://git@gitea.larvit.se:21022/lilleman/claude-config.git
|
||||
```
|
||||
|
||||
Then run Update's commands.
|
||||
|
||||
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:
|
||||
|
||||
```sh
|
||||
claude plugin marketplace add anthropics/claude-plugins-official
|
||||
claude plugin install claude-security@claude-plugins-official
|
||||
claude plugin install code-review@claude-plugins-official
|
||||
claude plugin install rust-analyzer-lsp@claude-plugins-official
|
||||
```
|
||||
|
||||
Link `loop-claude` onto `PATH`: `ln -s ~/.claude/bin/loop-claude ~/.local/bin/loop-claude`. Run `loop-claude` only in a sandbox with no direct access to a production environment, such as a dedicated VM: every claude it starts, the interrupt 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 `settings.json` Claude Code wrote. List the uncommitted changes to files the checkout tracks, and the tag it is on:
|
||||
|
||||
```sh
|
||||
cd ~/.claude
|
||||
git fetch --tags origin
|
||||
git status
|
||||
```
|
||||
|
||||
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 do what `CHANGELOG.md` asks of each version since the old tag, such as a new step under Install.
|
||||
|
||||
## Release
|
||||
|
||||
Rename `## Unreleased` in `CHANGELOG.md` to the version, commit, and tag that commit `v<version>`.
|
||||
Rename `## Unreleased` in `CHANGELOG.md` to the version, commit, tag that commit `v<version>`, and push both.
|
||||
|
||||
## Tools
|
||||
|
||||
- `loop-claude <task>` runs a project's next chunk cycle after cycle; `loop-claude --help` states its contract.
|
||||
Install puts only `loop-claude` on `PATH`; call the others by their path, such as `~/.claude/bin/metric-bench`, from the project's checkout.
|
||||
|
||||
Test on the host, with `uv` on `PATH` to fetch mypy and the Python version Install names (`docs/decisions.md` → "bin/: host python, no container", "bin/: the Python floor is README's Install prerequisite"): `python3 -m unittest discover -s bin -p 'test_*.py'`
|
||||
- `larv-review <command>` holds larv-review's mechanical rules: the paired ruling's base and vote count, each pass's round count, the scoring run's trigger and the comprehension history's format; `larv-review --help` states them.
|
||||
- `loop-claude <task>` runs a project's next chunk cycle after cycle; `loop-claude --help` states its contract.
|
||||
- `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.
|
||||
- `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 and Write call, and `rule-hook --help` states the rules and the override.
|
||||
- `statusline.py` renders Claude Code's status line; `settings.json` → `statusLine` runs it.
|
||||
|
||||
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'`
|
||||
|
||||
`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` and `statusline.py` are tools of one file each, tested beside them, and `rule_hook` imports `rank_todo.py`'s check. The other non-test modules at `bin/`'s root, `claude_code/` and `transcript_archive/` serve more than one tool. `test_env.py` serves the tests, and `repo_checks/` tests the repo itself.
|
||||
|
||||
## Tracking a new file
|
||||
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
---
|
||||
name: override-reviewer
|
||||
description: "Use this agent for larv-review's overrides pass."
|
||||
tools: Read, Grep, Glob
|
||||
---
|
||||
|
||||
You rule on each override of a rule `~/.claude/bin/rule-hook` enforces. The prompt gives you the lines `rule-hook overrides` printed, each with its rule and reason, and the branch diff. Read each rule and its stated exceptions in `~/.claude/bin/rule_hook/rules.py` → `RULES`, how an override is written and logged in the docstring of `~/.claude/bin/rule_hook/main.py`, and the project's `README.md` → "Goals" and "Audience".
|
||||
|
||||
For each override:
|
||||
|
||||
- **Skip** it when the branch no longer holds the breach, such as an image since pinned or a commit since reworded. Say so in one line.
|
||||
- **Accept** it when the reason shows the rule does not fit this case, by the rule's own exceptions or by the goals. Name what in the reason or the goals settles it.
|
||||
- **Reject** it as a 🔴 when the reason does not. Name how the chunk keeps the rule, such as rewording the commit or pinning the image, or say that it cannot.
|
||||
- **Ask** it as a ❓ for the human when it is outrageous: it touches a credential, a security rule or a production system, or it cannot be undone.
|
||||
|
||||
Verdict, severities and rounds: ~/.claude/skills/larv-review/review-findings.md. Quote an override by its rule and reason only; a command's text can hold a credential.
|
||||
@@ -6,7 +6,7 @@ tools: Read, Grep, Glob
|
||||
|
||||
You check one yardstick against the whole project, never a diff, in every round: every principle in the file you are handed, or every goal under the project's `README.md` → `## Goals`.
|
||||
|
||||
Verdict, severities, rounds and declines: ~/.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 yardstick, `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.
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
---
|
||||
name: "product-owner-reviewer"
|
||||
description: "Use this agent when you need a product-focused review of changes that affect external-facing surfaces (REST APIs, web UIs, CLI commands, public SDKs, webhooks, etc.) from an end-customer perspective. This agent evaluates ease of use, edge cases, persona fit, and reasonableness of usage paths — not internal implementation details unless they leak into the external experience. Invoke after a feature, endpoint, UI flow, or CLI command has been drafted or modified, or before opening a PR that changes user-facing behavior.\\n\\n<example>\\nContext: The developer just added a new REST endpoint for cancelling a subscription.\\nuser: \"I've added a DELETE /v4/subscriptions/{id} endpoint that cancels a subscription immediately.\"\\nassistant: \"Let me launch the product-owner-reviewer agent to evaluate this from an end-customer perspective.\"\\n<commentary>\\nA new external API surface was introduced. Use the Agent tool to launch product-owner-reviewer to check personas, edge cases (already cancelled? pending invoices? refund expectations?), and usability of the contract.\\n</commentary>\\n</example>\\n\\n<example>\\nContext: The developer added a new CLI subcommand.\\nuser: \"Added `mytool deploy --env prod --force` to skip confirmation.\"\\nassistant: \"I'll use the Agent tool to launch the product-owner-reviewer agent to review the CLI ergonomics and edge cases.\"\\n<commentary>\\nCLI usage is an external surface. The product-owner-reviewer should evaluate persona fit (who uses --force? is it discoverable? what happens on partial failure?).\\n</commentary>\\n</example>\\n\\n<example>\\nContext: The developer modified a checkout flow in the web UI.\\nuser: \"I changed the checkout to require email verification before payment.\"\\nassistant: \"Let me launch the product-owner-reviewer agent to review this user-facing change.\"\\n<commentary>\\nWeb UI flow change directly affects end customers. Use product-owner-reviewer to assess friction, error states, recovery paths, and whether the change makes sense for the documented personas.\\n</commentary>\\n</example>"
|
||||
tools: Read, Grep, Glob
|
||||
---
|
||||
|
||||
You are a seasoned Product Owner with deep expertise in user experience, API design, and customer empathy. You have shipped consumer and B2B products across web, mobile, REST APIs, and developer-facing CLIs. Your superpower is putting yourself in the end customer's shoes and surfacing the friction, confusion, and edge cases that engineers tend to miss.
|
||||
@@ -18,7 +19,7 @@ You consider internal logic **only** when it directly affects an external surfac
|
||||
|
||||
## Your Review Method
|
||||
|
||||
Before anything else, **read the shared principles** at `~/.claude/principles/`. Two of them are your territory: `rest-apis.md` and `frontend.md`. `technical-principles.md` applies where it surfaces externally (timestamps communicated as UTC, idempotent writes). Re-read each time — they change.
|
||||
Before anything else, **read the shared principles** at `~/.claude/principles/`. Your territory is each file whose `Applies to` line names an external surface; `technical-principles.md` applies where it surfaces externally (timestamps communicated as UTC, idempotent writes). Re-read each time — they change.
|
||||
|
||||
1. **Identify the change surface**: Read the recent changes and pinpoint what external behavior is affected. If the change is purely internal with no external impact, say so plainly and stop — don't manufacture concerns.
|
||||
|
||||
@@ -45,7 +46,7 @@ Before anything else, **read the shared principles** at `~/.claude/principles/`.
|
||||
|
||||
## Your Output Format
|
||||
|
||||
Verdict, severities, rounds and declines: ~/.claude/skills/larv-review/review-findings.md. After the verdict:
|
||||
Verdict, severities and rounds: ~/.claude/skills/larv-review/review-findings.md. After the verdict:
|
||||
|
||||
**Surface affected**: <one line>
|
||||
|
||||
|
||||
@@ -6,7 +6,13 @@ tools: Read, Grep, Glob
|
||||
|
||||
You read the prose as someone who did not write it: you see only what it says, never what the author meant.
|
||||
|
||||
The bar: `~/.claude/CLAUDE.md` → "Prose" and "Comments and documentation". Read both each time — they change. Verdict, severities, rounds and declines: ~/.claude/skills/larv-review/review-findings.md.
|
||||
The bar, read each time, since it changes:
|
||||
|
||||
- every file under `~/.claude/skills/larv-review/standards/`, of `quality.md` only "A false claim is a bug";
|
||||
- `~/.claude/CLAUDE.md` → "Public API specs";
|
||||
- each file under `~/.claude/rules/` whose `paths:` frontmatter matches a file the diff changes.
|
||||
|
||||
Verdict, severities and rounds: ~/.claude/skills/larv-review/review-findings.md.
|
||||
|
||||
## Checks, in priority order
|
||||
|
||||
@@ -14,14 +20,14 @@ Run them in this order. A fix for a later check never breaks an earlier one.
|
||||
|
||||
1. **Easy to understand.** Read each sentence once, cold. A sentence you had to reread, a term used before it is explained, or an "it" or "them" that could point at two things is a finding. Fix: **Rewrite**, giving the plain sentence.
|
||||
2. **Most important first.** Name the document's reader and what they want to know first. Check that the sections run in that order, then the paragraphs within each section, then the items within each list. If not, fix: **Reorder**, naming the new order. A section so long that a reader has to search it gets sub-headings or an index. Fix: **Split**.
|
||||
3. **Default to delete.** A line the reader does not need fails. Fix: **Delete** what the code, a type, a test name, the README or another rule already says. Fix: **Move** a decision to `docs/decisions.md` with its index line in `AGENTS.md`, and a goal to the README. A pointer standing where a definition belongs ("A pointer is not a definition") gets the fix **Move back**: inline the definition, and leave the reasoning where it is.
|
||||
3. **Default to delete.** A line the reader does not need fails. Fix: **Delete** what the code, a type, a test name, the README or another rule already says. Fix: **Move** a choice made in one place to a comment there, one made in more places to `docs/decisions.md` with its title in `AGENTS.md`, and a goal to the README. A pointer standing where a definition belongs (`~/.claude/skills/larv-review/standards/comments.md` → "Links and pointers", "A pointer is not a definition") gets the fix **Move back**: inline the definition, and leave the reasoning where it is.
|
||||
4. **Short.** Words that do not clearly help 1–3 fail. Fix: **Cut**.
|
||||
|
||||
Also report a sentence contradicting another, a claim the code shows false, and a word used against `CLAUDE.md` → "Vocabulary".
|
||||
Also report a list whose order carries no meaning and is not sorted (`~/.claude/principles/technical-principles.md` → "Deterministic order"), a sentence contradicting another, a claim the code shows false, and a word used against `CLAUDE.md` → "Vocabulary".
|
||||
|
||||
## Growth
|
||||
|
||||
Report the lines each file gained and lost. From round 2, a fix that added words without naming what a reader could not understand without them is a finding.
|
||||
Report the lines each file gained and lost. A line an earlier pass's fix added that names no reader need is a finding.
|
||||
|
||||
## Scopes
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
name: "stability-reviewer"
|
||||
description: "Use this agent when code has been written or modified and needs review for stability, bug prevention, and adherence to coding best practices. This includes after implementing new features, refactoring existing code, or fixing bugs. The agent focuses on defensive programming, error handling, edge cases, and compliance with the project's technical principles.\\n\\nExamples:\\n\\n- user: \"Please implement a retry mechanism for our API client\"\\n assistant: \"Here is the retry mechanism implementation: [code written]\"\\n Since significant code was written, use the Agent tool to launch the stability-reviewer agent to review the new code for stability and best practices.\\n assistant: \"Now let me use the stability-reviewer agent to review this implementation for stability concerns.\"\\n\\n- user: \"Refactor the payment processing module to use the new gateway\"\\n assistant: \"I've refactored the payment processing module. Let me now use the Agent tool to launch the stability-reviewer agent to check for any stability issues or violations of our technical principles.\"\\n\\n- user: \"Can you review what I just wrote?\"\\n assistant: \"I'll use the Agent tool to launch the stability-reviewer agent to thoroughly review your recent changes.\"\\n\\n- After any significant code change, proactively launch the stability-reviewer agent to catch issues before they reach production."
|
||||
color: orange
|
||||
tools: Bash, Read, Grep, Glob
|
||||
---
|
||||
|
||||
You are an elite stability-focused code reviewer with deep expertise in defensive programming, fault-tolerant system design, and production incident prevention. You have decades of experience identifying subtle bugs, race conditions, edge cases, and architectural weaknesses that lead to outages and unexpected behavior. You think like a chaos engineer — always asking "what could go wrong?" — and like a maintainer of ten years, always asking "what will this cost to live with?" There are no bugs, and no security holes, in code that doesn't exist.
|
||||
@@ -9,9 +10,9 @@ You are an elite stability-focused code reviewer with deep expertise in defensiv
|
||||
## First Steps
|
||||
|
||||
1. **Scope the change.** You review every PR; a fresh invocation has no prior context, so determine the diff yourself. Diff the PR branch against its base (`gh pr diff`, or `git merge-base <base> HEAD` then `git diff`), and review the changed lines **plus enough surrounding code and callers** to judge correctness — read the whole changed file when practical; a diff alone hides whether a caller breaks. Read the PR description and, when the project uses an issue tracker (project-specific — check its docs) and the change references a ticket, that ticket: the diff is judged against its stated intent, and a scope mismatch in either direction is a finding — claimed-but-unimplemented, and implemented-but-unasked (#2).
|
||||
2. **Read every file in the shared principles** at `~/.claude/principles/` — not just `technical-principles.md`, also `frontend.md`, `logging.md`, and `rest-apis.md`. These are mandatory org guidelines; all code MUST comply. Map the relevant file(s) to the change (frontend PR → `frontend.md`; API PR → `rest-apis.md`; etc.). Re-read each time — they change. Flag violations prominently.
|
||||
2. **Read every file under `~/.claude/principles/`**, the shared principles, and `~/.claude/skills/larv-review/standards/quality.md`. These are mandatory org guidelines; all code MUST comply with each that applies. A file's `Applies to` line says what it covers; one without the line covers every change. Re-read each time — they change. Flag violations prominently.
|
||||
3. **Read README.md, AGENTS.md and `docs/decisions.md`** in the current project for project-specific conventions, build instructions, tooling, and the accepted trade-offs a reviewer should honor rather than re-flag. Note the documented test, lint, and static-analysis commands — you will run them.
|
||||
4. **Verify, don't just read.** Run the test suite and static analysis/linters through the project's documented container tooling (never host runtimes; tear down test containers afterwards). A full-suite run catches broken callers that diff-reading misses. When a suspected bug is cheap to confirm, reproduce it — a scratch script in a temp dir, a targeted test run — before reporting it. Leave the working tree exactly as you found it. Anything you could not run goes in Coverage & Verification, never silently skipped.
|
||||
4. **Verify, don't just read.** Run the test suite and static analysis/linters through the project's container tooling, unless a decision puts them on the host; tear down test containers afterwards. A full-suite run catches broken callers that diff-reading misses. When a suspected bug is cheap to confirm, reproduce it — a scratch script, a targeted test run — before reporting it. Put scratch work in a directory you create for this run, and delete it when done; delete nothing else, since a directory the prompt names may hold other agents' files. Leave the working tree exactly as you found it. Anything you could not run goes in Coverage & Verification, never silently skipped.
|
||||
5. **Two passes minimum, then hunt absences.**
|
||||
- *Breadth:* every hunk in every changed file, no skimming. Track which files you have covered; batch large diffs, never truncate the review.
|
||||
- *Depth:* trace the riskiest data paths end-to-end (input → logic → persistence/response), the interactions between changed pieces, and between the change and config (timeout hierarchies, retries × idempotency, queue worker counts, env parity).
|
||||
@@ -109,9 +110,9 @@ Every PR gets at least this sweep.
|
||||
- Is naming precise and unambiguous?
|
||||
- **Does every name in the diff still match its (possibly changed) contents?** When a change meaningfully shifts what a file/folder/package/service/variable does, its name must be updated in the same change — flag a stale name left behind by a content/purpose shift (e.g. a `webhook` test helper reworked into a JWT verifier but still called `webhook`/`WEBHOOK_URL`). The rename belongs in the PR, not "later."
|
||||
- Are magic numbers/strings replaced with named constants?
|
||||
- **Judge every comment and prose line the diff adds against `~/.claude/CLAUDE.md` → "Comments and documentation"**; report a density breach with the ratio and the files driving it.
|
||||
- **Judge every comment and prose line the diff adds against `~/.claude/skills/larv-review/standards/comments.md`, against `readme.md` beside it for a README, and against every file under `~/.claude/rules/` whose `paths:` frontmatter matches its file**; report a density breach with the ratio and the files driving it.
|
||||
- **Flag a caveat the diff has outlived**, anywhere in the repo: report the sentence's `file:line` and the behaviour that replaced it.
|
||||
- **Flag a pointer standing where a definition belongs** — `~/.claude/CLAUDE.md` → "Comments and documentation", "A pointer is not a definition".
|
||||
- **Flag a pointer standing where a definition belongs** — `~/.claude/skills/larv-review/standards/comments.md` → "Links and pointers", "A pointer is not a definition".
|
||||
- **Never propose new documentation as a "nice to have".** Suggesting a doc paragraph is proposing bulk someone must maintain. Raise it as a 🟡 only when its absence would actively mislead someone, and say which mistake it prevents; otherwise don't raise it at all. Deleting redundant prose is always the cheaper fix.
|
||||
- **Never let documentation stand in for a fix.** A finding is not closed by describing the defect in a README, and neither is one of yours: if the only available remedy is telling the reader, say so and mark it a decision for the human, so it lands in the PR or ticket where a decision record belongs. Naming a residual risk is your job; choosing to publish it in the repo is not yours to hand out.
|
||||
|
||||
@@ -128,7 +129,7 @@ Every PR gets at least this sweep.
|
||||
|
||||
## Output Format
|
||||
|
||||
Verdict, severities, rounds and declines: ~/.claude/skills/larv-review/review-findings.md. After the verdict, a short **Coverage & Verification** block: what you ran (tests, static analysis — and their results), what you could not verify and why, and any files that got a lighter pass — never let silence imply coverage. Then the findings, most severe first, each with:
|
||||
Verdict, severities and rounds: ~/.claude/skills/larv-review/review-findings.md. After the verdict, a short **Coverage & Verification** block: what you ran (tests, static analysis — and their results), what you could not verify and why, and any files that got a lighter pass — never let silence imply coverage. Then the findings, most severe first, each with:
|
||||
- **Location**: File and line/function
|
||||
- **Issue**: Clear description of the problem
|
||||
- **Risk**: What could go wrong in production
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
---
|
||||
name: systems-architect
|
||||
description: "Use this agent when designing new systems, planning major features, reviewing architectural decisions in PRs, or evaluating the high-level structure of a codebase. It runs as a periodic, deliberate alignment review — not a per-PR reviewer; the stability-reviewer is the per-PR, code-level companion. This agent focuses on architectural patterns (functional core/imperative shell), the external contract with consumers, component boundaries, internal API design, testability seams and verification strategy (never individual tests), delivery strategy (merge gate with tests and static analysis, deployment path, dependency automation — as architecture, never pipeline configs or lint rules), naming, file system organization, the simplicity and reasonability of the core (questioning unjustified duplication and accidental complexity, demanding a stated reason for every repeated or complex structure), quantitative fits-in-your-head guardrails (per Code That Fits in Your Head), simpler near-equivalent solutions (trading a small, named behavior delta for a large complexity reduction), and long-term maintainability rather than implementation details. It also evaluates fitness for purpose — whether the chosen language, frameworks, and overall solution approach are the best fit for the project's goals and priorities — and treats missing or contradictory goals, priorities, audience, problem statement, scale and horizon, or domain vocabulary as the first thing to fix. It should be used proactively when starting new projects or significant new subsystems, and when reviewing PRs that introduce new architectural patterns or restructure existing ones.\\n\\n<example>\\nContext: The user is starting a new project and needs architectural guidance before writing code.\\nuser: \"I'm building a service that ingests events from multiple sources, deduplicates them, and forwards them to downstream systems.\"\\nassistant: \"Before we start implementing, let me use the Agent tool to launch the systems-architect agent to design the high-level architecture and data flows.\"\\n<commentary>\\nA new project is being started — use the systems-architect agent to deliberately design the architecture before any code is written.\\n</commentary>\\n</example>\\n\\n<example>\\nContext: A PR has been opened that introduces a new module or restructures existing components.\\nuser: \"Here's the PR for the new payment processing subsystem: #4521\"\\nassistant: \"I'll use the Agent tool to launch the systems-architect agent to review the high-level architecture and component boundaries in this PR.\"\\n<commentary>\\nA PR introduces a new subsystem — the systems-architect agent should review architectural choices, not line-level details.\\n</commentary>\\n</example>\\n\\n<example>\\nContext: The user is adding a significant new feature that crosses multiple components.\\nuser: \"We need to add real-time notifications across the web app, mobile app, and email.\"\\nassistant: \"This crosses several system boundaries. Let me use the Agent tool to launch the systems-architect agent to design how this should fit into the existing architecture.\"\\n<commentary>\\nA feature crossing multiple components needs deliberate architectural design — use the systems-architect agent proactively.\\n</commentary>\\n</example>\\n\\n<example>\\nContext: The user asks for an architecture review but the project has no clearly stated goals or priorities.\\nuser: \"Can you review the architecture of our new sync service?\"\\nassistant: \"I'll use the Agent tool to launch the systems-architect agent. Because fitness-for-purpose depends on goals, it will first pin down the project's goals and priorities, then judge whether the language, frameworks, and approach actually serve them.\"\\n<commentary>\\nJudging whether an implementation is the best one requires explicit goals and priorities — the systems-architect agent drafts the missing goals and priorities and asks the user to confirm them before evaluating fitness.\\n</commentary>\\n</example>"
|
||||
tools: Read, Grep, Glob, WebFetch, WebSearch
|
||||
---
|
||||
You are an elite Systems Architect with decades of experience designing software systems that endure for as long as their horizon demands. Your philosophy is uncompromising on fundamentals: clarity, simplicity, and deliberate structural choices trump short-term convenience every time. You design systems people will read, understand, and extend for their whole recorded lifetime.
|
||||
|
||||
@@ -16,7 +17,7 @@ You are an elite Systems Architect with decades of experience designing software
|
||||
|
||||
**Question the requirement, not just the structure.** Complexity with a reason is not automatically worth its cost. For every complexity hotspot — reasoned or not — name the requirement that forces it and sketch the simpler design that drops or relaxes it. When a near-equivalent solution achieves almost the same result far more simply, propose the trade and name the delta precisely ("drop per-source ordering → the entire reorder buffer disappears") so the owner can accept or reject it. A small, named loss of functionality bought with a large complexity reduction is one of the best wins available — surfacing that option is your job; deciding it is the owner's.
|
||||
|
||||
**Simple to reason about, not merely simple to call.** A clean external API over a core you cannot follow to the bottom is a shallow win. Trace the key data structures and core abstractions down to their foundation and confirm the core is genuinely simple to *understand*, not just convenient to *implement against*. In Ousterhout's terms: prefer deep modules (simple interface, real work hidden) over shallow ones; complexity is dependencies + obscurity, and it surfaces as change amplification (one change touches many places) and cognitive load (a reader must hold too much in their head). Hunt both, all the way down.
|
||||
**Simple to reason about, not merely simple to call.** A clean external API over a core you cannot follow to the bottom is a hollow win. Trace the key data structures and core abstractions down to their foundation and confirm the core is genuinely simple to *understand*, not just convenient to *implement against*. Hold every module to "Prefer deep modules" in `~/.claude/principles/technical-principles.md`. Complexity is dependencies + obscurity, and it surfaces as change amplification (one change touches many places) and cognitive load (a reader must hold too much in their head). Hunt both, all the way down.
|
||||
|
||||
**Be non-pragmatic about fundamentals.** You are deliberately uncompromising on architectural choices that shape the system for years. Do not bend on:
|
||||
- Functional core, imperative shell separation
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
"""Claude Code's files and JSON shapes, each beside a sample, as Claude Code 2.1.284 writes them."""
|
||||
@@ -0,0 +1,121 @@
|
||||
"""Entries of Claude Code's transcripts and of its stream-json and json output."""
|
||||
import json
|
||||
|
||||
|
||||
def parse_entry(raw: str | bytes) -> dict | None:
|
||||
try:
|
||||
entry = json.loads(raw)
|
||||
except ValueError:
|
||||
return None
|
||||
return entry if isinstance(entry, dict) else None
|
||||
|
||||
|
||||
def content(entry: dict) -> object:
|
||||
message = entry.get("message")
|
||||
return message.get("content") if isinstance(message, dict) else None
|
||||
|
||||
|
||||
def parts(entry: dict) -> list:
|
||||
found = content(entry)
|
||||
return found if isinstance(found, list) else []
|
||||
|
||||
|
||||
# Alike in the transcript and in stream-json: {"type": "assistant", "message": {"content": [{"type": "text", "text": "ok"}]}}
|
||||
def assistant_parts(entry: dict) -> list:
|
||||
return parts(entry) if entry.get("type") == "assistant" else []
|
||||
|
||||
|
||||
def written_by_human(entry: dict) -> bool:
|
||||
"""Whether the human wrote a "user" entry; Claude Code writes the rest."""
|
||||
if tagged_as_injected(entry):
|
||||
return False
|
||||
text = content(entry)
|
||||
return string_by_human(entry, text) if isinstance(text, str) else blocks_by_human(parts(entry))
|
||||
|
||||
|
||||
# {"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>..."}}
|
||||
def tagged_as_injected(entry: dict) -> bool:
|
||||
return bool(entry.get("isMeta")) or entry.get("promptSource") in ("sdk", "system")
|
||||
|
||||
|
||||
# {"type": "user", "promptSource": "typed", "message": {"content": "merge it"}}
|
||||
# {"type": "user", "message": {"content": "<command-name>/model</command-name>\n..."}}
|
||||
def string_by_human(entry: dict, text: str) -> bool:
|
||||
# Without promptSource, nothing else says who wrote the entry, so a leading < counts as Claude Code's.
|
||||
return entry.get("promptSource") == "typed" or not text.startswith("<")
|
||||
|
||||
|
||||
# {"type": "user", "message": {"content": [{"type": "text", "text": "merge it"}]}}
|
||||
# {"type": "user", "message": {"content": [{"tool_use_id": "toolu_01…", "type": "tool_result", "content": "hi"}]}}
|
||||
# {"type": "user", "message": {"content": [{"type": "text", "text": "[Request interrupted by user]"}]}}
|
||||
def blocks_by_human(blocks: list) -> bool:
|
||||
texts = [part_text(block) for block in blocks]
|
||||
return bool(texts) and all(text is not None and not text.startswith("[Request interrupted") for text in texts)
|
||||
|
||||
|
||||
def human_text(entry: dict) -> str | None:
|
||||
"""What the human wrote in the entry, or None where Claude Code wrote it."""
|
||||
if (queued := queued_human_text(entry)) is not None:
|
||||
return queued
|
||||
if entry.get("type") != "user" or not written_by_human(entry):
|
||||
return None
|
||||
text = content(entry)
|
||||
return text if isinstance(text, str) else "".join(part_text(part) or "" for part in parts(entry))
|
||||
|
||||
|
||||
# {"type": "user", "promptSource": "sdk", "message": {"content": "Continue the task; the previous run ended before the chunk was finished."}}
|
||||
def loop_text(entry: dict) -> str | None:
|
||||
"""What a -p prompt of loop-claude's told the agent."""
|
||||
text = content(entry)
|
||||
return text if entry.get("type") == "user" and entry.get("promptSource") == "sdk" and isinstance(text, str) else None
|
||||
|
||||
|
||||
# What the human types while claude works, written only as this entry:
|
||||
# {"type": "attachment", "attachment": {"type": "queued_command", "commandMode": "prompt", "origin": {"kind": "human"}, "prompt": "B"}}
|
||||
def queued_human_text(entry: dict) -> str | None:
|
||||
attachment = entry.get("attachment") if entry.get("type") == "attachment" else None
|
||||
if not isinstance(attachment, dict) or attachment.get("type") != "queued_command" or not isinstance(origin := attachment.get("origin"), dict) or origin.get("kind") != "human":
|
||||
return None
|
||||
return prompt if isinstance(prompt := attachment.get("prompt"), str) else None
|
||||
|
||||
|
||||
# {"type": "text", "text": "ok"}
|
||||
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"}}
|
||||
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
|
||||
|
||||
|
||||
# stream-json's last line: {"type": "result", "subtype": "success", ...}
|
||||
def ends_stream(event: dict) -> bool:
|
||||
return event.get("type") == "result"
|
||||
|
||||
|
||||
# {"type": "result", "api_error_status": 429, "result": "You've hit your session limit · resets 7:40pm (Europe/Stockholm)", ...}
|
||||
def hit_limit(event: dict) -> bool:
|
||||
return ends_stream(event) and event.get("api_error_status") == 429
|
||||
|
||||
|
||||
# {"type": "result", "structured_output": {"evidence": "...", ...}, ...}
|
||||
def structured_output(result: dict) -> object:
|
||||
return result.get("structured_output")
|
||||
|
||||
|
||||
def limit_said(event: dict) -> str:
|
||||
said = " ".join(result.split()) if isinstance(result := event.get("result"), str) else ""
|
||||
return said or "claude gave no message"
|
||||
|
||||
|
||||
# {"type": "rate_limit_event", "rate_limit_info": {"status": "rejected", "resetsAt": 1790790000, ...}}
|
||||
def rejected_until(event: dict) -> int | None:
|
||||
"""When a usage limit that rejected the request resets, in seconds since the epoch."""
|
||||
info = event.get("rate_limit_info") if event.get("type") == "rate_limit_event" else None
|
||||
if not isinstance(info, dict) or info.get("status") != "rejected":
|
||||
return None
|
||||
resets_at = info.get("resetsAt")
|
||||
return resets_at if isinstance(resets_at, int) and not isinstance(resets_at, bool) else None
|
||||
@@ -0,0 +1,26 @@
|
||||
import json
|
||||
import pathlib
|
||||
|
||||
|
||||
def catalog_models(folder: pathlib.Path) -> list[tuple[str, object]]:
|
||||
files = []
|
||||
for path in folder.glob("*.json"):
|
||||
try:
|
||||
with open(path, encoding="utf-8") as handle:
|
||||
files.append(json.load(handle))
|
||||
except (OSError, ValueError):
|
||||
continue
|
||||
return newest_catalog_models(files)
|
||||
|
||||
|
||||
# A model catalog file: {"fetchedAt": 1790618085238, "catalog": {"config": {"models": [{"id": "claude-opus-5-5", "name": "Opus 5.5", ...}]}}}
|
||||
def newest_catalog_models(files: list[object]) -> list[tuple[str, object]]:
|
||||
"""The (id, name) of each model in the newest of the parsed catalog files."""
|
||||
newest: dict = {}
|
||||
for data in files:
|
||||
if isinstance(data, dict) and isinstance(data.get("fetchedAt"), (int, float)) and data["fetchedAt"] > newest.get("fetchedAt", -1):
|
||||
newest = data
|
||||
models: object = newest
|
||||
for key in ("catalog", "config", "models"):
|
||||
models = models.get(key) if isinstance(models, dict) else None
|
||||
return [(entry["id"], entry.get("name", entry["id"])) for entry in models if isinstance(entry, dict) and isinstance(entry.get("id"), str)] if isinstance(models, list) else []
|
||||
@@ -0,0 +1,51 @@
|
||||
import dataclasses
|
||||
import glob
|
||||
import os
|
||||
import pathlib
|
||||
import shutil
|
||||
import uuid
|
||||
|
||||
from failure import Failure
|
||||
|
||||
NAMESPACE = uuid.UUID("64fb586b-d926-4bb3-a44c-c903e86d3eec")
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Session:
|
||||
"""Exists while its transcript does."""
|
||||
id: uuid.UUID
|
||||
claude_code_transcripts: pathlib.Path
|
||||
name: str
|
||||
|
||||
|
||||
def session_named(name: str, claude_code_transcripts: pathlib.Path) -> Session:
|
||||
return Session(id=uuid.uuid5(NAMESPACE, name), claude_code_transcripts=claude_code_transcripts, name=name)
|
||||
|
||||
|
||||
# <claude_code_transcripts>/-home-me-code-log/<session id>.jsonl
|
||||
def transcript_file(session: Session) -> str | None:
|
||||
hit = glob.glob(os.path.join(glob.escape(str(session.claude_code_transcripts)), "*", f"{session.id}.jsonl"))
|
||||
return hit[0] if hit else None
|
||||
|
||||
|
||||
def session_open(session: Session) -> bool:
|
||||
return transcript_file(session) is not None
|
||||
|
||||
|
||||
# <session id>.jsonl, <session id>/subagents/, and from older Claude Code versions <session id>.superseded-*/ and <session id>.orphaned-*.jsonl
|
||||
def session_files(transcript: str) -> list[str]:
|
||||
return sorted(glob.glob(glob.escape(transcript.removesuffix(".jsonl")) + "*"))
|
||||
|
||||
|
||||
def delete_session(session: Session) -> Failure | None:
|
||||
path = transcript_file(session)
|
||||
if path is None:
|
||||
return None
|
||||
stem = path.removesuffix(".jsonl")
|
||||
# The transcript goes last: a failed delete leaves a session that session_open still sees, never a new session with this id beside the old one's files.
|
||||
for sibling in sorted(session_files(path), key=lambda sibling: sibling == path):
|
||||
try:
|
||||
shutil.rmtree(sibling) if os.path.isdir(sibling) else os.remove(sibling)
|
||||
except OSError as failure:
|
||||
return Failure(f"could not delete {sibling}: {failure.strerror or failure}; delete every file and folder matching {stem}*, then rerun loop-claude; a rerun before that resumes the finished chunk's session")
|
||||
return None
|
||||
@@ -0,0 +1,93 @@
|
||||
import json
|
||||
import pathlib
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from claude_code import entries, transcript, trust
|
||||
|
||||
|
||||
def assistant(*parts):
|
||||
return {"type": "assistant", "message": {"content": list(parts)}}
|
||||
|
||||
|
||||
def human(content):
|
||||
return {"type": "user", "message": {"content": content}}
|
||||
|
||||
|
||||
def queued(prompt, kind):
|
||||
return {"type": "attachment", "attachment": {"type": "queued_command", "commandMode": "prompt", "origin": {"kind": kind}, "prompt": prompt}}
|
||||
|
||||
|
||||
class Render(unittest.TestCase):
|
||||
def test_joins_assistant_text_tool_calls_human_turns_and_loop_prompts_and_skips_the_rest(self):
|
||||
said = transcript.render([
|
||||
human("do it"),
|
||||
assistant({"type": "text", "text": "Starting."}, {"type": "tool_use", "name": "Bash", "input": {"command": "ls"}}),
|
||||
assistant({"type": "text", "text": " "}),
|
||||
human([{"type": "tool_result", "content": "not typed"}]),
|
||||
human("<command-name>/exit</command-name>"),
|
||||
human([{"type": "text", "text": "yes, "}, {"type": "text", "text": "merge it"}]),
|
||||
queued("B, while you work", "human"),
|
||||
queued("origin/main moved", "coordinator"),
|
||||
{**human("Continue the task; the previous run stopped before it was finished."), "promptSource": "sdk"},
|
||||
])
|
||||
self.assertEqual(said, '[human] do it\n\nStarting.\n\n[tool Bash] {"command": "ls"}\n\n[human] yes, merge it\n\n[human] B, while you work\n\n[loop] Continue the task; the previous run stopped before it was finished.')
|
||||
|
||||
|
||||
class FirstTimestampedLine(unittest.TestCase):
|
||||
def test_skips_the_lines_every_chunk_shares_and_else_takes_the_first(self):
|
||||
self.assertEqual(transcript.first_timestamped_line(b'{"type": "custom-title"}\nnot JSON\n{"timestamp": "t"}\n{"timestamp": "u"}\n'), b'{"timestamp": "t"}')
|
||||
self.assertEqual(transcript.first_timestamped_line(b'{"type": "custom-title"}\n[1]\n'), b'{"type": "custom-title"}')
|
||||
self.assertEqual(transcript.first_timestamped_line(b""), b"")
|
||||
|
||||
|
||||
class HumanTurns(unittest.TestCase):
|
||||
def test_counts_typed_turns_and_not_tool_results(self):
|
||||
self.assertEqual(transcript.human_turns([
|
||||
human("typed"),
|
||||
human([{"type": "text", "text": "typed as a block"}]),
|
||||
human([{"type": "tool_result", "content": "not typed"}]),
|
||||
human("<command-name>/model</command-name>"),
|
||||
{**human("<3 merge it"), "promptSource": "typed"},
|
||||
{**human("<task-notification>done</task-notification>"), "promptSource": "system"},
|
||||
{**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([{"type": "text", "text": "[Request interrupted by user]"}]),
|
||||
human([]),
|
||||
queued("typed while claude worked", "human"),
|
||||
queued("<task-notification>done</task-notification>", "task-notification"),
|
||||
{"type": "attachment", "attachment": {"type": "queued_command", "commandMode": "task-notification", "prompt": "<task-notification>done</task-notification>"}},
|
||||
assistant({"type": "text", "text": "said"}),
|
||||
]), 4)
|
||||
|
||||
|
||||
class PartLine(unittest.TestCase):
|
||||
def test_renders_text_and_tool_calls_and_nothing_else(self):
|
||||
self.assertEqual(transcript.part_line({"type": "text", "text": "hi"}, 20), "hi")
|
||||
self.assertEqual(transcript.part_line({"type": "text", "text": " \n"}, 20), "")
|
||||
self.assertEqual(transcript.part_line({"type": "tool_use", "name": "Bash", "input": {"command": "x" * 500}}, 20), '[tool Bash] {"command": "xxxxxxx')
|
||||
self.assertEqual(transcript.part_line("not a part", 20), "")
|
||||
self.assertEqual(transcript.part_line({"type": "tool_use", "name": "Write", "input": {"content": "Hälsa på"}}, 40), '[tool Write] {"content": "Hälsa på"}')
|
||||
|
||||
|
||||
class Parse(unittest.TestCase):
|
||||
def test_yields_only_json_objects(self):
|
||||
self.assertEqual(entries.parse_entry('{"type": "user"}'), {"type": "user"})
|
||||
self.assertIsNone(entries.parse_entry("not json"))
|
||||
self.assertIsNone(entries.parse_entry("[1, 2]"))
|
||||
|
||||
|
||||
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()
|
||||
@@ -0,0 +1,44 @@
|
||||
import json
|
||||
|
||||
from claude_code.entries import assistant_parts, human_text, loop_text, parse_entry, part_text, tool_call
|
||||
from failure import Failure
|
||||
|
||||
JUDGED_TOOL_INPUT = 400
|
||||
|
||||
|
||||
def read_transcript(path: str) -> list[dict] | Failure:
|
||||
try:
|
||||
with open(path, "rb") as handle:
|
||||
return [entry for raw in handle if (entry := parse_entry(raw))]
|
||||
except OSError as failure:
|
||||
return Failure(f"could not read the transcript {path}: {failure.strerror}")
|
||||
|
||||
|
||||
# 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()
|
||||
return next((line for line in lines if "timestamp" in (parse_entry(line) or {})), lines[0] if lines else b"")
|
||||
|
||||
|
||||
def human_turns(entries: list[dict]) -> int:
|
||||
return sum(1 for entry in entries if human_text(entry) is not None)
|
||||
|
||||
|
||||
def render(entries: list[dict]) -> str:
|
||||
lines = []
|
||||
for entry in entries:
|
||||
lines += [line for part in assistant_parts(entry) if (line := part_line(part, JUDGED_TOOL_INPUT))]
|
||||
if (text := human_text(entry)) is not None:
|
||||
lines.append("[human] " + text)
|
||||
elif (text := loop_text(entry)) is not None:
|
||||
lines.append("[loop] " + text)
|
||||
return "\n\n".join(lines)
|
||||
|
||||
|
||||
def part_line(part: object, tool_input_chars: int) -> str:
|
||||
if (text := part_text(part)) and text.strip():
|
||||
return text
|
||||
if call := tool_call(part):
|
||||
name, arguments = call
|
||||
return f"[tool {name}] {json.dumps(arguments, ensure_ascii=False)[:tool_input_chars]}"
|
||||
return ""
|
||||
@@ -0,0 +1,38 @@
|
||||
import json
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
from failure import Failure
|
||||
from file_writes import replace_json
|
||||
|
||||
|
||||
# A failure only warns: the interrupt still runs, 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, record in projects.items() if not isinstance(record, 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
|
||||
@@ -0,0 +1,183 @@
|
||||
import dataclasses
|
||||
import decimal
|
||||
import re
|
||||
|
||||
from failure import Failure
|
||||
from markdown_text import sections
|
||||
from utc_stamp import utc
|
||||
|
||||
ARCHITECT = "Inherited architect"
|
||||
DECIDED_BY = "decided by"
|
||||
DIMENSIONS = ("Navigation", "Locality", "Shape", "Self-sufficiency", "Overall")
|
||||
HARDEST_FIRST = "hardest first"
|
||||
HEADING = re.compile(r"^([^,]+), (.+) at ([0-9a-f]{7,40})(?:, against ([0-9a-f]{7,40}))?$")
|
||||
HISTORY = "docs/comprehension-history.md"
|
||||
JUNIOR = "Junior A"
|
||||
MEAN = "Mean"
|
||||
MID = "Mid A"
|
||||
# `path:line` or `:line`, then the unit's name where one follows.
|
||||
PLACE = re.compile(r"`([^`\s]*):\d+`(?: `(\w+)`)?")
|
||||
RESTRUCTURE_FIRST = "would restructure first"
|
||||
RULING = re.compile(r"^Ruling: (better|same|worse)$", re.M)
|
||||
RULED_PLACES = re.compile(rf"^.+, {DECIDED_BY}:$")
|
||||
SCORED_PLACES = re.compile(rf"^.+, ({HARDEST_FIRST}|{RESTRUCTURE_FIRST}):$")
|
||||
SENIOR = "Maintainability senior"
|
||||
TITLE = "# Comprehension history\n"
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Seat:
|
||||
name: str
|
||||
said: str
|
||||
places: list[str]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Place:
|
||||
path: str
|
||||
name: str | None
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Entry:
|
||||
"""One paired ruling, which names the commit it was against and its ruling, or one scoring run, which names neither. A scoring run's places, or those of the scores a fall called into a ruling, are scored_places."""
|
||||
heading: str
|
||||
time: str
|
||||
commit: str
|
||||
against: str | None
|
||||
ruling: str | None
|
||||
ruled_places: list[Place]
|
||||
scored_places: list[Place]
|
||||
|
||||
@property
|
||||
def paired(self) -> bool:
|
||||
return self.against is not None
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class HistoryChange:
|
||||
"""A merged change on the default branch that touched the history, and the history before and after it."""
|
||||
commit: str
|
||||
before: str
|
||||
after: str
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Heading:
|
||||
title: str
|
||||
label: str
|
||||
commit: str
|
||||
against: str | None
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class ScoringRun:
|
||||
"""The four scoring seats' lines, their scores as written and the means, in DIMENSIONS' order."""
|
||||
seats: list[Seat]
|
||||
scores: dict[str, list[str]]
|
||||
means: list[decimal.Decimal]
|
||||
|
||||
|
||||
# A paired ruling as entry_text writes it. A scoring run's heading has no `, against`; it has no Ruling line, ends its table with a Mean row, and labels each seat's places `<seat>, hardest first:` or, for the architect, `<seat>, would restructure first:`.
|
||||
#
|
||||
# ## 2026-10-09T09:47:25Z, PR #232 at 324d650, against 12d6d75
|
||||
#
|
||||
# Ruling: same
|
||||
#
|
||||
# | Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|
||||
# |---|---|---|---|---|---|
|
||||
# | Mid A | better | worse | same | same | better |
|
||||
#
|
||||
# Mid A, decided by:
|
||||
#
|
||||
# - Locality: `bin/x.py:12` `run`: three branches to hold at once
|
||||
def entries(history: str) -> list[Entry]:
|
||||
"""Each paired ruling and scoring run in a comprehension history, in the order the file holds them; a section whose heading names no commit is left out."""
|
||||
found = []
|
||||
for heading, bodies in sections(history).items():
|
||||
if named := HEADING.match(heading):
|
||||
body = "\n".join(bodies)
|
||||
ruling = RULING.search(body)
|
||||
found.append(Entry(heading, named.group(1), named.group(3), named.group(4), ruling.group(1) if ruling else None, seat_places(body, RULED_PLACES), seat_places(body, SCORED_PLACES)))
|
||||
return found
|
||||
|
||||
|
||||
def recorded(history: str, read: str) -> bool:
|
||||
"""Whether the history holds an entry on what a seats file's first line says the seats read."""
|
||||
return any(entry.heading.partition(", ")[2] == read for entry in entries(history))
|
||||
|
||||
|
||||
def seat_places(body: str, labels: re.Pattern[str]) -> list[Place]:
|
||||
"""The places under each seat label labels matches."""
|
||||
places = []
|
||||
listing = False
|
||||
for line in body.splitlines():
|
||||
if labels.match(line):
|
||||
listing = True
|
||||
elif listing and line.startswith("- "):
|
||||
places += bullet_places(line)
|
||||
elif not line.startswith(" "):
|
||||
listing = False
|
||||
return places
|
||||
|
||||
|
||||
def bullet_places(bullet: str) -> list[Place]:
|
||||
"""A `:line` with no path is in the file named before it in the bullet."""
|
||||
places = []
|
||||
path = ""
|
||||
for match in PLACE.finditer(bullet):
|
||||
path = match.group(1) or path
|
||||
if path:
|
||||
places.append(Place(path, match.group(2)))
|
||||
return places
|
||||
|
||||
|
||||
def heading(at: float, read: str, paired: bool) -> Heading | Failure:
|
||||
"""An entry's heading, matched by HEADING: when the seats finished, in UTC, and what they read."""
|
||||
title = f"{utc(at)}, {read}"
|
||||
if (named := HEADING.match(title)) and bool(named.group(4)) == paired:
|
||||
return Heading(title, named.group(2), named.group(3), named.group(4))
|
||||
return Failure(f"the seats file's first line is not `<PR or branch> at <commit>{', against <base>' if paired else ''}`: {read}")
|
||||
|
||||
|
||||
def appended(history: str, entry: str) -> str:
|
||||
"""The history with entry added last; an empty history gets the file's title first."""
|
||||
text = history.rstrip("\n") + "\n" if history.strip() else TITLE
|
||||
return f"{text}\n{entry}"
|
||||
|
||||
|
||||
def ruling_entry(title: str, seats: list[Seat], said: dict[str, list[str]], counted: dict[str, list[str]], ruled: str, notes: list[str], scoring: ScoringRun | None) -> str:
|
||||
"""A paired ruling's entry, with any notes, such as why a fall decided it, and the scores that decided a fall; a seat's vote that counted as same for want of a place says so."""
|
||||
votes = [[seat.name, *map(vote_text, DIMENSIONS, said[seat.name], counted[seat.name])] for seat in seats]
|
||||
tables = [[["Seat", *DIMENSIONS], *votes]] + ([scores_table(scoring)] if scoring else [])
|
||||
labels = [(f"{seat.name}, {DECIDED_BY}:", seat.places) for seat in seats] + (scoring_labels(scoring.seats) if scoring else [])
|
||||
return entry_text(title, [f"Ruling: {ruled}", *notes], tables, labels)
|
||||
|
||||
|
||||
def vote_text(dimension: str, said: str, counted: str) -> str:
|
||||
if counted == said:
|
||||
return counted
|
||||
return f"same (voted {said}, naming no place)" if dimension == DIMENSIONS[-1] else f"same (voted {said}, no place naming {dimension})"
|
||||
|
||||
|
||||
def scoring_entry(title: str, scoring: ScoringRun) -> str:
|
||||
return entry_text(title, [], [scores_table(scoring)], scoring_labels(scoring.seats))
|
||||
|
||||
|
||||
def scores_table(scoring: ScoringRun) -> list[list[str]]:
|
||||
return [["Seat", *DIMENSIONS], *([seat, *values] for seat, values in scoring.scores.items()), [MEAN, *map(str, scoring.means)]]
|
||||
|
||||
|
||||
def scoring_labels(seats: list[Seat]) -> list[tuple[str, list[str]]]:
|
||||
return [(f"{seat.name}, {RESTRUCTURE_FIRST if seat.name == ARCHITECT else HARDEST_FIRST}:", seat.places) for seat in seats]
|
||||
|
||||
|
||||
def entry_text(title: str, lines: list[str], tables: list[list[list[str]]], seats: list[tuple[str, list[str]]]) -> str:
|
||||
"""The heading, any lines such as `Ruling: same`, each table, whose first row is its header, and under each seat's label its places, one bullet each."""
|
||||
parts = [f"## {title}", *lines, *("\n".join([row_text(header), "|" + "---|" * len(header), *map(row_text, rows)]) for header, *rows in tables)]
|
||||
parts += [f"{label}\n\n" + "\n".join(f"- {place}" for place in places) for label, places in seats if places]
|
||||
return "\n\n".join(parts) + "\n"
|
||||
|
||||
|
||||
def row_text(cells: list[str]) -> str:
|
||||
return "| " + " | ".join(cells) + " |"
|
||||
@@ -0,0 +1,7 @@
|
||||
import dataclasses
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Failure:
|
||||
"""A step failed, and reason says why; its caller decides what follows."""
|
||||
reason: str
|
||||
@@ -1,10 +1,12 @@
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import typing
|
||||
|
||||
from loop_claude.outcome import Failure
|
||||
from failure import Failure
|
||||
|
||||
|
||||
def make_private(folder) -> None:
|
||||
def make_private(folder: pathlib.Path) -> None:
|
||||
mask = os.umask(0o077)
|
||||
try:
|
||||
os.makedirs(folder, exist_ok=True)
|
||||
@@ -12,11 +14,11 @@ def make_private(folder) -> None:
|
||||
os.umask(mask)
|
||||
|
||||
|
||||
def replace_json(path, data, **dump) -> Failure | None:
|
||||
def replace_json(path: pathlib.Path, data: object, **dump: typing.Any) -> Failure | None:
|
||||
return replace_file(path, json.dumps(data, **dump).encode())
|
||||
|
||||
|
||||
def replace_file(path, data) -> Failure | None:
|
||||
def replace_file(path: pathlib.Path, data: bytes) -> Failure | None:
|
||||
staged = f"{path}.{os.getpid()}"
|
||||
try:
|
||||
mode = os.stat(path).st_mode & 0o7777 if os.path.exists(path) else 0o600
|
||||
@@ -0,0 +1,58 @@
|
||||
import dataclasses
|
||||
|
||||
from 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:
|
||||
directory: str
|
||||
messages: list[str]
|
||||
from_file: bool
|
||||
|
||||
|
||||
def commits(simples: list[Simple], home: str) -> list[Commit]:
|
||||
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])))
|
||||
return found
|
||||
|
||||
|
||||
def git_subcommand(words: list[str], directory: str, home: str) -> tuple[str, list[str], str] | None:
|
||||
"""A git command's subcommand, its arguments and the directory it runs in, after git's own options such as -C."""
|
||||
if words[:1] != ["git"]:
|
||||
return None
|
||||
args = iter(words[1:])
|
||||
for word in args:
|
||||
if word in GIT_VALUED:
|
||||
value = next(args, "")
|
||||
directory = resolved(directory, value, home) if word == "-C" else directory
|
||||
elif not word.startswith("-"):
|
||||
return word, list(args), directory
|
||||
return None
|
||||
|
||||
|
||||
def commit_message(args: list[str]) -> tuple[list[str], bool]:
|
||||
"""git commit's messages, and whether it reads one from a file."""
|
||||
messages = []
|
||||
from_file = False
|
||||
words = iter(args)
|
||||
for word in words:
|
||||
if word == "--":
|
||||
break
|
||||
name, equals, value = word.partition("=")
|
||||
if name in ("--message", "--file"):
|
||||
given = value if equals else next(words, "")
|
||||
elif word.startswith("-") and not word.startswith("--") and (flags := [flag for flag in word[1:] if flag in "mF"]):
|
||||
# A cluster such as -am: the valued flag takes the rest of the word, or else the next word.
|
||||
name = "--message" if flags[0] == "m" else "--file"
|
||||
given = word[word.index(flags[0]) + 1:] or next(words, "")
|
||||
else:
|
||||
continue
|
||||
messages += [given] if name == "--message" else []
|
||||
from_file = from_file or name == "--file"
|
||||
return messages, from_file
|
||||
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 larv_review import main
|
||||
|
||||
sys.exit(main.main(sys.argv[1:]))
|
||||
@@ -0,0 +1,94 @@
|
||||
import re
|
||||
import subprocess
|
||||
|
||||
from failure import Failure
|
||||
from comprehension_history import HISTORY, HistoryChange
|
||||
|
||||
|
||||
def git(*args: str) -> str | Failure:
|
||||
try:
|
||||
ran = subprocess.run(["git", *args], capture_output=True, text=True)
|
||||
except (OSError, ValueError) as failure:
|
||||
return Failure(f"git could not start: {failure}")
|
||||
return ran.stdout if ran.returncode == 0 else Failure(f"git {' '.join(args)}: {ran.stderr.strip()}")
|
||||
|
||||
|
||||
def top() -> str | Failure:
|
||||
found = git("rev-parse", "--show-toplevel")
|
||||
return found if isinstance(found, Failure) else found.strip()
|
||||
|
||||
|
||||
def default_branch(stale_ok: bool) -> tuple[str, str | None] | Failure:
|
||||
"""The default branch's ref, `origin/<branch>` after a fetch with that remote, else the local main or master, and a note for stderr. With stale_ok, a failed fetch reads origin as last fetched, and the note says so."""
|
||||
remotes = git("remote")
|
||||
if isinstance(remotes, Failure):
|
||||
return remotes
|
||||
if "origin" in remotes.split():
|
||||
fetch = git("fetch", "--quiet", "origin")
|
||||
if isinstance(fetch, Failure) and not stale_ok:
|
||||
return fetch
|
||||
note = f"reading origin as last fetched: {fetch.reason}" if isinstance(fetch, Failure) else None
|
||||
default = git("symbolic-ref", "--short", "refs/remotes/origin/HEAD")
|
||||
named = default.strip() if not isinstance(default, Failure) else origin_head()
|
||||
return named if isinstance(named, Failure) else (named, note)
|
||||
for branch in ("main", "master"):
|
||||
if not isinstance(git("rev-parse", "--quiet", "--verify", f"refs/heads/{branch}"), Failure):
|
||||
return branch, None
|
||||
return Failure("no origin remote, and no main or master branch to take as the default branch")
|
||||
|
||||
|
||||
def origin_head() -> 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")
|
||||
if isinstance(listed, Failure):
|
||||
return listed
|
||||
if named := re.match(r"ref: refs/heads/(\S+)\tHEAD", listed):
|
||||
return f"origin/{named.group(1)}"
|
||||
return Failure("origin names no default branch; set it with `git remote set-head origin --auto`")
|
||||
|
||||
|
||||
def commit_exists(commit: str) -> bool:
|
||||
return not isinstance(git("rev-parse", "--quiet", "--verify", f"{commit}^{{commit}}"), Failure)
|
||||
|
||||
|
||||
def file_at(revision: str, path: str) -> str | Failure:
|
||||
"""A file's text at a revision, 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):
|
||||
return ""
|
||||
listed = git("ls-tree", "--name-only", revision, "--", path)
|
||||
if isinstance(listed, Failure):
|
||||
return listed
|
||||
return git("show", f"{revision}:{path}") if listed.strip() else ""
|
||||
|
||||
|
||||
def history_changes(default: str) -> list[HistoryChange] | Failure:
|
||||
"""Each merged change on the default branch that touched the history, newest first; a merge commit counts as one change against its first parent."""
|
||||
shallow = git("rev-parse", "--is-shallow-repository")
|
||||
if isinstance(shallow, Failure):
|
||||
return shallow
|
||||
if shallow.strip() == "true":
|
||||
return Failure("a shallow clone lacks the commits the base search reads; run `git fetch --unshallow origin`")
|
||||
commits = git("log", "--first-parent", "--format=%H", default, "--", HISTORY)
|
||||
if isinstance(commits, Failure):
|
||||
return commits
|
||||
changes = []
|
||||
for commit in commits.split():
|
||||
before = file_at(f"{commit}^1", HISTORY)
|
||||
if isinstance(before, Failure):
|
||||
return before
|
||||
after = file_at(commit, HISTORY)
|
||||
if isinstance(after, Failure):
|
||||
return after
|
||||
changes.append(HistoryChange(commit, before, after))
|
||||
return changes
|
||||
|
||||
|
||||
def landed_since_release(default: str) -> bool | Failure:
|
||||
"""Whether the default branch holds a commit after its newest `v*` tag, or any commit when it has none."""
|
||||
# Sorts v1.0.0-rc.1 below v1.0.0.
|
||||
tags = git("-c", "versionsort.suffix=-", "tag", "--list", "v*", "--merged", default, "--sort=-v:refname")
|
||||
if isinstance(tags, Failure):
|
||||
return tags
|
||||
newest = tags.split()[:1]
|
||||
count = git("rev-list", "--count", f"{newest[0]}..{default}" if newest else default)
|
||||
return count if isinstance(count, Failure) else int(count) > 0
|
||||
@@ -0,0 +1,180 @@
|
||||
"""Hold larv-review's mechanical rules: the paired ruling's base and vote count, each pass's rounds, the scoring run's trigger, and the comprehension history's format.
|
||||
|
||||
usage: larv-review ruling-base | round-count | needs-scoring-run [<item ID>...] | record-ruling <votes file> [<scores file>] | record-scoring <scores file> [<item ID>...]
|
||||
|
||||
The comprehension check keeps a project from reading worse, two ways. In a paired ruling, simulated
|
||||
readers, the seats, read
|
||||
the branch's head beside a base and vote better, same or worse, overall and on each dimension; a
|
||||
worse ruling blocks the merge, which is the ratchet. In a scoring run, four seats score the project
|
||||
from 1 to 10; a mean under the floor of {floor} blocks the merge, unless you decide to ship.
|
||||
|
||||
Run it inside a project checkout or one of its worktrees. Each command but record-ruling first
|
||||
fetches origin, when the checkout has that remote, and takes origin's default branch, or else the
|
||||
local main or master, as the default branch. When the fetch fails, round-count reads origin as
|
||||
last fetched and says so on stderr; the other three exit 1. The history is
|
||||
docs/comprehension-history.md in the checkout.
|
||||
|
||||
ruling-base prints the commit a paired ruling reads against, then which of these found it. The last
|
||||
measured commit is the default branch's newest merged change that adds a scoring run to the
|
||||
history, or whose last added paired ruling, by heading time, is better; a merge commit counts as
|
||||
one change against its first parent. With none, the base is the one the history's first paired
|
||||
ruling names; with no ruling either, 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.
|
||||
|
||||
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
|
||||
an item whose tagline names the comprehension floor, or when it leaves a release with no item in
|
||||
the checkout's todo.md, less the shipped items, and work has landed towards that release. Work has
|
||||
landed when the chunk ships one of the release's items, or when the release is the earliest the
|
||||
default branch's todo.md names and the default branch has a commit after its newest v* tag, or has
|
||||
no v* tag.
|
||||
|
||||
A seats file's first line names what the seats read, `<PR or branch> at <commit>`, ending
|
||||
`, against <base>` in a votes file. Each seat's line follows, opening with its label written
|
||||
exactly: `Junior A:`, `Mid A:`, `Maintainability senior:` or `Inherited architect:`. Its places
|
||||
follow it, one `- ` bullet each, as the history writes them. A votes file:
|
||||
|
||||
PR #231 at abc1234, against def5678
|
||||
|
||||
Mid A: Navigation better, Locality worse, Shape same, Self-sufficiency same, Overall better
|
||||
|
||||
- Navigation, Overall: `README.md:40` "Tools": names the tool a symptom leads to
|
||||
- Locality: `bin/x.py:12` `run`: three branches to hold at once
|
||||
|
||||
Inherited architect: Navigation better, Locality worse, Shape same, Self-sufficiency same, Overall better
|
||||
|
||||
- Navigation: `README.md:40` "Tools": ...
|
||||
- Locality: `bin/x.py:12` `run`: ...
|
||||
|
||||
A scores file holds Junior A's, Mid A's, the maintainability senior's and the inherited architect's
|
||||
lines in that order, each `Navigation <n>, Locality <n>, Shape <n>, Self-sufficiency <n>, Overall
|
||||
<n>`: each score from 1 to 10, and the overall at most 1 above the line's lowest dimension.
|
||||
|
||||
record-ruling takes Mid A's and the inherited architect's votes on each dimension and overall, each
|
||||
better, same or worse. Each place opens with the names from the seat's line that it moves, joined by
|
||||
`, ` and followed by `: `. A dimension's vote counts as same unless one of the seat's places opens
|
||||
with that dimension and holds a `path:line` in backticks; the overall vote counts as same unless any
|
||||
place holds one. The printed votes say so. When the two counted overall votes differ, it appends
|
||||
nothing and prints `Split:`, saying to add the maintainability senior's and Junior A's lines.
|
||||
Otherwise the ruling is the overall vote that leads each other vote by two or more, else same. A
|
||||
dimension falls when its worse votes lead each other vote by two or more. When a better or same
|
||||
ruling has a fallen dimension, it appends nothing and prints `Fell:`, saying to run the four
|
||||
scoring seats on the same commit and run it again with their scores file. With that file, the
|
||||
ruling counts as worse when a fallen dimension's mean is under the floor of {floor}, and stands
|
||||
otherwise. It prints `Ruling:` and appends the ruling, with the scores where a fall called them.
|
||||
|
||||
record-scoring takes the scores file of a run needs-scoring-run calls, whose first line names no
|
||||
`, against`, and the same item IDs, and exits 1 when they call no run: each scoring run moves the
|
||||
ratchet's base. It appends the seats' scores and their means, rounded half up to two decimals,
|
||||
prints the means and, when a mean is under the floor of {floor}, a line opening `Floor:` naming
|
||||
each one, which blocks the merge.
|
||||
|
||||
Each record is appended to the history, created when missing, under a heading of the current UTC
|
||||
time and the seats file's first line. Each commit that line names must be in the checkout. It exits 1
|
||||
when the history already holds an entry on what that line reads.
|
||||
|
||||
Exit 1, saying why, on unknown arguments, an unknown item ID, a seats file it cannot read or that
|
||||
breaks the shape above, a scores file record-ruling did not call for or one naming another commit,
|
||||
or when git cannot start, finds no checkout or no default branch, cannot
|
||||
fetch origin for ruling-base, needs-scoring-run or record-scoring, or cannot read or write the history or todo.md.
|
||||
"""
|
||||
import pathlib
|
||||
import re
|
||||
import sys
|
||||
import typing
|
||||
|
||||
from larv_review.ruling_base import base
|
||||
from larv_review.rounds import CAP, PASSES, round_counts
|
||||
from larv_review.git import default_branch, file_at, git, history_changes
|
||||
from failure import Failure
|
||||
from larv_review.scoring import FLOOR
|
||||
from comprehension_history import HISTORY
|
||||
from larv_review.plan import plan_reasons
|
||||
from larv_review.record import record_ruling, record_scoring
|
||||
|
||||
USAGE = "usage: larv-review ruling-base | round-count | needs-scoring-run [<item ID>...] | record-ruling <votes file> [<scores file>] | record-scoring <scores file> [<item ID>...]"
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
if argv in (["-h"], ["--help"]):
|
||||
print(__doc__.strip().format(cap=CAP, floor=FLOOR))
|
||||
return 0
|
||||
command, *given = argv or [""]
|
||||
if command == "ruling-base" and not given:
|
||||
done = with_default_branch(show_ruling_base, stale_ok=False)
|
||||
elif command == "round-count" and not given:
|
||||
done = with_default_branch(round_count, stale_ok=True)
|
||||
elif command == "needs-scoring-run" and all(re.fullmatch(r"[0-9]+", id_) for id_ in given):
|
||||
done = with_default_branch(lambda default: needs_scoring_run(default, [int(id_) for id_ in given]), stale_ok=False)
|
||||
elif command == "record-ruling" and len(given) in (1, 2):
|
||||
done = record_ruling(*map(pathlib.Path, given))
|
||||
elif command == "record-scoring" and given and all(re.fullmatch(r"[0-9]+", id_) for id_ in given[1:]):
|
||||
done = with_default_branch(lambda default: record_scoring(default, pathlib.Path(given[0]), [int(id_) for id_ in given[1:]]), stale_ok=False)
|
||||
elif command in ("needs-scoring-run", "record-scoring") and given:
|
||||
named = given[1:] if command == "record-scoring" else given
|
||||
print(f"{command} takes item IDs, the numbers in todo.md's ID column, not {' '.join(id_ for id_ in named if not re.fullmatch(r'[0-9]+', id_))}; {USAGE}", file=sys.stderr)
|
||||
return 1
|
||||
elif not argv:
|
||||
print(USAGE, file=sys.stderr)
|
||||
return 1
|
||||
else:
|
||||
print(f"unknown arguments {' '.join(argv)}; {USAGE}", file=sys.stderr)
|
||||
return 1
|
||||
if isinstance(done, Failure):
|
||||
print(done.reason, file=sys.stderr)
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
def with_default_branch(command: typing.Callable[[str], Failure | None], stale_ok: bool) -> Failure | None:
|
||||
default = default_branch(stale_ok)
|
||||
if isinstance(default, Failure):
|
||||
return default
|
||||
branch, note = default
|
||||
if note:
|
||||
print(note, file=sys.stderr)
|
||||
return command(branch)
|
||||
|
||||
|
||||
def show_ruling_base(default: str) -> Failure | None:
|
||||
changes = history_changes(default)
|
||||
if isinstance(changes, Failure):
|
||||
return changes
|
||||
history = file_at(default, HISTORY)
|
||||
if isinstance(history, Failure):
|
||||
return history
|
||||
if found := base(changes, history):
|
||||
print("\n".join(found))
|
||||
return None
|
||||
merge_base = git("merge-base", "HEAD", default)
|
||||
if isinstance(merge_base, Failure):
|
||||
return merge_base
|
||||
print(f"{merge_base.strip()}\nthe merge base of HEAD and {default}")
|
||||
return None
|
||||
|
||||
|
||||
def round_count(default: str) -> Failure | None:
|
||||
titles = git("log", "--format=%s", f"{default}..HEAD")
|
||||
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'}")
|
||||
return None
|
||||
|
||||
|
||||
def cap_note(count: int) -> str:
|
||||
if count < CAP:
|
||||
return ""
|
||||
return f", {'at' if count == CAP else 'past'} the cap: ask the human before another round"
|
||||
|
||||
|
||||
def needs_scoring_run(default: str, ids: list[int]) -> Failure | None:
|
||||
reasons = plan_reasons(default, ids)
|
||||
if isinstance(reasons, Failure):
|
||||
return reasons
|
||||
print(f"Scoring run due: the chunk {' and '.join(reasons)}." if reasons else "No scoring run due.")
|
||||
return None
|
||||
@@ -0,0 +1,54 @@
|
||||
import pathlib
|
||||
|
||||
from failure import Failure
|
||||
from larv_review.git import file_at, landed_since_release, top
|
||||
from todo_table import Item, items, ITEMS_HEADER
|
||||
|
||||
|
||||
def scoring_run_due(before: list[Item], after: list[Item], ships: list[int], landed: bool) -> list[str] | Failure:
|
||||
"""Why the plan calls a scoring run, empty when it does not. before is the default branch's plan, after the chunk's, ships the IDs it ships, and landed whether the default branch holds a commit after its newest release tag.
|
||||
|
||||
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. Work has landed when the chunk ships one of the release's items, or when the release is the earliest one `before` names and `landed` holds. That covers a release whose last item moved to another release.
|
||||
"""
|
||||
plan = {item.id: item for item in before + after}
|
||||
if unknown := sorted(set(ships) - set(plan)):
|
||||
return Failure(f"neither plan holds item {', '.join(map(str, unknown))}")
|
||||
shipped = [plan[id_] for id_ in ships]
|
||||
reasons = [f"ships item {item.id}, which names the comprehension floor" for item in shipped if "comprehension floor" in item.tagline.lower()]
|
||||
next_release = min((item.release for item in before), default=None)
|
||||
for release in emptied(before, after, shipped):
|
||||
if any(item.release == release for item in shipped) or (release == next_release and landed):
|
||||
reasons.append(f"leaves release {'.'.join(map(str, release))} with no plan item")
|
||||
return reasons
|
||||
|
||||
|
||||
def emptied(before: list[Item], after: list[Item], shipped: list[Item]) -> list[tuple[int, int, int]]:
|
||||
"""Each release the default branch's plan or a shipped item names that the chunk's plan, less the shipped items, names no longer."""
|
||||
named = {item.release for item in before + shipped}
|
||||
left = {item.release for item in after if item.id not in {ship.id for ship in shipped}}
|
||||
return sorted(named - left)
|
||||
|
||||
|
||||
def plan_reasons(default: str, ids: list[int]) -> list[str] | Failure:
|
||||
"""Why the plan calls a scoring run, from the default branch's todo.md and the checkout's."""
|
||||
checkout = top()
|
||||
if isinstance(checkout, Failure):
|
||||
return checkout
|
||||
before = file_at(default, "todo.md")
|
||||
if isinstance(before, Failure):
|
||||
return before
|
||||
try:
|
||||
after = pathlib.Path(checkout, "todo.md").read_text(encoding="utf-8")
|
||||
except (OSError, UnicodeDecodeError) as failure:
|
||||
return Failure(f"could not read todo.md: {failure}")
|
||||
# While a chunk reshapes todo.md into one table, the default branch's todo.md has no items table.
|
||||
planned = items(before) if ITEMS_HEADER in before.splitlines() else []
|
||||
if isinstance(planned, Failure):
|
||||
return Failure(f"{default}'s todo.md: {planned.reason}")
|
||||
chunk = items(after)
|
||||
if isinstance(chunk, Failure):
|
||||
return Failure(f"the checkout's todo.md: {chunk.reason}")
|
||||
landed = landed_since_release(default)
|
||||
if isinstance(landed, Failure):
|
||||
return landed
|
||||
return scoring_run_due(planned, chunk, ids, landed)
|
||||
@@ -0,0 +1,135 @@
|
||||
import pathlib
|
||||
import time
|
||||
|
||||
from comprehension_history import appended, DIMENSIONS, heading, Heading, HISTORY, recorded, ruling_entry, scoring_entry, ScoringRun, vote_text
|
||||
from larv_review.git import commit_exists, top
|
||||
from larv_review.ruling import counted, fallen, overall, ruling, split, votes
|
||||
from failure import Failure
|
||||
from larv_review.scoring import fall_ruling, FLOOR, means, under_floor
|
||||
from larv_review.plan import plan_reasons
|
||||
from file_writes import replace_file
|
||||
from larv_review.seats import scores, seats_file, SeatsFile
|
||||
|
||||
|
||||
def record_ruling(votes_file: pathlib.Path, scores_file: pathlib.Path | None = None) -> Failure | None:
|
||||
read = read_seats(votes_file, paired=True)
|
||||
if isinstance(read, Failure):
|
||||
return read
|
||||
heading_read, seats_read = read
|
||||
written = votes(seats_read.seats)
|
||||
if isinstance(written, Failure):
|
||||
return written
|
||||
counts = counted(seats_read.seats, written)
|
||||
tally = ", ".join(f"{seat.name} {vote_text(DIMENSIONS[-1], overall(written[seat.name]), overall(counts[seat.name]))}" for seat in seats_read.seats)
|
||||
overall_votes = [overall(each) for each in counts.values()]
|
||||
if split(overall_votes):
|
||||
print(f"Split: {tally}. Launch the maintainability senior and Junior A together, add their lines to the votes file, and run this again.")
|
||||
return None
|
||||
ruled = ruling(overall_votes)
|
||||
fell = fallen(counts) if ruled != "worse" else []
|
||||
scoring = None
|
||||
notes = []
|
||||
if not fell and scores_file:
|
||||
why = "a worse ruling takes no scores file" if ruled == "worse" else f"no dimension fell in this {ruled} ruling, so it takes no scores file"
|
||||
return Failure(f"{why}; run record-ruling again with the votes file alone")
|
||||
if fell and not scores_file:
|
||||
print(f"Fell: {', '.join(fell)}, in a {ruled} ruling. Launch the four scoring seats on {heading_read.label} at {heading_read.commit}, write their lines to a scores file, and run this again with both files.")
|
||||
return None
|
||||
if fell and scores_file:
|
||||
scored = read_fall_scores(scores_file, heading_read)
|
||||
if isinstance(scored, Failure):
|
||||
return scored
|
||||
scoring = scored
|
||||
ruled, why = fall_ruling(ruled, fell, scoring.means)
|
||||
notes = [why]
|
||||
print(f"Ruling: {ruled}. {' '.join(notes + [f'Overall votes as counted: {tally}.'])}")
|
||||
return append(seats_read.read, ruling_entry(heading_read.title, seats_read.seats, written, counts, ruled, notes, scoring))
|
||||
|
||||
|
||||
def record_scoring(default: str, scores_file: pathlib.Path, ids: list[int]) -> Failure | None:
|
||||
read = read_seats(scores_file, paired=False)
|
||||
if isinstance(read, Failure):
|
||||
return read
|
||||
named, given = read
|
||||
scoring = scored_seats(given)
|
||||
if isinstance(scoring, Failure):
|
||||
return scoring
|
||||
reasons = plan_reasons(default, ids)
|
||||
if isinstance(reasons, Failure):
|
||||
return reasons
|
||||
if not reasons:
|
||||
return Failure("no plan item or release calls this scoring run; name the item IDs the chunk ships, as needs-scoring-run took them, or record a fall's scores with record-ruling")
|
||||
print(f"Means: {', '.join(f'{name} {value}' for name, value in zip(DIMENSIONS, scoring.means))}.")
|
||||
if under := under_floor(scoring.means):
|
||||
print(f"Floor: {', '.join(under)} under the floor of {FLOOR} block the merge, as the chunk {' and '.join(reasons)}.")
|
||||
return append(given.read, scoring_entry(named.title, scoring))
|
||||
|
||||
|
||||
def read_fall_scores(scores_file: pathlib.Path, votes: Heading) -> ScoringRun | Failure:
|
||||
"""The scores a fall called, once their file names what the votes file read."""
|
||||
read = read_seats(scores_file, paired=False, refuse_recorded=False)
|
||||
if isinstance(read, Failure):
|
||||
return read
|
||||
named, given = read
|
||||
if (named.label, named.commit) != (votes.label, votes.commit):
|
||||
return Failure(f"the scores file's first line is not `{votes.label} at {votes.commit}`, as the votes file reads: {given.read}")
|
||||
return scored_seats(given)
|
||||
|
||||
|
||||
def scored_seats(given: SeatsFile) -> ScoringRun | Failure:
|
||||
found = scores(given.seats)
|
||||
if isinstance(found, Failure):
|
||||
return found
|
||||
return ScoringRun(given.seats, found, means(list(found.values())))
|
||||
|
||||
|
||||
def read_seats(path: pathlib.Path, paired: bool, refuse_recorded: bool = True) -> tuple[Heading, SeatsFile] | Failure:
|
||||
"""The seats file and the heading its record goes under. Fails when the file names a commit the checkout lacks, or, when refuse_recorded, when the history already holds an entry on what it reads; it runs before anything is printed."""
|
||||
try:
|
||||
given = seats_file(path.read_text(encoding="utf-8"))
|
||||
except (OSError, UnicodeDecodeError) as failure:
|
||||
return Failure(f"could not read {path}: {failure}")
|
||||
if isinstance(given, Failure):
|
||||
return given
|
||||
named = heading(time.time(), given.read, paired)
|
||||
if isinstance(named, Failure):
|
||||
return named
|
||||
if unknown := [commit for commit in (named.commit, named.against) if commit and not commit_exists(commit)]:
|
||||
return Failure(f"the seats file names {', '.join(unknown)}, which is no commit in this checkout")
|
||||
if refuse_recorded:
|
||||
history = history_file()
|
||||
if isinstance(history, Failure):
|
||||
return history
|
||||
if recorded(history[1], given.read):
|
||||
return Failure(f"{history[0]} already holds an entry on {given.read}; record each ruling or run once")
|
||||
return named, given
|
||||
|
||||
|
||||
def history_file() -> tuple[pathlib.Path, str] | Failure:
|
||||
"""The checkout's history and its text, empty when the file is missing."""
|
||||
checkout = top()
|
||||
if isinstance(checkout, Failure):
|
||||
return checkout
|
||||
history = pathlib.Path(checkout, HISTORY)
|
||||
try:
|
||||
return history, history.read_text(encoding="utf-8") if history.exists() else ""
|
||||
except (OSError, UnicodeDecodeError) as failure:
|
||||
return Failure(f"could not read {history}: {failure}")
|
||||
|
||||
|
||||
def append(read: str, entry: str) -> Failure | None:
|
||||
"""Append entry unless the history already holds one on what the seats read."""
|
||||
read_history = history_file()
|
||||
if isinstance(read_history, Failure):
|
||||
return read_history
|
||||
history, text = read_history
|
||||
if recorded(text, read):
|
||||
return Failure(f"{history} already holds an entry on {read}; record each ruling or run once")
|
||||
try:
|
||||
history.parent.mkdir(parents=True, exist_ok=True)
|
||||
except OSError as failure:
|
||||
return Failure(f"could not create {history.parent}: {failure}")
|
||||
if unwritten := replace_file(history, appended(text, entry).encode()):
|
||||
return Failure(f"could not write {history}: {unwritten.reason}")
|
||||
print(f"Appended to {history}.")
|
||||
return None
|
||||
@@ -0,0 +1,17 @@
|
||||
import re
|
||||
|
||||
CAP = 3
|
||||
PASSES = ("architecture", "full scan", "security", "overrides", "stability", "product-owner", "prose")
|
||||
ROUND = re.compile(r"^Answer (.+?) round ([0-9]+):", re.IGNORECASE)
|
||||
|
||||
|
||||
def round_counts(titles: list[str]) -> dict[str, int]:
|
||||
"""Each pass's round count among the branch's `Answer <pass> round <n>:` commit titles: the highest <n>, or the number of such commits where that is more, so a repeated number still counts. A pass with none has 0, and a title naming no known pass adds its name. Case is ignored."""
|
||||
highest: dict[str, int] = dict.fromkeys(PASSES, 0)
|
||||
commits: dict[str, int] = dict.fromkeys(PASSES, 0)
|
||||
for title in titles:
|
||||
if named := ROUND.match(title):
|
||||
name = named.group(1).lower()
|
||||
highest[name] = max(highest.get(name, 0), int(named.group(2)))
|
||||
commits[name] = commits.get(name, 0) + 1
|
||||
return {name: max(highest[name], commits[name]) for name in highest}
|
||||
@@ -0,0 +1,63 @@
|
||||
from comprehension_history import DIMENSIONS, PLACE, Seat
|
||||
from failure import Failure
|
||||
from larv_review.seats import FIRST_SEATS, SPLIT_SEATS, vote_line
|
||||
|
||||
VOTES = ("better", "same", "worse")
|
||||
|
||||
|
||||
def votes(seats: list[Seat]) -> dict[str, list[str]] | Failure:
|
||||
"""Each seat's five votes as written, in DIMENSIONS' order."""
|
||||
names = [seat.name for seat in seats]
|
||||
if names[:2] != list(FIRST_SEATS) or names[2:] not in ([], list(SPLIT_SEATS)):
|
||||
return Failure(f"a paired ruling's seats are {' and '.join(FIRST_SEATS)}, then, when their overall votes differ, {' and '.join(SPLIT_SEATS)}, in that order; the file has {', '.join(names) or 'none'}")
|
||||
said = {}
|
||||
for seat in seats:
|
||||
line = vote_line(seat.name, seat.said)
|
||||
if isinstance(line, Failure):
|
||||
return line
|
||||
if unnamed := [place for place in seat.places if not place_dimensions(place)]:
|
||||
return Failure(f"{seat.name}'s place does not open with the dimensions it moves, each one of {', '.join(DIMENSIONS)}, then `: `: {unnamed[0]}")
|
||||
said[seat.name] = line
|
||||
first, second, *more = (overall(each) for each in counted(seats, said).values())
|
||||
if more and first == second:
|
||||
return Failure(f"{' and '.join(FIRST_SEATS)} both count as {first} overall, which settles the ruling; drop the other seats' lines")
|
||||
return said
|
||||
|
||||
|
||||
def overall(votes: list[str]) -> str:
|
||||
"""The overall vote, which DIMENSIONS lists last."""
|
||||
return votes[-1]
|
||||
|
||||
|
||||
def counted(seats: list[Seat], said: dict[str, list[str]]) -> dict[str, list[str]]:
|
||||
"""Each seat's votes as they count: a dimension's vote counts as same unless one of the seat's `path:line` places opens with that dimension, and the overall vote unless the seat names any such place."""
|
||||
return {seat.name: [vote if names_a_place(seat, name) else "same" for name, vote in zip(DIMENSIONS, said[seat.name])] for seat in seats}
|
||||
|
||||
|
||||
def names_a_place(seat: Seat, dimension: str) -> bool:
|
||||
return any(PLACE.search(place) and (dimension == DIMENSIONS[-1] or dimension in place_dimensions(place)) for place in seat.places)
|
||||
|
||||
|
||||
def place_dimensions(place: str) -> list[str]:
|
||||
"""The dimensions a place opens with, as in `Locality, Shape: `path:line` ...`; empty when any name before the first `: ` is no dimension."""
|
||||
named = place.partition(": ")[0].split(", ")
|
||||
return named if all(name in DIMENSIONS for name in named) else []
|
||||
|
||||
|
||||
def split(overall: list[str]) -> bool:
|
||||
"""Whether only the first two seats voted overall and they differ, so two more must vote: two votes that differ cannot reach a lead of two."""
|
||||
return len(overall) == 2 and overall[0] != overall[1]
|
||||
|
||||
|
||||
def ruling(overall: list[str]) -> str:
|
||||
return lead(overall) or "same"
|
||||
|
||||
|
||||
def fallen(counted: dict[str, list[str]]) -> list[str]:
|
||||
"""Each dimension, Overall aside, that the seats rule worse by a lead of two."""
|
||||
return [name for name, column in zip(DIMENSIONS[:-1], zip(*counted.values())) if lead(list(column)) == "worse"]
|
||||
|
||||
|
||||
def lead(votes: list[str]) -> str | None:
|
||||
"""The vote that leads each other vote by two or more, if one does."""
|
||||
return next((vote for vote in VOTES if all(votes.count(vote) >= votes.count(other) + 2 for other in VOTES if other != vote)), None)
|
||||
@@ -0,0 +1,30 @@
|
||||
from comprehension_history import entries, Entry, HistoryChange
|
||||
|
||||
|
||||
def measured_commit(changes: list[HistoryChange]) -> str | None:
|
||||
"""The newest change, of changes given newest first, that adds a scoring run to the history, or whose last added paired ruling is better.
|
||||
|
||||
It is the ratchet's base. A ruling of same leaves the base where it was, so a run of small falls each ruled same still adds up against one commit. Entry times are UTC stamps in ISO order, so they sort as text.
|
||||
"""
|
||||
for change in changes:
|
||||
held = {entry.heading for entry in entries(change.before)}
|
||||
added = [entry for entry in entries(change.after) if entry.heading not in held]
|
||||
rulings = sorted((entry for entry in added if entry.paired), key=lambda entry: entry.time)
|
||||
ruled_better = bool(rulings) and rulings[-1].ruling == "better"
|
||||
if ruled_better or any(not entry.paired for entry in added):
|
||||
return change.commit
|
||||
return None
|
||||
|
||||
|
||||
def first_ruling(history: str) -> Entry | None:
|
||||
rulings = sorted((entry for entry in entries(history) if entry.paired), key=lambda entry: entry.time)
|
||||
return rulings[0] if rulings else None
|
||||
|
||||
|
||||
def base(changes: list[HistoryChange], history: str) -> tuple[str, str] | None:
|
||||
"""The commit a paired ruling reads against, and which fallback found it; None leaves the merge base of HEAD and the default branch. history is the default branch's."""
|
||||
if found := measured_commit(changes):
|
||||
return found, "the last measured commit"
|
||||
if (first := first_ruling(history)) and first.against:
|
||||
return first.against, "the base the history's first paired ruling names"
|
||||
return None
|
||||
@@ -0,0 +1,25 @@
|
||||
import decimal
|
||||
|
||||
from comprehension_history import DIMENSIONS
|
||||
|
||||
FLOOR = decimal.Decimal("7.0")
|
||||
|
||||
|
||||
def fall_ruling(ruled: str, fell: list[str], found: list[decimal.Decimal]) -> tuple[str, str]:
|
||||
"""The ruling once the scoring run has scored the dimensions that fell, and the line that says why: worse when one of their means is under the floor, so a chunk cannot trade one dimension below the floor for gains in the others."""
|
||||
if under := [f"{name} {value}" for name, value in zip(DIMENSIONS, found) if name in fell and value < FLOOR]:
|
||||
return "worse", f"Fell: {', '.join(fell)}. Under the floor of {FLOOR}: {', '.join(under)}, so the {ruled} ruling counts as worse."
|
||||
return ruled, f"Fell: {', '.join(fell)}, each at or above the floor of {FLOOR}, so the {ruled} ruling stands."
|
||||
|
||||
|
||||
def means(lines: list[list[str]]) -> list[decimal.Decimal]:
|
||||
"""The mean of each score across the lines, in DIMENSIONS' order, rounded half up to two decimals."""
|
||||
return [mean([decimal.Decimal(score) for score in column]) for column in zip(*lines)]
|
||||
|
||||
|
||||
def mean(values: list[decimal.Decimal]) -> decimal.Decimal:
|
||||
return (sum(values, decimal.Decimal(0)) / len(values)).quantize(decimal.Decimal("0.01"), decimal.ROUND_HALF_UP)
|
||||
|
||||
|
||||
def under_floor(found: list[decimal.Decimal]) -> list[str]:
|
||||
return [f"{name} {value}" for name, value in zip(DIMENSIONS, found) if value < FLOOR]
|
||||
@@ -0,0 +1,72 @@
|
||||
import dataclasses
|
||||
import decimal
|
||||
import re
|
||||
|
||||
from 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))
|
||||
|
||||
FIRST_SEATS = (MID, ARCHITECT)
|
||||
SCORING_SEATS = (JUNIOR, MID, SENIOR, ARCHITECT)
|
||||
SEAT_LINE = re.compile(rf"^({'|'.join(SCORING_SEATS)}): (.+)$")
|
||||
SPLIT_SEATS = (SENIOR, JUNIOR)
|
||||
VOTE_LINE = re.compile(", ".join(rf"{name} (better|same|worse)" for name in DIMENSIONS))
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class SeatsFile:
|
||||
"""What the seats read, `<PR or branch> at <commit>`, with `, against <base>` for a paired ruling, then each seat's line and its places."""
|
||||
read: str
|
||||
seats: list[Seat]
|
||||
|
||||
|
||||
def seats_file(text: str) -> SeatsFile | Failure:
|
||||
lines = [line for line in text.splitlines() if line.strip()]
|
||||
if not lines:
|
||||
return Failure("the seats file is empty; its first line names what the seats read: <PR or branch> at <commit>")
|
||||
seats: list[Seat] = []
|
||||
for line in lines[1:]:
|
||||
if seat := SEAT_LINE.match(line):
|
||||
if seat.group(1) in [known.name for known in seats]:
|
||||
return Failure(f"{seat.group(1)} appears twice in the seats file")
|
||||
seats.append(Seat(seat.group(1), seat.group(2).strip(), []))
|
||||
elif seats and line.startswith("- "):
|
||||
seats[-1].places.append(line[2:].strip())
|
||||
elif seats and seats[-1].places and line.startswith(" "):
|
||||
seats[-1].places[-1] += " " + line.strip()
|
||||
else:
|
||||
return Failure(f"the seats file has a line that is neither a seat's line, opening with one of {', '.join(SCORING_SEATS)} and a colon, nor one of its places: {line}")
|
||||
return SeatsFile(lines[0].strip(), seats)
|
||||
|
||||
|
||||
def scores(seats: list[Seat]) -> dict[str, list[str]] | Failure:
|
||||
"""Each seat's five scores as written, in DIMENSIONS' order."""
|
||||
if [seat.name for seat in seats] != list(SCORING_SEATS):
|
||||
return Failure(f"a scoring run's seats are {', '.join(SCORING_SEATS)}, in that order; the file has {', '.join(seat.name for seat in seats) or 'none'}")
|
||||
found = {}
|
||||
for seat in seats:
|
||||
values = score_line(seat.name, seat.said)
|
||||
if isinstance(values, Failure):
|
||||
return values
|
||||
found[seat.name] = values
|
||||
return found
|
||||
|
||||
|
||||
def score_line(name: str, said: str) -> list[str] | Failure:
|
||||
"""A line's five scores as written, each from 1 to 10 and the overall at most 1 above the lowest dimension."""
|
||||
if not (written := SCORES.fullmatch(said)):
|
||||
return Failure(f"{name}'s line is not {', '.join(score + ' <score>' for score in DIMENSIONS)}: {said}")
|
||||
values = [decimal.Decimal(value) for value in written.groups()]
|
||||
if not all(1 <= value <= 10 for value in values):
|
||||
return Failure(f"{name}'s scores are not each from 1 to 10: {said}")
|
||||
if values[-1] > min(values[:-1]) + 1:
|
||||
return Failure(f"{name}'s overall exceeds the lowest dimension by more than 1; ask the seat to rescore: {said}")
|
||||
return list(written.groups())
|
||||
|
||||
|
||||
def vote_line(name: str, said: str) -> list[str] | Failure:
|
||||
"""A paired seat's five votes, in DIMENSIONS' order."""
|
||||
if not (written := VOTE_LINE.fullmatch(said)):
|
||||
return Failure(f"{name}'s line is not {', '.join(vote + ' <better, same or worse>' for vote in DIMENSIONS)}: {said}")
|
||||
return list(written.groups())
|
||||
@@ -0,0 +1,389 @@
|
||||
import decimal
|
||||
import itertools
|
||||
import os
|
||||
import pathlib
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import textwrap
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from comprehension_history import appended, entries, HistoryChange, Place, recorded, ruling_entry, ScoringRun, Seat
|
||||
from larv_review.ruling_base import base, first_ruling, measured_commit
|
||||
import comprehension_history
|
||||
from larv_review.ruling import counted, fallen, ruling, split, votes
|
||||
from failure import Failure
|
||||
from larv_review.scoring import fall_ruling, means, under_floor
|
||||
from test_env import isolated_env
|
||||
from todo_table import Item, items
|
||||
from larv_review.rounds import round_counts
|
||||
from larv_review.seats import score_line, scores, seats_file
|
||||
from larv_review.plan import scoring_run_due
|
||||
|
||||
TOOL = pathlib.Path(__file__).resolve().parents[1] / "larv-review"
|
||||
SCORING = "## 2026-10-08T12:00:00Z, PR #1 at aaaaaaa\n\n| Seat | Overall |\n|---|---|\n| Mean | 7.00 |\n"
|
||||
|
||||
|
||||
def paired(time: str, verdict: str, commit: str = "bbbbbbb") -> str:
|
||||
return f"## {time}, PR #2 at {commit}, against aaaaaaa\n\nRuling: {verdict}\n"
|
||||
|
||||
|
||||
def said(overall: str, locality: str = "same") -> str:
|
||||
return f"Navigation same, Locality {locality}, Shape same, Self-sufficiency same, Overall {overall}"
|
||||
|
||||
|
||||
def item(id_: int, release: tuple[int, int, int], tagline: str = "**Do it.**") -> Item:
|
||||
return Item(id_, release, "", tagline, {"R": 1, "S": 1, "A": 1, "G": 1}, ("1",))
|
||||
|
||||
|
||||
def todo(*rows: str) -> str:
|
||||
return "## Items\n\n| ID | Release | Exempt | Item | R | S | A | G | Goals | Score |\n|---|---|---|---|---|---|---|---|---|---|\n" + "".join(f"{row}\n" for row in rows)
|
||||
|
||||
|
||||
class Seats(unittest.TestCase):
|
||||
def test_reads_each_seats_line_and_places_and_joins_a_wrapped_place(self):
|
||||
given = seats_file(f"PR #2 at abc1234, against def5678\n\nMid A: {said('worse')}\n\n- `a.py:1` `f`: hard\n to read\n\nInherited architect: {said('same')}\n")
|
||||
self.assertEqual(given.read, "PR #2 at abc1234, against def5678")
|
||||
self.assertEqual(given.seats, [Seat("Mid A", said("worse"), ["`a.py:1` `f`: hard to read"]), Seat("Inherited architect", said("same"), [])])
|
||||
|
||||
def test_refuses_a_line_that_is_neither_a_seat_nor_a_place_and_a_seat_twice(self):
|
||||
self.assertIsInstance(seats_file("PR #2 at abc1234\n\nMid A worse\n"), Failure)
|
||||
self.assertIsInstance(seats_file("PR #2 at abc1234\n\nMid A: worse\n\nMid A: same\n"), Failure)
|
||||
self.assertIsInstance(seats_file(""), Failure)
|
||||
|
||||
def test_counts_each_vote_of_a_seat_naming_no_place_as_same(self):
|
||||
seats = [Seat("Mid A", said("worse", "worse"), ["Locality: the whole skill"]), Seat("Inherited architect", said("better"), ["Overall: `a.py:3` `f`: shorter"])]
|
||||
written = votes(seats)
|
||||
self.assertEqual(written, {"Mid A": ["same", "worse", "same", "same", "worse"], "Inherited architect": ["same", "same", "same", "same", "better"]})
|
||||
self.assertEqual(counted(seats, written)["Mid A"], ["same"] * 5)
|
||||
|
||||
def test_counts_a_dimensions_vote_only_where_a_place_names_that_dimension(self):
|
||||
seats = [Seat("Mid A", said("better", "worse"), ["Shape: `a.py:3` `f`: the Locality of it, reshaped"]), Seat("Inherited architect", said("better", "worse"), ["Locality, Shape: `a.py:3` `f`: held at once"])]
|
||||
written = {seat.name: ["same", "worse", "same", "same", "better"] for seat in seats}
|
||||
self.assertEqual(counted(seats, written), {"Mid A": ["same", "same", "same", "same", "better"], "Inherited architect": written["Inherited architect"]})
|
||||
self.assertIsInstance(votes([Seat("Mid A", said("better"), ["Locality, self sufficiency: `a.py:3` `f`: x"]), seats[1]]), Failure)
|
||||
self.assertIsInstance(votes([Seat("Mid A", said("better"), ["`a.py:3` `f`: Locality: x"]), seats[1]]), Failure)
|
||||
self.assertEqual(votes(seats), {seat.name: written[seat.name] for seat in seats})
|
||||
|
||||
def test_refuses_two_more_seats_once_the_first_two_agree_overall(self):
|
||||
seats = [Seat(name, said(vote), ["Overall: `f.py:1` `f`: x"]) for name, vote in (("Mid A", "worse"), ("Inherited architect", "worse"), ("Maintainability senior", "better"), ("Junior A", "better"))]
|
||||
self.assertIsInstance(votes(seats), Failure)
|
||||
|
||||
def test_takes_the_first_two_seats_then_the_other_two_in_order_and_each_dimensions_vote(self):
|
||||
first = [Seat("Mid A", said("same"), []), Seat("Inherited architect", said("same"), [])]
|
||||
self.assertIsInstance(votes(first[::-1]), Failure)
|
||||
self.assertIsInstance(votes(first + [Seat("Junior A", said("same"), [])]), Failure)
|
||||
self.assertIsInstance(votes([first[0], Seat("Inherited architect", said("worst"), [])]), Failure)
|
||||
self.assertIsInstance(votes([first[0], Seat("Inherited architect", "same", [])]), Failure)
|
||||
|
||||
def test_finds_each_dimension_ruled_worse_by_a_lead_of_two(self):
|
||||
self.assertEqual(fallen({"Mid A": ["same", "worse", "worse", "same", "better"], "Inherited architect": ["same", "worse", "same", "same", "better"]}), ["Locality"])
|
||||
four = {name: ["same", vote, "same", "same", "better"] for name, vote in (("Mid A", "worse"), ("Inherited architect", "same"), ("Maintainability senior", "worse"), ("Junior A", "worse"))}
|
||||
self.assertEqual(fallen(four), ["Locality"])
|
||||
self.assertEqual(fallen({**four, "Junior A": ["same", "better", "same", "same", "better"]}), [])
|
||||
|
||||
def test_rules_by_a_lead_of_two_and_splits_two_seats_that_differ(self):
|
||||
cases = [
|
||||
(["worse", "worse"], "worse"),
|
||||
(["same", "same"], "same"),
|
||||
(["worse", "same"], None),
|
||||
(["worse", "better", "worse", "worse"], "worse"),
|
||||
(["worse", "same", "worse", "same"], "same"),
|
||||
(["worse", "same", "worse", "better"], "same"),
|
||||
(["better", "same", "better", "better"], "better"),
|
||||
]
|
||||
for counted, expected in cases:
|
||||
with self.subTest(counted):
|
||||
self.assertEqual(None if split(counted) else ruling(counted), expected)
|
||||
|
||||
def test_reads_four_seats_scores_and_refuses_an_overall_above_the_lowest_by_more_than_one(self):
|
||||
line = "Navigation 7, Locality 6.5, Shape 7, Self-sufficiency 6.5, Overall 7"
|
||||
seats = [Seat(name, line, []) for name in ("Junior A", "Mid A", "Maintainability senior", "Inherited architect")]
|
||||
self.assertEqual(scores(seats)["Mid A"], ["7", "6.5", "7", "6.5", "7"])
|
||||
self.assertIsInstance(scores(seats[:3]), Failure)
|
||||
self.assertIsInstance(scores([*seats[:3], Seat("Inherited architect", line.replace("Overall 7", "Overall 8"), [])]), Failure)
|
||||
self.assertIsInstance(scores([*seats[:3], Seat("Inherited architect", line.replace("Shape 7", "Shape 11"), [])]), Failure)
|
||||
self.assertEqual(score_line("Mean", "Navigation 7.38, Locality 7.38, Shape 8, Self-sufficiency 8, Overall 8.38")[-1], "8.38")
|
||||
|
||||
def test_rounds_each_mean_half_up_and_names_each_under_the_floor(self):
|
||||
found = means([["7.5", "6.5", "7", "7", "7"], ["7.5", "7", "7", "6.5", "7"], ["7", "6.5", "7", "6.5", "6.5"], ["7.5", "6.5", "7", "6.5", "7"]])
|
||||
self.assertEqual([str(mean) for mean in found], ["7.38", "6.63", "7.00", "6.63", "6.88"])
|
||||
self.assertEqual(under_floor(found), ["Locality 6.63", "Self-sufficiency 6.63", "Overall 6.88"])
|
||||
self.assertEqual(under_floor([decimal.Decimal("7.00")] * 5), [])
|
||||
|
||||
|
||||
class History(unittest.TestCase):
|
||||
def test_writes_the_sample_entry_its_parser_shows(self):
|
||||
source = pathlib.Path(comprehension_history.__file__).read_text(encoding="utf-8").splitlines()
|
||||
start = next(index for index, line in enumerate(source) if line.startswith("# ## "))
|
||||
sample = [line.removeprefix("#").removeprefix(" ") for line in itertools.takewhile(lambda line: line.startswith("#"), source[start:])]
|
||||
seat = Seat("Mid A", said("better", "worse"), ["Locality: `bin/x.py:12` `run`: three branches to hold at once"])
|
||||
votes = {"Mid A": ["better", "worse", "same", "same", "better"]}
|
||||
self.assertEqual(ruling_entry("2026-10-09T09:47:25Z, PR #232 at 324d650, against 12d6d75", [seat], votes, votes, "same", [], None), "\n".join(sample) + "\n")
|
||||
|
||||
def test_reads_back_what_it_writes(self):
|
||||
seats = [Seat("Mid A", said("better", "worse"), ["`bin/a.py:3` `f`: hard, with `:9` `g`"]), Seat("Inherited architect", said("worse", "worse"), [])]
|
||||
written = {"Mid A": ["same", "worse", "same", "same", "better"], "Inherited architect": ["same", "worse", "same", "same", "worse"]}
|
||||
scoring = ScoringRun([Seat("Junior A", "", ["`bin/b.py:4` `h`: long"])], {"Junior A": ["7", "6.5", "7", "7", "7"]}, [decimal.Decimal(mean) for mean in ("7.00", "6.50", "7.00", "7.00", "7.00")])
|
||||
ruled = ruling_entry("2026-10-08T18:37:21Z, PR #2 at bbbbbbb, against aaaaaaa", seats, written, {**written, "Inherited architect": ["same"] * 5}, "worse", ["Fell: Locality, under the floor."], scoring)
|
||||
history = appended(appended("", SCORING), ruled)
|
||||
self.assertTrue(history.startswith("# Comprehension history\n\n## 2026-10-08T12:00:00Z"))
|
||||
self.assertNotIn("Inherited architect, decided by:", history)
|
||||
self.assertIn("| Inherited architect | same | same (voted worse, no place naming Locality) | same | same | same (voted worse, naming no place) |", history)
|
||||
found = entries(history)
|
||||
self.assertEqual([(entry.commit, entry.against, entry.ruling) for entry in found], [("aaaaaaa", None, None), ("bbbbbbb", "aaaaaaa", "worse")])
|
||||
self.assertEqual((found[1].ruled_places, found[1].scored_places), ([Place("bin/a.py", "f"), Place("bin/a.py", "g")], [Place("bin/b.py", "h")]))
|
||||
self.assertTrue(recorded(history, "PR #2 at bbbbbbb, against aaaaaaa"))
|
||||
self.assertFalse(recorded(history, "PR #2 at bbbbbbb"))
|
||||
self.assertIn("| Mean | 7.00 | 6.50 | 7.00 | 7.00 | 7.00 |\n\nMid A, decided by:", history)
|
||||
self.assertEqual([entry.paired for entry in found], [False, True])
|
||||
|
||||
|
||||
class FallRuling(unittest.TestCase):
|
||||
def test_counts_a_ruling_worse_when_a_fallen_dimensions_mean_is_under_the_floor(self):
|
||||
found = [decimal.Decimal(score) for score in ("6", "6.5", "7", "6", "6")]
|
||||
self.assertEqual(fall_ruling("better", ["Locality", "Shape"], found), ("worse", "Fell: Locality, Shape. Under the floor of 7.0: Locality 6.5, so the better ruling counts as worse."))
|
||||
self.assertEqual(fall_ruling("same", ["Shape"], found), ("same", "Fell: Shape, each at or above the floor of 7.0, so the same ruling stands."))
|
||||
|
||||
|
||||
class Base(unittest.TestCase):
|
||||
def test_takes_the_newest_change_adding_a_scoring_run_or_ending_on_a_better_ruling(self):
|
||||
older = HistoryChange("old", "", SCORING)
|
||||
same = HistoryChange("same", SCORING, SCORING + paired("2026-10-08T13:00:00Z", "same"))
|
||||
self.assertEqual(measured_commit([same, older]), "old")
|
||||
# The file holds the later ruling first, as a merge conflict resolved the other way would.
|
||||
better = HistoryChange("better", SCORING, SCORING + paired("2026-10-08T14:00:00Z", "better") + paired("2026-10-08T13:00:00Z", "worse"))
|
||||
self.assertEqual(measured_commit([better, older]), "better")
|
||||
worse_last = HistoryChange("worse", SCORING, SCORING + paired("2026-10-08T13:00:00Z", "better") + paired("2026-10-08T14:00:00Z", "worse"))
|
||||
self.assertEqual(measured_commit([worse_last, older]), "old")
|
||||
self.assertIsNone(measured_commit([same]))
|
||||
scored_fall = HistoryChange("same fell", SCORING, SCORING + paired("2026-10-08T13:00:00Z", "same\n\nFell: Locality, each at or above the floor.\n\n| Seat | Overall |\n|---|---|\n| Mean | 7.00 |"))
|
||||
self.assertEqual(measured_commit([scored_fall, older]), "old")
|
||||
|
||||
def test_falls_back_to_the_first_rulings_base_then_to_none(self):
|
||||
ruled = paired("2026-10-08T13:00:00Z", "worse")
|
||||
self.assertEqual(base([HistoryChange("c", "", ruled)], ruled), ("aaaaaaa", "the base the history's first paired ruling names"))
|
||||
self.assertIsNone(base([], ""))
|
||||
self.assertEqual(base([HistoryChange("c", "", SCORING)], SCORING), ("c", "the last measured commit"))
|
||||
|
||||
def test_finds_the_earliest_ruling_by_its_time(self):
|
||||
ruled = first_ruling(paired("2026-10-08T14:00:00Z", "same", "ccccccc") + paired("2026-10-08T13:00:00Z", "worse"))
|
||||
self.assertEqual(ruled and ruled.commit, "bbbbbbb")
|
||||
self.assertIsNone(first_ruling(SCORING))
|
||||
|
||||
|
||||
class Rounds(unittest.TestCase):
|
||||
def test_counts_each_passs_highest_round(self):
|
||||
counts = round_counts(["Answer prose round 1: x", "Answer full scan round 2: y", "Answer full scan round 1: z", "Answer stability: no round", "Answer stabilty round 1: typo", "Answer security round 1: rename round 2: x", "Rescore: w"])
|
||||
self.assertEqual((counts["prose"], counts["full scan"], counts["stability"], counts["architecture"], counts["stabilty"], counts["security"]), (1, 2, 0, 0, 1, 1))
|
||||
|
||||
def test_counts_a_mis_cased_title_under_its_pass(self):
|
||||
self.assertEqual(round_counts(["Answer Architecture round 4: x", "Answer architecture round 3: y"])["architecture"], 4)
|
||||
|
||||
def test_counts_a_repeated_round_number_as_a_round_of_its_own(self):
|
||||
self.assertEqual(round_counts(["Answer stability round 3: x", "Answer stability round 3: y", "Answer stability round 2: z", "Answer stability round 1: w"])["stability"], 4)
|
||||
|
||||
|
||||
class ScoringRunDue(unittest.TestCase):
|
||||
def test_reads_each_rows_id_release_and_tagline(self):
|
||||
self.assertEqual(items(todo("| 3 | 0.1.0 | | **Do it.** | 1 | 1 | 1 | 1 | 1 | 9.0 |")), [item(3, (0, 1, 0))])
|
||||
self.assertIsInstance(items("# todo\n"), Failure)
|
||||
self.assertIsInstance(items(todo("| 0 | 0.1.0 | | **Do it.** | 1 | 1 | 1 | 1 | 1 | 9.0 |")), Failure)
|
||||
|
||||
def test_is_due_for_an_item_naming_the_floor(self):
|
||||
plan = [item(1, (0, 1, 0), "**Lift the project to the Comprehension floor.**"), item(2, (0, 1, 0))]
|
||||
self.assertEqual(scoring_run_due(plan, plan, [1], True), ["ships item 1, which names the comprehension floor"])
|
||||
self.assertIsInstance(scoring_run_due(plan, plan, [9], True), Failure)
|
||||
|
||||
def test_is_due_when_the_chunk_ships_a_releases_last_item(self):
|
||||
plan = [item(1, (0, 1, 0)), item(2, (0, 2, 0))]
|
||||
self.assertEqual(scoring_run_due(plan, plan, [1], False), ["leaves release 0.1.0 with no plan item"])
|
||||
self.assertEqual(scoring_run_due(plan, plan + [item(3, (0, 1, 0))], [1], True), [])
|
||||
|
||||
def test_is_due_when_the_chunk_removes_the_next_releases_last_item_after_work_landed(self):
|
||||
before = [item(1, (0, 1, 0)), item(2, (0, 1, 0)), item(3, (0, 2, 0))]
|
||||
after = [item(2, (0, 1, 0)), item(3, (0, 2, 0))]
|
||||
self.assertEqual(scoring_run_due(before, after, [2], True), ["leaves release 0.1.0 with no plan item"])
|
||||
self.assertEqual(scoring_run_due(before, after, [], True), [])
|
||||
emptied = [item(3, (0, 2, 0))]
|
||||
self.assertEqual(scoring_run_due(before, emptied, [2], False), ["leaves release 0.1.0 with no plan item"])
|
||||
self.assertEqual(scoring_run_due(before, emptied, [], True), ["leaves release 0.1.0 with no plan item"])
|
||||
self.assertEqual(scoring_run_due(before, emptied, [], False), [])
|
||||
|
||||
def test_is_not_due_when_a_later_release_loses_its_last_item_unshipped(self):
|
||||
before = [item(1, (0, 1, 0)), item(3, (0, 2, 0))]
|
||||
self.assertEqual(scoring_run_due(before, before[:1], [], True), [])
|
||||
|
||||
|
||||
class LarvReviewTool(unittest.TestCase):
|
||||
def setUp(self):
|
||||
temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(temp.cleanup)
|
||||
root = pathlib.Path(os.path.realpath(temp.name))
|
||||
self.env = {**isolated_env(), "GIT_CONFIG_GLOBAL": os.devnull, "HOME": str(root)}
|
||||
self.checkout = root / "proj"
|
||||
subprocess.run(["git", "init", "-q", "--bare", "-b", "main", str(root / "origin.git")], check=True, env=self.env)
|
||||
subprocess.run(["git", "clone", "-q", str(root / "origin.git"), str(self.checkout)], check=True, env=self.env, capture_output=True)
|
||||
self.commit("start", {"todo.md": todo("| 1 | 0.1.0 | | **Do it.** | 1 | 1 | 1 | 1 | 1 | 9.0 |", "| 2 | 0.2.0 | | **Then this.** | 1 | 1 | 1 | 1 | 1 | 9.0 |", "| 3 | 0.2.0 | | **And this.** | 1 | 1 | 1 | 1 | 1 | 9.0 |")})
|
||||
self.git("push", "-q", "origin", "HEAD:main")
|
||||
self.git("remote", "set-head", "origin", "main")
|
||||
self.git("switch", "-q", "-c", "chunk")
|
||||
self.start = self.git("rev-parse", "--short", "HEAD").strip()
|
||||
|
||||
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=None):
|
||||
for name, text in (files or {}).items():
|
||||
(self.checkout / name).parent.mkdir(parents=True, exist_ok=True)
|
||||
(self.checkout / name).write_text(text)
|
||||
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 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_a_scoring_run(self):
|
||||
start = self.git("rev-parse", "HEAD").strip()
|
||||
self.commit("work")
|
||||
ran = self.run_tool("ruling-base")
|
||||
self.assertEqual((ran.returncode, ran.stdout.splitlines()[0]), (0, start), ran.stderr)
|
||||
self.git("switch", "-q", "-c", "measured", "main")
|
||||
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.git("switch", "-q", "chunk")
|
||||
self.assertEqual(self.run_tool("ruling-base").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("prose: 1\n", ran.stdout)
|
||||
self.assertIn("architecture: 0\n", ran.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")
|
||||
unknown = self.run_tool("needs-scoring-run", "9")
|
||||
self.assertEqual(unknown.returncode, 1)
|
||||
self.assertIn("item 9", unknown.stderr)
|
||||
self.assertEqual(self.run_tool("needs-scoring-run").stdout, "No scoring run due.\n")
|
||||
self.assertIn("todo.md's ID column", self.run_tool("needs-scoring-run", "item-85").stderr)
|
||||
|
||||
def test_records_a_ruling_once_four_seats_settle_a_split(self):
|
||||
lines = """\
|
||||
PR #2 at {start}, against {start}
|
||||
|
||||
Mid A: {worse}
|
||||
|
||||
- Overall: `bin/a.py:3` `f`: three branches
|
||||
|
||||
Inherited architect: {same}
|
||||
"""
|
||||
lines = lines.replace("{start}", self.start).replace("{worse}", said("worse")).replace("{same}", said("same"))
|
||||
split = self.run_tool("record-ruling", self.seats_file(lines))
|
||||
self.assertEqual(split.returncode, 0, split.stderr)
|
||||
self.assertTrue(split.stdout.startswith("Split: Mid A worse, Inherited architect same."))
|
||||
history = self.checkout / "docs" / "comprehension-history.md"
|
||||
self.assertFalse(history.exists())
|
||||
lines += f"\n\t\t\tMaintainability senior: {said('worse')}\n\n\t\t\t- Overall: `bin/a.py:3` `f`: hard\n\n\t\t\tJunior A: {said('worse')}\n"
|
||||
ran = self.run_tool("record-ruling", self.seats_file(lines))
|
||||
self.assertEqual(ran.stdout.splitlines()[0], "Ruling: same. Overall votes as counted: Mid A worse, Inherited architect same, Maintainability senior worse, Junior A same (voted worse, naming no place).")
|
||||
recorded = entries(history.read_text())
|
||||
self.assertEqual([(entry.commit, entry.against, entry.ruling) for entry in recorded], [(self.start, self.start, "same")])
|
||||
self.assertEqual(recorded[0].ruled_places, [Place("bin/a.py", "f")] * 2)
|
||||
self.assertIn("| Junior A | same | same | same | same | same (voted worse, naming no place) |", history.read_text())
|
||||
|
||||
def test_asks_for_the_scoring_seats_when_a_dimension_falls_and_rules_with_their_scores(self):
|
||||
place = "\n\n- Locality, Overall: `bin/a.py:3` `f`: shorter\n\n"
|
||||
votes_file = self.seats_file(f"PR #2 at {self.start}, against {self.start}\n\nMid A: {said('better', 'worse')}{place}Inherited architect: {said('better', 'worse')}{place}", "votes.md")
|
||||
asked = self.run_tool("record-ruling", votes_file)
|
||||
self.assertEqual(asked.returncode, 0, asked.stderr)
|
||||
self.assertTrue(asked.stdout.startswith(f"Fell: Locality, in a better ruling. Launch the four scoring seats on PR #2 at {self.start},"))
|
||||
history = self.checkout / "docs" / "comprehension-history.md"
|
||||
self.assertFalse(history.exists())
|
||||
line = "Navigation 7, Locality 6.5, Shape 7, Self-sufficiency 7, Overall 7"
|
||||
scores_text = f"PR #2 at {self.start}\n" + "".join(f"\n{seat}: {line}\n\n- `bin/b.py:4` `h`: long\n" for seat in ("Junior A", "Mid A", "Maintainability senior", "Inherited architect"))
|
||||
ruled = self.run_tool("record-ruling", votes_file, self.seats_file(scores_text, "scores.md"))
|
||||
self.assertEqual(ruled.returncode, 0, ruled.stderr)
|
||||
self.assertTrue(ruled.stdout.startswith("Ruling: worse. Fell: Locality. Under the floor of 7.0: Locality 6.50, so the better ruling counts as worse."))
|
||||
again = self.run_tool("record-ruling", votes_file, self.seats_file(scores_text, "scores.md"))
|
||||
self.assertIn("already holds an entry on", again.stderr)
|
||||
self.assertEqual(self.run_tool("record-ruling", votes_file).stdout, "")
|
||||
recorded = entries(history.read_text())
|
||||
self.assertEqual([entry.ruling for entry in recorded], ["worse"])
|
||||
self.assertIn("| Mean | 7.00 | 6.50 | 7.00 | 7.00 | 7.00 |", history.read_text())
|
||||
votes_file = self.seats_file(pathlib.Path(votes_file).read_text().replace("PR #2", "PR #3"), "votes.md")
|
||||
scores_text = scores_text.replace("PR #2", "PR #3")
|
||||
stands = self.run_tool("record-ruling", votes_file, self.seats_file(scores_text.replace("Locality 6.5", "Locality 7"), "scores.md"))
|
||||
self.assertTrue(stands.stdout.startswith("Ruling: better. Fell: Locality, each at or above the floor of 7.0, so the better ruling stands."), stands.stderr)
|
||||
votes_file = self.seats_file(pathlib.Path(votes_file).read_text().replace("PR #3", "PR #4"), "votes.md")
|
||||
other = self.run_tool("record-ruling", votes_file, self.seats_file(scores_text.replace("PR #3", "PR #5"), "scores.md"))
|
||||
self.assertIn("the scores file's first line is not", other.stderr)
|
||||
|
||||
def test_names_no_fall_on_a_worse_ruling_and_takes_no_scores_file_without_one(self):
|
||||
place = "\n\n- Locality, Overall: `bin/a.py:3` `f`: longer\n\n"
|
||||
ran = self.run_tool("record-ruling", self.seats_file(f"PR #2 at {self.start}, against {self.start}\n\nMid A: {said('worse', 'worse')}{place}Inherited architect: {said('worse', 'worse')}{place}"))
|
||||
self.assertEqual(ran.returncode, 0, ran.stderr)
|
||||
self.assertNotIn("Fell:", ran.stdout + (self.checkout / "docs" / "comprehension-history.md").read_text())
|
||||
extra = self.run_tool("record-ruling", self.seats_file(f"PR #3 at {self.start}, against {self.start}\n\nMid A: {said('worse')}{place}Inherited architect: {said('worse')}{place}"), self.seats_file("PR #2", "scores.md"))
|
||||
self.assertIn("a worse ruling takes no scores file; run record-ruling again with the votes file alone", extra.stderr)
|
||||
better = self.run_tool("record-ruling", self.seats_file(f"PR #5 at {self.start}, against {self.start}\n\nMid A: {said('better')}{place}Inherited architect: {said('better')}{place}"), self.seats_file("PR #5", "scores.md"))
|
||||
self.assertIn("no dimension fell in this better ruling, so it takes no scores file", better.stderr)
|
||||
|
||||
def test_records_a_scoring_run_with_its_means(self):
|
||||
line = "Navigation 7, Locality 6.5, Shape 7, Self-sufficiency 6.5, Overall 7"
|
||||
seats = "".join(f"\n{seat}: {line}\n\n- `bin/a.py:3` `f`: long\n" for seat in ("Junior A", "Mid A", "Maintainability senior", "Inherited architect"))
|
||||
uncalled = self.run_tool("record-scoring", self.seats_file(f"PR #2 at {self.start}\n" + seats))
|
||||
self.assertEqual(uncalled.returncode, 1)
|
||||
self.assertIn("no plan item or release calls this scoring run", uncalled.stderr)
|
||||
ran = self.run_tool("record-scoring", self.seats_file(f"PR #2 at {self.start}\n" + seats), "1")
|
||||
self.assertEqual(ran.returncode, 0, ran.stderr)
|
||||
self.assertIn("\nFloor: Locality 6.50, Self-sufficiency 6.50 under the floor of 7.0 block the merge, as the chunk leaves release 0.1.0 with no plan item.\n", ran.stdout)
|
||||
self.assertIn("not /", self.run_tool("record-scoring", "1", self.seats_file(f"PR #2 at {self.start}\n" + seats)).stderr)
|
||||
text = (self.checkout / "docs" / "comprehension-history.md").read_text()
|
||||
self.assertIn("| Mean | 7.00 | 6.50 | 7.00 | 6.50 | 7.00 |", text)
|
||||
self.assertIn("Inherited architect, would restructure first:", text)
|
||||
self.assertEqual(entries(text)[0].scored_places, [Place("bin/a.py", "f")] * 4)
|
||||
|
||||
def test_refuses_a_ruling_file_that_names_no_base_or_a_commit_the_checkout_lacks(self):
|
||||
ran = self.run_tool("record-ruling", self.seats_file(f"PR #2 at {self.start}\n\nMid A: {said('same')}\n\nInherited architect: {said('same')}\n"))
|
||||
self.assertEqual(ran.returncode, 1)
|
||||
self.assertIn("against <base>", ran.stderr)
|
||||
lacking = self.run_tool("record-ruling", self.seats_file(f"PR #2 at {self.start}, against abcdef1\n\nMid A: {said('same')}\n\nInherited architect: {said('same')}\n"))
|
||||
self.assertEqual(lacking.returncode, 1)
|
||||
self.assertIn("abcdef1, which is no commit", lacking.stderr)
|
||||
|
||||
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.git("remote", "set-head", "origin", "--delete")
|
||||
self.assertEqual(self.run_tool("needs-scoring-run", "2").stdout, "No scoring run due.\n")
|
||||
|
||||
def test_takes_a_local_main_without_origin_and_reads_origin_as_last_fetched_when_the_fetch_fails(self):
|
||||
self.commit("Answer prose round 1: a")
|
||||
self.git("remote", "set-url", "origin", str(self.checkout.parent / "gone.git"))
|
||||
offline = self.run_tool("round-count")
|
||||
self.assertEqual(offline.returncode, 0, offline.stderr)
|
||||
self.assertIn("reading origin as last fetched", offline.stderr)
|
||||
self.assertIn("prose: 1\n", offline.stdout)
|
||||
self.git("remote", "remove", "origin")
|
||||
self.assertIn("prose: 1\n", self.run_tool("round-count").stdout)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
+2
-2
@@ -6,7 +6,7 @@ import sys
|
||||
LAUNCHER = pathlib.Path(__file__).resolve()
|
||||
sys.path.insert(0, str(LAUNCHER.parent))
|
||||
|
||||
from loop_claude import paths
|
||||
from loop_claude import effects, paths
|
||||
from loop_claude.loop import main
|
||||
|
||||
sys.exit(main.main(sys.argv[1:], os.environ, paths.paths_from(pathlib.Path.home(), os.environ), LAUNCHER, pathlib.Path.cwd()))
|
||||
sys.exit(main.main(sys.argv[1:], os.environ, paths.paths_from(pathlib.Path.home()), LAUNCHER, pathlib.Path.cwd(), effects.system_effects()))
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
import json
|
||||
|
||||
from loop_claude.claude_code.formats import models_in
|
||||
|
||||
|
||||
def offered_models(folder) -> list[tuple[str, object]]:
|
||||
files = []
|
||||
for path in folder.glob("*.json"):
|
||||
try:
|
||||
with open(path, encoding="utf-8") as handle:
|
||||
files.append(json.load(handle))
|
||||
except (OSError, ValueError):
|
||||
continue
|
||||
return models_in(files)
|
||||
@@ -1,110 +0,0 @@
|
||||
"""Claude Code's JSON shapes loop-claude handles, each under a sample of it, as Claude Code 2.1.284 writes it."""
|
||||
import json
|
||||
|
||||
from loop_claude.outcome import Failure
|
||||
|
||||
|
||||
def parse(raw) -> dict | None:
|
||||
try:
|
||||
entry = json.loads(raw)
|
||||
except ValueError:
|
||||
return None
|
||||
return entry if isinstance(entry, dict) else None
|
||||
|
||||
|
||||
def content(entry) -> object:
|
||||
message = entry.get("message")
|
||||
return message.get("content") if isinstance(message, dict) else None
|
||||
|
||||
|
||||
def parts(entry) -> list:
|
||||
found = content(entry)
|
||||
return found if isinstance(found, list) else []
|
||||
|
||||
|
||||
# Alike in the transcript and in stream-json: {"type": "assistant", "message": {"content": [{"type": "text", "text": "ok"}]}}
|
||||
def assistant_parts(entry) -> list:
|
||||
return parts(entry) if entry.get("type") == "assistant" else []
|
||||
|
||||
|
||||
def written_by_human(entry) -> bool:
|
||||
"""Whether the human wrote a "user" entry; Claude Code writes the rest."""
|
||||
# {"type": "user", "isMeta": true, "message": {"content": "<local-command-caveat>Caveat: ..."}}
|
||||
# {"type": "user", "promptSource": "sdk", "message": {"content": "Continue the task; ..."}}
|
||||
if entry.get("isMeta") or entry.get("promptSource") == "sdk":
|
||||
return False
|
||||
# {"type": "user", "message": {"content": "<command-name>/model</command-name>\n..."}}
|
||||
# {"type": "user", "promptSource": "system", "message": {"content": "<task-notification>..."}}
|
||||
# {"type": "user", "promptSource": "typed", "message": {"content": "merge it"}}
|
||||
# Claude Code tags what it injects, and an entry without promptSource carries no other mark, so a leading < is its own.
|
||||
if isinstance(text := content(entry), str):
|
||||
source = entry.get("promptSource")
|
||||
return source != "system" and (source == "typed" or not text.startswith("<"))
|
||||
texts = [part_text(part) for part in parts(entry)]
|
||||
# {"type": "user", "message": {"content": [{"tool_use_id": "toolu_01…", "type": "tool_result", "content": "hi"}]}}
|
||||
# {"type": "user", "message": {"content": [{"type": "text", "text": "[Request interrupted by user]"}]}}
|
||||
return bool(texts) and all(text is not None and not text.startswith("[Request interrupted") for text in texts)
|
||||
|
||||
|
||||
def human_text(entry) -> str | None:
|
||||
"""What the human wrote in the entry, or None where Claude Code wrote it."""
|
||||
if (queued := queued_human_text(entry)) is not None:
|
||||
return queued
|
||||
if entry.get("type") != "user" or not written_by_human(entry):
|
||||
return None
|
||||
text = content(entry)
|
||||
return text if isinstance(text, str) else "".join(part_text(part) or "" for part in parts(entry))
|
||||
|
||||
|
||||
# What the human types while claude works, written only as this entry:
|
||||
# {"type": "attachment", "attachment": {"type": "queued_command", "commandMode": "prompt", "origin": {"kind": "human"}, "prompt": "B"}}
|
||||
def queued_human_text(entry) -> str | None:
|
||||
attachment = entry.get("attachment") if entry.get("type") == "attachment" else None
|
||||
if not isinstance(attachment, dict) or attachment.get("type") != "queued_command" or not isinstance(origin := attachment.get("origin"), dict) or origin.get("kind") != "human":
|
||||
return None
|
||||
return prompt if isinstance(prompt := attachment.get("prompt"), str) else None
|
||||
|
||||
|
||||
# {"type": "text", "text": "ok"}
|
||||
def part_text(part) -> 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"}}
|
||||
def tool_call(part) -> tuple[object, object] | None:
|
||||
return (part.get("name"), part.get("input")) if isinstance(part, dict) and part.get("type") == "tool_use" else None
|
||||
|
||||
|
||||
# stream-json's last line: {"type": "result", "subtype": "success", ...}
|
||||
def ends_stream(event) -> bool:
|
||||
return event.get("type") == "result"
|
||||
|
||||
|
||||
# {"type": "result", "structured_output": {"evidence": "...", ...}, ...}
|
||||
def structured_output(stdout) -> object:
|
||||
return (parse(stdout) or {}).get("structured_output")
|
||||
|
||||
|
||||
# Claude Code's config: {"projects": {"/home/me/code/log": {"hasTrustDialogAccepted": true, ...}}, ...}
|
||||
def mark_trusted(config, roots) -> tuple[dict, list[str]] | Failure:
|
||||
projects = config.get("projects", {}) if isinstance(config, dict) else None
|
||||
if not isinstance(projects, dict):
|
||||
return Failure('not an object whose "projects" is an object')
|
||||
if (wrong := next((path for path, record in projects.items() if not isinstance(record, 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
|
||||
|
||||
|
||||
# A model catalog file: {"fetchedAt": 1790618085238, "catalog": {"config": {"models": [{"id": "claude-opus-5-5", "name": "Opus 5.5", ...}]}}}
|
||||
def models_in(files) -> list[tuple[str, object]]:
|
||||
"""The (id, name) of each model in the newest of the parsed catalog files."""
|
||||
newest: dict = {}
|
||||
for data in files:
|
||||
if isinstance(data, dict) and isinstance(data.get("fetchedAt"), (int, float)) and data["fetchedAt"] > newest.get("fetchedAt", -1):
|
||||
newest = data
|
||||
models: object = newest
|
||||
for key in ("catalog", "config", "models"):
|
||||
models = models.get(key) if isinstance(models, dict) else None
|
||||
return [(entry["id"], entry.get("name", entry["id"])) for entry in models if isinstance(entry, dict) and isinstance(entry.get("id"), str)] if isinstance(models, list) else []
|
||||
@@ -1,41 +0,0 @@
|
||||
import dataclasses
|
||||
import glob
|
||||
import os
|
||||
import pathlib
|
||||
import shutil
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
NAMESPACE = uuid.UUID("64fb586b-d926-4bb3-a44c-c903e86d3eec")
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Session:
|
||||
"""Exists while its transcript does."""
|
||||
id: uuid.UUID
|
||||
claude_code_transcripts: pathlib.Path
|
||||
name: str
|
||||
|
||||
|
||||
def session_for(project, paths) -> Session:
|
||||
# "A " is the human's cue in the session picker that the session is the loop's.
|
||||
name = f"A {project} loop-claude"
|
||||
return Session(id=uuid.uuid5(NAMESPACE, name), claude_code_transcripts=paths.claude_code_transcripts, name=name)
|
||||
|
||||
|
||||
# <claude_code_transcripts>/-home-me-code-log/<session id>.jsonl
|
||||
def transcript_file(session) -> str:
|
||||
hit = glob.glob(os.path.join(glob.escape(str(session.claude_code_transcripts)), "*", f"{session.id}.jsonl"))
|
||||
return hit[0] if hit else ""
|
||||
|
||||
|
||||
def delete_session(session) -> None:
|
||||
path = transcript_file(session)
|
||||
if not path:
|
||||
return
|
||||
# <session id>.jsonl, <session id>/subagents/, and from older versions <session id>.superseded-1789290815002/ and <session id>.orphaned-*.jsonl
|
||||
for sibling in glob.glob(glob.escape(path.removesuffix(".jsonl")) + "*"):
|
||||
try:
|
||||
shutil.rmtree(sibling) if os.path.isdir(sibling) else os.remove(sibling)
|
||||
except OSError as failure:
|
||||
print(f"could not remove {sibling}: {failure}", file=sys.stderr)
|
||||
@@ -1,34 +0,0 @@
|
||||
import json
|
||||
|
||||
from loop_claude.claude_code.formats import assistant_parts, human_text, parse, part_text, tool_call
|
||||
from loop_claude.outcome import Failure
|
||||
|
||||
|
||||
def read(path) -> list[dict] | Failure:
|
||||
try:
|
||||
with open(path, "rb") as handle:
|
||||
return [entry for raw in handle if (entry := parse(raw))]
|
||||
except OSError as failure:
|
||||
return Failure(f"could not read the transcript {path}: {failure.strerror}")
|
||||
|
||||
|
||||
def human_turns(entries) -> int:
|
||||
return sum(1 for entry in entries if human_text(entry) is not None)
|
||||
|
||||
|
||||
def render(entries) -> str:
|
||||
lines = []
|
||||
for entry in entries:
|
||||
lines += [line for part in assistant_parts(entry) if (line := part_line(part))]
|
||||
if (text := human_text(entry)) is not None:
|
||||
lines.append("[human] " + text)
|
||||
return "\n\n".join(lines)
|
||||
|
||||
|
||||
def part_line(part, limit=400) -> str:
|
||||
if (text := part_text(part)) and text.strip():
|
||||
return text
|
||||
if call := tool_call(part):
|
||||
name, arguments = call
|
||||
return f"[tool {name}] {json.dumps(arguments)[:limit]}"
|
||||
return ""
|
||||
@@ -1,27 +0,0 @@
|
||||
import json
|
||||
import sys
|
||||
|
||||
from loop_claude.claude_code.formats import mark_trusted
|
||||
from loop_claude.file_writes import replace_json
|
||||
from loop_claude.outcome import Failure
|
||||
|
||||
|
||||
# A failure only warns: the interrupt still runs, and the human answers Claude Code's trust dialog.
|
||||
def trust(config, roots) -> 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)
|
||||
@@ -1,23 +0,0 @@
|
||||
import hashlib
|
||||
import sys
|
||||
|
||||
from loop_claude.file_writes import make_private, replace_file
|
||||
from loop_claude.outcome import Failure
|
||||
|
||||
|
||||
def archive(project, path, note, paths) -> Failure | None:
|
||||
folder = paths.archive / project
|
||||
try:
|
||||
with open(path, "rb") as handle:
|
||||
raw = handle.read()
|
||||
make_private(folder)
|
||||
except OSError as failure:
|
||||
return Failure(f"could not archive the transcript: {failure.filename}: {failure.strerror}")
|
||||
copy = folder / f"{hashlib.sha256(raw).hexdigest()}.jsonl"
|
||||
# The copy lands last, so a copy on disk always has its verdict beside it.
|
||||
if not copy.exists():
|
||||
for dest, data in ((copy.with_suffix(".verdict.md"), f"{note}\n".encode()), (copy, raw)):
|
||||
if unwritten := replace_file(dest, data):
|
||||
return Failure(f"could not archive the transcript: {dest}: {unwritten.reason}")
|
||||
print(f"transcript: {copy}", file=sys.stderr)
|
||||
return None
|
||||
@@ -1,31 +1,31 @@
|
||||
import subprocess
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
from loop_claude import human_needed
|
||||
from loop_claude.claude_code.transcript import human_turns, read
|
||||
from loop_claude.claude_code.trust import trust
|
||||
from loop_claude.outcome import Failure, Stop
|
||||
from loop_claude.project.checkout import checkouts
|
||||
from loop_claude.effects import Effects
|
||||
from failure import Failure
|
||||
from claude_code.transcript import human_turns, read_transcript
|
||||
from loop_claude.stop import needs_human, needs_terminal, Stop
|
||||
from loop_claude.paths import Paths
|
||||
from claude_code.trust import trust
|
||||
from loop_claude.project.checkout import worktrees
|
||||
|
||||
TO = "answer the question above"
|
||||
ANSWER_QUESTION = "answer the question above"
|
||||
|
||||
|
||||
def interrupt(root, session_id, model, path, question, paths) -> Stop | None:
|
||||
def interrupt(root: str, session_id: uuid.UUID, model: str, path: str, question: str, paths: Paths, effects: Effects) -> Stop | None:
|
||||
print(f"\n{question}", file=sys.stderr)
|
||||
if stop := human_needed.off_terminal(TO):
|
||||
if stop := needs_terminal(ANSWER_QUESTION, effects.on_terminal()):
|
||||
return stop
|
||||
trust(paths.claude_json, checkouts(root))
|
||||
entries = read(path)
|
||||
trust(paths.claude_json, worktrees(root, effects))
|
||||
entries = read_transcript(path)
|
||||
if isinstance(entries, Failure):
|
||||
return Stop(1, entries.reason)
|
||||
before = human_turns(entries)
|
||||
try:
|
||||
subprocess.run(["claude", "--model", model, "--permission-mode", "bypassPermissions", "--resume", str(session_id)], cwd=root)
|
||||
effects.claude_on_terminal(["--model", model, "--permission-mode", "bypassPermissions", "--resume", str(session_id)], root)
|
||||
except OSError as failure:
|
||||
return Stop(1, f"could not start claude for the interrupt: {failure.strerror}")
|
||||
entries = read(path)
|
||||
entries = read_transcript(path)
|
||||
if isinstance(entries, Failure):
|
||||
return Stop(1, f"could not tell whether you typed anything: {entries.reason}")
|
||||
if human_turns(entries) <= before:
|
||||
return human_needed.stop(TO, "the interrupt ended with nothing typed")
|
||||
return None
|
||||
return None if human_turns(entries) > before else needs_human(ANSWER_QUESTION, "the interrupt ended with nothing typed")
|
||||
|
||||
+129
-49
@@ -1,50 +1,115 @@
|
||||
import dataclasses
|
||||
import json
|
||||
import subprocess
|
||||
import re
|
||||
import typing
|
||||
|
||||
from loop_claude.claude_code.formats import structured_output
|
||||
from loop_claude.cycle.retry import retried
|
||||
from loop_claude.outcome import Failure, Stop
|
||||
from loop_claude.cycle.prompts import ANSWER_DESTINATIONS, ANSWERS_RECORDED, either
|
||||
from loop_claude.effects import Effects
|
||||
from failure import Failure
|
||||
from claude_code.entries import hit_limit, limit_said, parse_entry, structured_output
|
||||
from loop_claude.project.records import HUMAN_RULE_NAMES
|
||||
from loop_claude.cycle.retry import Limited, retried
|
||||
from loop_claude.stop import Stop
|
||||
|
||||
# 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
|
||||
JUDGE_RULES = (
|
||||
"Decide whether the human must now be interrupted. interrupt=true when any of these appear:\n"
|
||||
"- the agent asks the human anything, seeks approval, or says a decision is the human's\n"
|
||||
"- it carried on under an assumption that decides the deliverable and that the human could "
|
||||
"reasonably reject; 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 release "
|
||||
"ready to cut, a choice outside the repo\n"
|
||||
"- it flags that the goals, the plan or the task itself is unclear, missing or in need of change\n"
|
||||
"- it chose between alternatives the README text does not discriminate between - it does not "
|
||||
"rule the rejected one out - and the choice materially changes the deliverable\n"
|
||||
"- the agent 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"
|
||||
"- 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"
|
||||
"interrupt=false otherwise. Bookkeeping the agent settled silently - what to document, wording, "
|
||||
"where a note goes - is not on its own a reason to interrupt. 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"
|
||||
"is still open, never a question they already answered there. A [loop] line is what loop-claude told "
|
||||
"the agent, such as an answer quoted from README.md or the records.\n"
|
||||
"Where the agent asked or flagged something itself, the question is that one, in the agent's own "
|
||||
"wording; never construct another from facts it stated.\n"
|
||||
"Where README.md or the records answer the agent's own question and no [loop] line has "
|
||||
"quoted that answer yet, set interrupt=false and quote the passage that answers it; the agent is "
|
||||
"then given that passage in place of the human's reply. An interrupt outranks a quoted answer, and either "
|
||||
"outranks finished.\n"
|
||||
"The chunk is the piece of work the agent is on, shipped as one pull request. "
|
||||
"finished=true when the chunk is complete: merged, or nothing remains that the agent could do on "
|
||||
"its own. finished=false when work remains that a further run can continue: an open PR, a review "
|
||||
"not yet run, CI not yet reported."
|
||||
f"its own. Even then, it is finished only once {ANSWERS_RECORDED}. An answer counts as recorded "
|
||||
f"where README.md or the records above hold it, {', '.join(HUMAN_RULE_NAMES)} included. It also counts where "
|
||||
f"the transcript shows the agent writing it into {ANSWER_DESTINATIONS}; writing it into "
|
||||
f"{either(HUMAN_RULE_NAMES)} does not count. finished=false when work remains that a further run can "
|
||||
"continue: an open PR, a review not yet run, CI not yet reported, an answer not yet recorded."
|
||||
)
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Verdict:
|
||||
evidence: str = dataclasses.field(metadata={"description": "A verbatim quote of the transcript line the verdict rests on: what triggers the interrupt, else what shows the chunk finished or the work remaining."})
|
||||
finished: bool
|
||||
interrupt: bool
|
||||
question: str = dataclasses.field(metadata={"description": "The single question to put to the human. Empty when interrupt is false."})
|
||||
class Reply:
|
||||
answer: str = dataclasses.field(metadata={"description": "With interrupt false, the passage of README.md or the records that answers the agent's question, quoted verbatim, without elisions. Empty otherwise."})
|
||||
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 agent'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 agent's question that the answer field answers. Empty otherwise."})
|
||||
|
||||
|
||||
VERDICT_TYPES = typing.get_type_hints(Verdict)
|
||||
REPLY_TYPES = typing.get_type_hints(Reply)
|
||||
JSON_TYPES = {bool: "boolean", str: "string"}
|
||||
JUDGE_SCHEMA = {
|
||||
"properties": {field.name: {**field.metadata, "type": JSON_TYPES[VERDICT_TYPES[field.name]]} for field in dataclasses.fields(Verdict)},
|
||||
"required": list(VERDICT_TYPES),
|
||||
"properties": {field.name: {**field.metadata, "type": JSON_TYPES[REPLY_TYPES[field.name]]} for field in dataclasses.fields(Reply)},
|
||||
"required": list(REPLY_TYPES),
|
||||
"type": "object",
|
||||
}
|
||||
|
||||
|
||||
def judge(root, task, premises, transcript, model) -> Verdict | Stop:
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Interrupt:
|
||||
evidence: str
|
||||
question: str
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class QuotedAnswer:
|
||||
"""The agent asked a question that README.md or the records answer. The answer field quotes the passage."""
|
||||
evidence: str
|
||||
question: str
|
||||
answer: str
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Finished:
|
||||
evidence: str
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Unfinished:
|
||||
evidence: str
|
||||
|
||||
|
||||
Verdict = Interrupt | QuotedAnswer | Finished | Unfinished
|
||||
|
||||
|
||||
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():
|
||||
if not isinstance(output.get(name), kind):
|
||||
return Failure(f"the judge's reply has no {name} of type {JSON_TYPES[kind]}")
|
||||
if output["interrupt"]:
|
||||
if not output["question"].strip():
|
||||
return Failure("the judge interrupted without a question")
|
||||
return Interrupt(output["evidence"], output["question"])
|
||||
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"])
|
||||
return Finished(output["evidence"]) if output["finished"] else Unfinished(output["evidence"])
|
||||
|
||||
|
||||
def judge(root: str, task: str, premises: str, records: str, rendered_transcript: str, model: str, effects: Effects) -> Verdict | Stop:
|
||||
# --json-schema has claude check its reply against the schema and return it as the json result's structured_output.
|
||||
# No tools, so the verdict rests on the transcript grounded() checks it against; no persistence, so its runs stay out of the session picker.
|
||||
args = [
|
||||
"-p",
|
||||
@@ -55,49 +120,64 @@ def judge(root, task, premises, transcript, model) -> Verdict | Stop:
|
||||
"--permission-mode", "bypassPermissions",
|
||||
"--tools", "",
|
||||
]
|
||||
prompt = judge_prompt(task, premises, transcript)
|
||||
return retried("judge", lambda: run_judge(root, args, prompt, transcript))
|
||||
prompt, shown = judge_prompt(task, premises, records, rendered_transcript)
|
||||
return retried("judge", lambda: run_judge(root, args, prompt, shown, f"{premises}\n\n{records}", effects), effects)
|
||||
|
||||
|
||||
def run_judge(root, args, prompt, transcript) -> Verdict | Failure:
|
||||
def run_judge(root: str, args: list[str], prompt: str, shown: str, quotable: str, effects: Effects) -> Verdict | Failure | Limited:
|
||||
try:
|
||||
proc = subprocess.run(["claude", *args], capture_output=True, cwd=root, input=prompt, text=True)
|
||||
proc = effects.claude(args, root, prompt)
|
||||
except OSError as failure:
|
||||
return Failure(f"could not start claude: {failure.strerror}")
|
||||
reply = parse_entry(proc.stdout) or {}
|
||||
# The json output names the reset only in prose, such as "resets 7:40pm (Europe/Stockholm)", so the judge's limit carries no reset time.
|
||||
if hit_limit(reply):
|
||||
return Limited(None, limit_said(reply))
|
||||
if proc.returncode != 0:
|
||||
return Failure(proc.stderr.strip() or f"the judge exited {proc.returncode}")
|
||||
verdict = verdict_from(structured_output(proc.stdout))
|
||||
if isinstance(verdict, Verdict) and not grounded(verdict, transcript):
|
||||
return Failure(f"the judge quoted {verdict.evidence!r}, nothing in the transcript" + (f", for the question: {verdict.question}" if verdict.interrupt else ""))
|
||||
verdict = verdict_from(structured_output(reply))
|
||||
if isinstance(verdict, Failure):
|
||||
return Failure(f"{verdict.reason}; it replied: {proc.stdout.strip() or 'nothing'}")
|
||||
if not grounded(verdict.evidence, shown):
|
||||
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 ""))
|
||||
# Not a Failure: a misquote would otherwise exit an unattended loop. Never elided: stitched fragments can say what the records do not.
|
||||
if isinstance(verdict, QuotedAnswer) and not verbatim(verdict.answer, quotable):
|
||||
return Interrupt(verdict.evidence, verdict.question)
|
||||
return verdict
|
||||
|
||||
|
||||
def judge_prompt(task, premises, transcript) -> str:
|
||||
return (
|
||||
def judge_prompt(task: str, premises: str, records: str, rendered_transcript: str) -> tuple[str, str]:
|
||||
"""The prompt, and the part of the transcript it shows, which the judge's evidence must quote."""
|
||||
head = (
|
||||
f"From README.md:\n{premises}\n\n"
|
||||
f"The records: the project's working rules and decisions, then the human's rules for every project:\n{records or 'none'}\n\n"
|
||||
f"The task an agent was given:\n{task}\n\n"
|
||||
# The tail, where an interrupt or a finish lands; the session's transcript grows cycle over cycle.
|
||||
f"What the agent did and said, and what the human typed on [human] lines, latest last:\n{transcript[-40000:]}\n\n"
|
||||
f"{JUDGE_RULES}"
|
||||
"What the agent did and said, what the human typed on [human] lines and what loop-claude told it on [loop] lines, latest last:\n"
|
||||
)
|
||||
room = max(0, JUDGE_PROMPT_CHARS - len(head) - len(JUDGE_RULES) - 2)
|
||||
# The tail, where an interrupt or a finish lands; the session's transcript grows cycle over cycle.
|
||||
shown = rendered_transcript[max(0, len(rendered_transcript) - room):]
|
||||
return f"{head}{shown}\n\n{JUDGE_RULES}", shown
|
||||
|
||||
|
||||
def verdict_from(output) -> Verdict | Failure:
|
||||
if not isinstance(output, dict):
|
||||
return Failure("the judge returned no verdict")
|
||||
for name, kind in VERDICT_TYPES.items():
|
||||
if not isinstance(output.get(name), kind):
|
||||
return Failure(f"the judge's verdict has no {name} of type {JSON_TYPES[kind]}")
|
||||
if output["interrupt"] and not output["question"].strip():
|
||||
return Failure("the judge interrupted without a question")
|
||||
return Verdict(**{name: output[name] for name in VERDICT_TYPES})
|
||||
def grounded(evidence: str, rendered_transcript: str) -> bool:
|
||||
# The judge joins passages with an ellipsis though told to quote one.
|
||||
fragments = [fragment.strip() for fragment in re.split(r"\.\.\.|…", plain(evidence)) if fragment.strip()]
|
||||
transcript = plain(rendered_transcript)
|
||||
at = 0
|
||||
for fragment in fragments:
|
||||
found = transcript.find(fragment, at)
|
||||
if found < 0:
|
||||
return False
|
||||
at = found + len(fragment)
|
||||
return fragments != []
|
||||
|
||||
|
||||
def grounded(verdict, transcript) -> bool:
|
||||
evidence = plain(verdict.evidence)
|
||||
return evidence != "" and evidence in plain(transcript)
|
||||
def verbatim(quote: str, text: str) -> bool:
|
||||
quoted = plain(quote)
|
||||
return quoted != "" and quoted in plain(text)
|
||||
|
||||
|
||||
def plain(text) -> str:
|
||||
def plain(text: str) -> str:
|
||||
# The judge drops markdown emphasis and reflows whitespace when it quotes.
|
||||
return " ".join(text.replace("*", "").replace("_", "").split())
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
from loop_claude.project.records import HUMAN_RULE_NAMES, RECORD_FILES
|
||||
from markdown_text import quoted
|
||||
|
||||
def either(names: tuple[str, ...]) -> str:
|
||||
"""The names as `a, b or c`."""
|
||||
return f"{', '.join(names[:-1])} or {names[-1]}"
|
||||
|
||||
|
||||
# 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.
|
||||
QUOTE_SOURCES = either(("README.md's Goals and Audience", *RECORD_FILES, *HUMAN_RULE_NAMES))
|
||||
# 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"
|
||||
|
||||
|
||||
def fresh(task: str) -> str:
|
||||
return f"{task}\n\nContinue any open draft PR or worktree for the chunk before creating a new one."
|
||||
|
||||
|
||||
def resumed(unfinished_evidence: str) -> str:
|
||||
ruled = f" A judge ruled the chunk unfinished, quoting this passage of your transcript as the work remaining:\n\n{quoted(unfinished_evidence)}\n\n" if unfinished_evidence else " "
|
||||
return f"Continue the task; the previous run ended before the chunk was finished.{ruled}The chunk is finished once it is merged, or nothing remains that you could do on your own. Even then, it is finished only once {ANSWERS_RECORDED}."
|
||||
|
||||
|
||||
def answered(question: str, answer: str) -> str:
|
||||
return f"Your question: {question}\n\n{QUOTE_SOURCES} answers it:\n\n{answer}\n\nContinue the task."
|
||||
|
||||
|
||||
def past_the_cap(question: str, answer: str, cap: int) -> str:
|
||||
"""The question a quoted answer puts to the human once the cycle's quoted answers reach the cap."""
|
||||
return f"{question}\n\n{QUOTE_SOURCES} says:\n{answer}\n\nThose files have answered {cap} questions this cycle, the most allowed, so this one comes to you."
|
||||
@@ -1,20 +1,49 @@
|
||||
import dataclasses
|
||||
import sys
|
||||
import time
|
||||
import typing
|
||||
|
||||
from loop_claude.outcome import Failure, Stop
|
||||
from loop_claude.effects import Effects
|
||||
from failure import Failure
|
||||
from loop_claude.stop import Stop
|
||||
|
||||
T = typing.TypeVar("T")
|
||||
|
||||
FAILURES_RUNNING = 3
|
||||
PAST_RESET = 120
|
||||
RETRY_DELAY = 60
|
||||
UNKNOWN_RESET_POLL = 600
|
||||
|
||||
def retried(who, attempt: typing.Callable[[], T | Failure]) -> T | Stop:
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Limited:
|
||||
"""claude hit a usage limit; said is claude's message about it, and resets_at is when the limit resets, in seconds since the epoch, or None when unknown."""
|
||||
resets_at: int | None
|
||||
said: str
|
||||
|
||||
|
||||
def retried(who: str, attempt: typing.Callable[[], T | Failure | Limited], effects: Effects) -> T | Stop:
|
||||
failures = 0
|
||||
while True:
|
||||
failures += 1
|
||||
result = attempt()
|
||||
if isinstance(result, Limited):
|
||||
# Hitting the limit proves claude started and reached the API, so the failures before it stop counting towards three.
|
||||
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)
|
||||
effects.sleep(wait)
|
||||
continue
|
||||
if not isinstance(result, Failure):
|
||||
return result
|
||||
if failures == 3:
|
||||
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)
|
||||
time.sleep(60)
|
||||
effects.sleep(RETRY_DELAY)
|
||||
|
||||
|
||||
def limit_wait(limited: Limited, now: float) -> float:
|
||||
# The limit rejects every request until it resets, so wait for a known reset and poll rarely for an unknown one.
|
||||
if limited.resets_at is not None and limited.resets_at + PAST_RESET > now:
|
||||
return limited.resets_at + PAST_RESET - now
|
||||
return UNKNOWN_RESET_POLL
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
import dataclasses
|
||||
import pathlib
|
||||
import typing
|
||||
|
||||
from loop_claude.cycle.states import Active, Archived, Closing, Ended, Event, HumanAnswered, Interrupting, Judging, QUOTED_ANSWERS_PER_CYCLE, Ruled, State, transition, WorkerRan, Working
|
||||
from transcript_archive.write import archive
|
||||
from claude_code.session import delete_session, Session, session_open, transcript_file
|
||||
from loop_claude.effects import Effects
|
||||
from failure import Failure
|
||||
from loop_claude.cycle.judge import Finished, Interrupt, judge, QuotedAnswer, Unfinished
|
||||
from loop_claude.cycle.interrupt import interrupt
|
||||
from loop_claude.project.model_choice import Models
|
||||
from transcript_archive import outcomes
|
||||
from loop_claude.paths import Paths
|
||||
from loop_claude.cycle import prompts
|
||||
from claude_code.transcript import read_transcript, render
|
||||
from loop_claude.cycle.retry import retried
|
||||
from loop_claude.cycle.worker import run_worker, worker_args
|
||||
from loop_claude.stop import Stop
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Cycle:
|
||||
effects: Effects
|
||||
models: Models
|
||||
paths: Paths
|
||||
premises: str
|
||||
project_archive: pathlib.Path
|
||||
records: str
|
||||
root: str
|
||||
session: Session
|
||||
task: str
|
||||
# Empty when the previous cycle's verdict was not Unfinished.
|
||||
unfinished_evidence: str
|
||||
|
||||
|
||||
def run_cycle(cycle: Cycle) -> Stop | Finished | Unfinished:
|
||||
state: State = Working()
|
||||
try:
|
||||
while not isinstance(state, Ended):
|
||||
event = step(cycle, state)
|
||||
if isinstance(event, Stop):
|
||||
return stopped(cycle, event, event.reason)
|
||||
state = transition(state, event)
|
||||
except KeyboardInterrupt:
|
||||
return stopped(cycle, Stop(130, ""), "Ctrl-C")
|
||||
return state.verdict
|
||||
|
||||
|
||||
def stopped(cycle: Cycle, stop: Stop, why: str) -> Stop:
|
||||
path = transcript_file(cycle.session)
|
||||
failure = archive(cycle.project_archive, path, cycle.task, outcomes.stopped(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 Stop(1, f"{failure.reason}\n{stop.reason}".rstrip()) if failure and failure.reason != stop.reason else stop
|
||||
|
||||
|
||||
def step(cycle: Cycle, state: Active) -> Event | Stop:
|
||||
match state:
|
||||
case Working(answered, _):
|
||||
return work(cycle, answered)
|
||||
case Judging(transcript_path, _):
|
||||
return rule(cycle, transcript_path)
|
||||
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 | None) -> WorkerRan | Stop:
|
||||
if answered is not None:
|
||||
print(f"\n=== {prompts.QUOTE_SOURCES} answered: {answered.question} ===\n{answered.answer}", flush=True)
|
||||
if stop := keep_answer(cycle, answered):
|
||||
return stop
|
||||
# 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), 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_start(cycle: Cycle, answered: QuotedAnswer | None) -> list[str]:
|
||||
if answered is not None:
|
||||
return worker_args(cycle.session, cycle.models.worker, prompts.answered(answered.question, answered.answer), resume=True)
|
||||
if session_open(cycle.session):
|
||||
return worker_args(cycle.session, cycle.models.worker, prompts.resumed(cycle.unfinished_evidence), resume=True)
|
||||
return worker_args(cycle.session, cycle.models.worker, prompts.fresh(cycle.task), resume=False)
|
||||
|
||||
|
||||
def keep_answer(cycle: Cycle, answered: QuotedAnswer) -> Stop | None:
|
||||
path = transcript_file(cycle.session)
|
||||
if path and (failure := archive(cycle.project_archive, path, cycle.task, outcomes.answered(answered.question, prompts.QUOTE_SOURCES, answered.answer, answered.evidence), cycle.effects.now())):
|
||||
return Stop(1, failure.reason)
|
||||
return None
|
||||
|
||||
|
||||
def rule(cycle: Cycle, transcript_path: str) -> Ruled | Stop:
|
||||
entries = read_transcript(transcript_path)
|
||||
if isinstance(entries, Failure):
|
||||
return Stop(1, entries.reason)
|
||||
verdict = judge(cycle.root, cycle.task, cycle.premises, cycle.records, render(entries), cycle.models.judge, cycle.effects)
|
||||
return verdict if isinstance(verdict, Stop) else Ruled(verdict)
|
||||
|
||||
|
||||
def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer) -> HumanAnswered | 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.
|
||||
if failure := archive(cycle.project_archive, transcript_path, cycle.task, outcomes.interrupted(question, ruling.evidence), cycle.effects.now()):
|
||||
return Stop(1, failure.reason)
|
||||
return interrupt(cycle.root, cycle.session.id, cycle.models.worker, transcript_path, question, cycle.paths, cycle.effects) or HumanAnswered()
|
||||
|
||||
|
||||
def question_for(ruling: Interrupt | QuotedAnswer) -> str:
|
||||
if isinstance(ruling, Interrupt):
|
||||
return ruling.question
|
||||
return prompts.past_the_cap(ruling.question, ruling.answer, QUOTED_ANSWERS_PER_CYCLE)
|
||||
|
||||
|
||||
def close(cycle: Cycle, transcript_path: str, verdict: Finished | Unfinished) -> Archived | Stop:
|
||||
finished = isinstance(verdict, Finished)
|
||||
if failure := archive(cycle.project_archive, transcript_path, cycle.task, outcomes.finished(verdict.evidence) if finished else outcomes.unfinished(verdict.evidence), cycle.effects.now()):
|
||||
return Stop(1, failure.reason)
|
||||
if finished and (failure := delete_session(cycle.session)):
|
||||
return Stop(1, failure.reason)
|
||||
return Archived()
|
||||
@@ -0,0 +1,86 @@
|
||||
import dataclasses
|
||||
|
||||
from loop_claude.cycle.judge import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict
|
||||
|
||||
# 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
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Working:
|
||||
"""The worker runs, resumed with an answer quoted from README.md or the records when there is one."""
|
||||
answered: QuotedAnswer | None = None
|
||||
quoted_answers: int = 0
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Judging:
|
||||
"""The judge rules; quoted_answers counts the questions README.md or the records answered this cycle, and an interrupt does not reset it."""
|
||||
transcript_path: str
|
||||
quoted_answers: int = 0
|
||||
|
||||
|
||||
@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."""
|
||||
transcript_path: str
|
||||
ruling: Interrupt | QuotedAnswer
|
||||
quoted_answers: int = 0
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Closing:
|
||||
transcript_path: str
|
||||
verdict: Finished | Unfinished
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Ended:
|
||||
verdict: Finished | Unfinished
|
||||
|
||||
|
||||
Active = Working | Judging | Interrupting | Closing
|
||||
State = Active | Ended
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class WorkerRan:
|
||||
transcript_path: str
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Ruled:
|
||||
verdict: Verdict
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class HumanAnswered:
|
||||
pass
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Archived:
|
||||
pass
|
||||
|
||||
|
||||
Event = WorkerRan | Ruled | HumanAnswered | Archived
|
||||
|
||||
|
||||
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) if quoted_answers < QUOTED_ANSWERS_PER_CYCLE:
|
||||
return Working(answered, quoted_answers + 1)
|
||||
case Judging(transcript_path, quoted_answers), Ruled(QuotedAnswer() as ruling) if quoted_answers >= QUOTED_ANSWERS_PER_CYCLE:
|
||||
return Interrupting(transcript_path, ruling, quoted_answers)
|
||||
case Judging(transcript_path, quoted_answers), Ruled(Interrupt() as ruling):
|
||||
return Interrupting(transcript_path, ruling, quoted_answers)
|
||||
case Judging(transcript_path, _), Ruled(Finished() | Unfinished() as verdict):
|
||||
return Closing(transcript_path, verdict)
|
||||
# The human works in the interrupt's claude session, so the judge rules again on the transcript it leaves.
|
||||
case Interrupting(transcript_path, _, quoted_answers), HumanAnswered():
|
||||
return Judging(transcript_path, quoted_answers)
|
||||
case Closing(_, verdict), Archived():
|
||||
return Ended(verdict)
|
||||
raise ValueError(f"no transition from {state} on {event}")
|
||||
@@ -1,55 +0,0 @@
|
||||
import dataclasses
|
||||
|
||||
from loop_claude.claude_code.session import Session, delete_session, transcript_file
|
||||
from loop_claude.claude_code.transcript import read, render
|
||||
from loop_claude.cycle.archive import archive
|
||||
from loop_claude.cycle.interrupt import interrupt
|
||||
from loop_claude.cycle.judge import Verdict, judge
|
||||
from loop_claude.cycle.retry import retried
|
||||
from loop_claude.cycle.worker import run_worker, worker_args
|
||||
from loop_claude.outcome import Failure, Stop
|
||||
from loop_claude.paths import Paths
|
||||
from loop_claude.project.models import Models
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Cycle:
|
||||
models: Models
|
||||
paths: Paths
|
||||
premises: str
|
||||
project: str
|
||||
root: str
|
||||
session: Session
|
||||
task: str
|
||||
|
||||
|
||||
def run_cycle(cycle) -> Stop | None:
|
||||
if stop := retried("worker", lambda: run_worker(cycle.root, worker_args(cycle.task, cycle.session, cycle.models.worker, bool(transcript_file(cycle.session))))):
|
||||
return stop
|
||||
path = transcript_file(cycle.session)
|
||||
if not path:
|
||||
return Stop(1, f"claude left no transcript for session {cycle.session.id}")
|
||||
verdict = judge_through_interrupts(cycle, path)
|
||||
if isinstance(verdict, Stop):
|
||||
return verdict
|
||||
if verdict.finished:
|
||||
if failure := archive(cycle.project, path, f"Task: {cycle.task}\n\nVerdict: finished", cycle.paths):
|
||||
return Stop(1, failure.reason)
|
||||
delete_session(cycle.session)
|
||||
return None
|
||||
|
||||
|
||||
def judge_through_interrupts(cycle, path) -> Verdict | Stop:
|
||||
# The interrupt appends to this transcript, so each pass judges and archives it anew.
|
||||
while True:
|
||||
entries = read(path)
|
||||
if isinstance(entries, Failure):
|
||||
return Stop(1, entries.reason)
|
||||
verdict = judge(cycle.root, cycle.task, cycle.premises, render(entries), cycle.models.judge)
|
||||
if isinstance(verdict, Stop) or not verdict.interrupt:
|
||||
return verdict
|
||||
if failure := archive(cycle.project, path, f"Task: {cycle.task}\n\nVerdict: interrupt\n\n{verdict.question}", cycle.paths):
|
||||
return Stop(1, failure.reason)
|
||||
if stop := interrupt(cycle.root, cycle.session.id, cycle.models.worker, path, verdict.question, cycle.paths):
|
||||
return stop
|
||||
|
||||
@@ -1,37 +1,48 @@
|
||||
import subprocess
|
||||
from claude_code.entries import assistant_parts, ends_stream, hit_limit, limit_said, parse_entry, rejected_until
|
||||
from loop_claude.effects import Effects
|
||||
from failure import Failure
|
||||
from loop_claude.cycle.retry import Limited
|
||||
from claude_code.transcript import part_line
|
||||
from claude_code.session import Session
|
||||
|
||||
from loop_claude.claude_code.formats import assistant_parts, ends_stream, parse
|
||||
from loop_claude.claude_code.transcript import part_line
|
||||
from loop_claude.outcome import Failure
|
||||
PRINTED_TOOL_INPUT = 160
|
||||
|
||||
|
||||
def run_worker(root, args) -> Failure | None:
|
||||
def run_worker(root: str, args: list[str], effects: Effects) -> Failure | Limited | None:
|
||||
try:
|
||||
proc = subprocess.Popen(["claude", *args], cwd=root, encoding="utf-8", errors="replace", stdin=subprocess.DEVNULL, stdout=subprocess.PIPE)
|
||||
proc = effects.stream_claude(args, root)
|
||||
except OSError as failure:
|
||||
return Failure(f"could not start claude: {failure.strerror}")
|
||||
with proc:
|
||||
done = False
|
||||
for raw in proc.stdout or ():
|
||||
event = parse(raw) or {}
|
||||
done = done or ends_stream(event)
|
||||
for part in assistant_parts(event):
|
||||
if line := part_line(part, 160):
|
||||
print(line, flush=True)
|
||||
code = proc.wait()
|
||||
result: dict | None = None
|
||||
resets: list[int] = []
|
||||
for raw in proc.lines():
|
||||
event = parse_entry(raw) or {}
|
||||
if ends_stream(event):
|
||||
result = event
|
||||
if (resets_at := rejected_until(event)) is not None:
|
||||
resets.append(resets_at)
|
||||
for part in assistant_parts(event):
|
||||
if line := part_line(part, PRINTED_TOOL_INPUT):
|
||||
print(line, flush=True)
|
||||
return worker_outcome(proc.wait(), result, resets)
|
||||
|
||||
|
||||
def worker_outcome(code: int, result: dict | None, resets: list[int]) -> Failure | Limited | None:
|
||||
if result is not None and hit_limit(result):
|
||||
return Limited(max(resets, default=None), limit_said(result))
|
||||
if code < 0:
|
||||
return Failure(f"claude killed by signal {-code}")
|
||||
if code:
|
||||
return Failure(f"claude exited {code}")
|
||||
return None if done else Failure("claude exited 0 without a result event")
|
||||
return None if result is not None else Failure("claude exited 0 without a result event")
|
||||
|
||||
|
||||
def worker_args(task, session, model, resuming) -> list[str]:
|
||||
if resuming:
|
||||
start = ["-p", "Continue the task; the previous run stopped before it was finished.", "--resume", str(session.id)]
|
||||
else:
|
||||
start = ["-p", f"{task}\n\nContinue any open draft PR or worktree for the chunk before creating a new one.", "--name", session.name, "--session-id", str(session.id)]
|
||||
def worker_args(session: Session, model: str, prompt: str, resume: bool) -> list[str]:
|
||||
# --session-id creates the session under the id loop-claude keeps; --resume continues that session.
|
||||
start = ["--resume", str(session.id)] if resume else ["--name", session.name, "--session-id", str(session.id)]
|
||||
# -p fails without --verbose under stream-json.
|
||||
return [
|
||||
"-p", prompt,
|
||||
*start,
|
||||
"--output-format", "stream-json",
|
||||
"--permission-mode", "bypassPermissions",
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import dataclasses
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import typing
|
||||
|
||||
|
||||
class Streaming(typing.Protocol):
|
||||
"""A started claude whose stream-json lines arrive as it works."""
|
||||
|
||||
def lines(self) -> typing.Iterable[str]: ...
|
||||
|
||||
def wait(self) -> int: ...
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Effects:
|
||||
claude: typing.Callable[[list[str], str, str], subprocess.CompletedProcess[str]]
|
||||
claude_on_terminal: typing.Callable[[list[str], str], int]
|
||||
execv: typing.Callable[[str, list[str]], None]
|
||||
git: typing.Callable[[list[str], str], subprocess.CompletedProcess[str]]
|
||||
input: typing.Callable[[str], str]
|
||||
local_time: typing.Callable[[float], str]
|
||||
now: typing.Callable[[], float]
|
||||
on_terminal: typing.Callable[[], bool]
|
||||
python: typing.Callable[[list[str]], subprocess.CompletedProcess[str]]
|
||||
sleep: typing.Callable[[float], None]
|
||||
stream_claude: typing.Callable[[list[str], str], Streaming]
|
||||
|
||||
|
||||
class StreamingClaude:
|
||||
def __init__(self, args: list[str], cwd: str) -> None:
|
||||
self.proc = subprocess.Popen(["claude", *args], cwd=cwd, encoding="utf-8", errors="replace", stdin=subprocess.DEVNULL, stdout=subprocess.PIPE)
|
||||
|
||||
def lines(self) -> typing.Iterable[str]:
|
||||
with self.proc:
|
||||
yield from self.proc.stdout or ()
|
||||
|
||||
def wait(self) -> int:
|
||||
return self.proc.wait()
|
||||
|
||||
|
||||
def system_effects() -> Effects:
|
||||
return Effects(
|
||||
claude=lambda args, cwd, stdin: subprocess.run(["claude", *args], capture_output=True, cwd=cwd, input=stdin, text=True),
|
||||
claude_on_terminal=lambda args, cwd: subprocess.run(["claude", *args], cwd=cwd).returncode,
|
||||
execv=os.execv,
|
||||
git=lambda args, cwd: subprocess.run(["git", *args], capture_output=True, cwd=cwd, text=True),
|
||||
input=input,
|
||||
local_time=lambda seconds: time.strftime("%Y-%m-%d %H:%M %Z", time.localtime(seconds)),
|
||||
now=time.time,
|
||||
on_terminal=lambda: sys.stdin.isatty() and sys.stdout.isatty(),
|
||||
python=lambda args: subprocess.run([sys.executable, *args], capture_output=True, text=True),
|
||||
sleep=time.sleep,
|
||||
stream_claude=StreamingClaude,
|
||||
)
|
||||
@@ -1,13 +0,0 @@
|
||||
import sys
|
||||
|
||||
from loop_claude.outcome import Stop
|
||||
|
||||
|
||||
def stop(to, but) -> Stop:
|
||||
return Stop(2, f"the human is needed to {to}, but {but}")
|
||||
|
||||
|
||||
def off_terminal(to) -> Stop | None:
|
||||
if sys.stdin.isatty() and sys.stdout.isatty():
|
||||
return None
|
||||
return stop(to, "stdin or stdout is not a terminal; rerun loop-claude on a terminal")
|
||||
+106
-50
@@ -3,51 +3,99 @@
|
||||
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 judge then reads
|
||||
the transcript against them and rules whether the chunk, the work of one PR, is finished.
|
||||
premises; the task runs at the checkout root. Each cycle a worker runs the task. 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.
|
||||
A question only the human can answer, or a release ready to cut, is an interrupt: `claude --resume`
|
||||
on the terminal, every worktree first marked trusted in ~/.claude.json. An unfinished chunk resumes
|
||||
its session next cycle; the next chunk starts a fresh session.
|
||||
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".
|
||||
|
||||
Exit 1: no task, not inside a checkout, no premises, a models file it cannot read or write, claude
|
||||
leaves no transcript or one it cannot read or archive, claude cannot start for an interrupt, a
|
||||
reload with unreadable state, or 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 or exits non-zero, or its verdict misses or
|
||||
mistypes a field, interrupts without a question, or quotes nothing in the transcript.
|
||||
Exit 2: the human is needed, to pick the model or answer an interrupt, and stdin or stdout is not a
|
||||
terminal, the input ends, or the interrupt ended with nothing typed. Rerunning resumes any
|
||||
open session.
|
||||
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 to $LOOP_CLAUDE_TRANSCRIPTS/<key>/<chunk>/<sha256>.jsonl (default
|
||||
~/.claude/loop-claude-transcripts), named by its hash. <chunk> is the hash of the transcript's first
|
||||
line with a timestamp, the same for every cycle of a chunk. Beside the copy, <sha256>.outcomes.md
|
||||
holds the verdict, with the transcript passage the judge rested it on; each answer the judge
|
||||
quoted, with the question it answers; and why the loop stopped. Each of these opens with its UTC
|
||||
time. Claude Code keeps a folder per session beside its transcript, holding the subagents'
|
||||
transcripts among other files; that folder, and every other file named after the session except
|
||||
the transcript, are copied into <chunk>/session/. A file there is replaced only by a version that
|
||||
grew from it. A file Claude Code rewrote lands beside its copy as <name>.<hash of its content>.
|
||||
|
||||
Each project has one session, "A <path> loop-claude", <path> being the checkout relative to ~/code,
|
||||
or to / outside it, deleted when the chunk finishes. At every interrupt and when the chunk finishes
|
||||
its transcript is copied to $LOOP_CLAUDE_TRANSCRIPTS/<path>/<sha256>.jsonl (default
|
||||
~/.claude/loop-claude-transcripts), the verdict beside it in <sha256>.verdict.md.
|
||||
Every claude loop-claude starts runs the project's model, saved per <key> in
|
||||
~/.claude/loop-claude-models.json and read each cycle; a project without an entry, as on its first
|
||||
run, is asked for one. LOOP_CLAUDE_JUDGE_MODEL overrides it for the judge, LOOP_CLAUDE_WORKER_MODEL
|
||||
for the worker and the interrupt; with both set, nothing is asked.
|
||||
|
||||
Every claude it starts runs the project's model, saved per <path> in ~/.claude/loop-claude-models.json
|
||||
and read each cycle; a project without an entry, as on its first run, is asked for one.
|
||||
LOOP_CLAUDE_JUDGE_MODEL overrides it for the judge, LOOP_CLAUDE_WORKER_MODEL for the worker and the
|
||||
interrupt; with both set, nothing is asked.
|
||||
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 or exits non-zero, 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 ends with nothing typed
|
||||
Rerunning resumes any open session.
|
||||
|
||||
A change to bin/loop-claude or bin/loop_claude/**/*.py takes effect at the next cycle boundary, once
|
||||
loop-claude --help succeeds.
|
||||
"""
|
||||
import dataclasses
|
||||
import pathlib
|
||||
import sys
|
||||
import typing
|
||||
|
||||
from loop_claude.claude_code.session import session_for
|
||||
from loop_claude.cycle.steps import Cycle, run_cycle
|
||||
from loop_claude.loop.reload import RELOAD_FLAG, LoopState, decode_state, exec_if_edited, fingerprint
|
||||
from loop_claude.outcome import Stop
|
||||
from loop_claude.project.checkout import checkout_root, project_name
|
||||
from loop_claude.project.models import project_models
|
||||
from loop_claude.project.checkout import checkout_root
|
||||
from loop_claude.cycle.run import Cycle, run_cycle
|
||||
from loop_claude.loop.reload import decode_handed, exec_if_edited, fingerprint, LoopRun, RELOAD_FLAG
|
||||
from loop_claude.effects import Effects
|
||||
from loop_claude.project.model_choice import get_or_ask_models
|
||||
from loop_claude.paths import Paths
|
||||
from transcript_archive.location import project_archive
|
||||
from project_key import project_key
|
||||
from loop_claude.project.premises import read_premises
|
||||
from loop_claude.project.records import read_records
|
||||
from claude_code.session import session_named
|
||||
from loop_claude.stop import Stop
|
||||
from loop_claude.cycle.judge import Unfinished
|
||||
|
||||
|
||||
def main(argv, env, paths, launcher, cwd) -> int:
|
||||
def main(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher: pathlib.Path, cwd: pathlib.Path, effects: Effects) -> int:
|
||||
try:
|
||||
stop = run_loop(argv, env, paths, launcher, cwd)
|
||||
stop = run_loop(argv, env, paths, launcher, cwd, effects)
|
||||
except KeyboardInterrupt:
|
||||
stop = Stop(130, "")
|
||||
if stop.reason:
|
||||
@@ -55,35 +103,43 @@ def main(argv, env, paths, launcher, cwd) -> int:
|
||||
return stop.code
|
||||
|
||||
|
||||
def run_loop(argv, env, paths, launcher, cwd) -> Stop:
|
||||
state = loop_state(argv, cwd)
|
||||
if isinstance(state, Stop):
|
||||
return state
|
||||
def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher: pathlib.Path, cwd: pathlib.Path, effects: Effects) -> Stop:
|
||||
loop_run = loop_run_from(argv, cwd, effects)
|
||||
if isinstance(loop_run, Stop):
|
||||
return loop_run
|
||||
baseline = fingerprint(launcher)
|
||||
project = project_name(state.root, paths.code)
|
||||
session = session_for(project, paths)
|
||||
key = project_key(loop_run.root, paths.home)
|
||||
archive = 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:
|
||||
exec_if_edited(launcher, baseline, state)
|
||||
state = dataclasses.replace(state, cycle_number=state.cycle_number + 1)
|
||||
premises = read_premises(state.root)
|
||||
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
|
||||
models = project_models(project, paths, env)
|
||||
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
|
||||
print(f"\n=== cycle {state.cycle_number} ===", flush=True)
|
||||
if stop := run_cycle(Cycle(models=models, paths=paths, premises=premises, project=project, root=state.root, session=session, task=state.task)):
|
||||
return stop
|
||||
print(f"\n=== cycle {loop_run.cycle_number} ===", flush=True)
|
||||
verdict = run_cycle(Cycle(effects=effects, models=models, paths=paths, premises=premises, project_archive=archive, records=records, root=loop_run.root, session=session, task=loop_run.task, unfinished_evidence=loop_run.unfinished_evidence))
|
||||
if isinstance(verdict, Stop):
|
||||
return verdict
|
||||
loop_run = dataclasses.replace(loop_run, unfinished_evidence=verdict.evidence if isinstance(verdict, Unfinished) else "")
|
||||
|
||||
|
||||
def loop_state(argv, cwd) -> LoopState | Stop:
|
||||
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())
|
||||
root = checkout_root(cwd)
|
||||
return root if isinstance(root, Stop) else LoopState(0, root, task)
|
||||
state = decode_state(argv[1], LoopState) if len(argv) == 2 else None
|
||||
if not (state and state.root and state.task):
|
||||
return Stop(1, f"the reload cannot read the loop's state from {argv[1:]}; rerun loop-claude <task>")
|
||||
return state
|
||||
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
|
||||
if not (loop_run and loop_run.root and loop_run.task):
|
||||
return Stop(1, f"the edited loop-claude cannot read the state the running one handed it, likely because the edit changed that handover; rerun loop-claude <task>. Handed: {' '.join(argv[1:])}")
|
||||
return loop_run
|
||||
|
||||
@@ -1,24 +1,28 @@
|
||||
import dataclasses
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import pathlib
|
||||
import sys
|
||||
import typing
|
||||
|
||||
from loop_claude.effects import Effects
|
||||
from loop_claude.stop import Stop
|
||||
|
||||
RELOAD_FLAG = "--reloaded"
|
||||
T = typing.TypeVar("T")
|
||||
|
||||
|
||||
# A field change stops a running loop at its next reload: the new script rejects the old fields.
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class LoopState:
|
||||
class LoopRun:
|
||||
"""What a reload hands the edited script, as JSON on argv."""
|
||||
cycle_number: int
|
||||
root: str
|
||||
task: str
|
||||
unfinished_evidence: str
|
||||
|
||||
|
||||
def decode_state(handed, kind: type[T]) -> T | None:
|
||||
def decode_handed(handed: str, kind: type[T]) -> T | None:
|
||||
try:
|
||||
fields = json.loads(handed)
|
||||
except ValueError:
|
||||
@@ -31,9 +35,9 @@ def decode_state(handed, kind: type[T]) -> T | None:
|
||||
return kind(**fields)
|
||||
|
||||
|
||||
def fingerprint(launcher) -> str:
|
||||
def fingerprint(launcher: pathlib.Path) -> str:
|
||||
digest = hashlib.sha256()
|
||||
for path in [launcher, *sorted((launcher.parent / "loop_claude").rglob("*.py"))]:
|
||||
for path in [launcher, *sorted(launcher.parent.rglob("*.py"))]:
|
||||
try:
|
||||
content = path.read_bytes()
|
||||
except OSError as failure:
|
||||
@@ -42,11 +46,16 @@ def fingerprint(launcher) -> str:
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def exec_if_edited(launcher, baseline, state) -> None:
|
||||
# A loop runs unattended for hours, often on its own checkout: reloading puts each edit to loop-claude to use without the human rerunning it.
|
||||
def exec_if_edited(launcher: pathlib.Path, baseline: str, loop_run: LoopRun, effects: Effects) -> Stop | None:
|
||||
if fingerprint(launcher) == baseline:
|
||||
return
|
||||
trial = subprocess.run([sys.executable, launcher, "--help"], capture_output=True, text=True)
|
||||
if trial.returncode != 0:
|
||||
print(f"keeping the running script: {trial.stderr.strip() or f'exit {trial.returncode}'}", file=sys.stderr)
|
||||
return
|
||||
os.execv(sys.executable, [sys.executable, str(launcher), RELOAD_FLAG, json.dumps(dataclasses.asdict(state))])
|
||||
return None
|
||||
try:
|
||||
trial = effects.python([str(launcher), "--help"])
|
||||
if trial.returncode != 0:
|
||||
print(f"keeping the running script: {trial.stderr.strip() or f'exit {trial.returncode}'}", file=sys.stderr)
|
||||
return None
|
||||
effects.execv(sys.executable, [sys.executable, str(launcher), RELOAD_FLAG, json.dumps(dataclasses.asdict(loop_run))])
|
||||
except OSError as failure:
|
||||
return Stop(1, f"could not reload loop-claude: {failure.strerror}; rerun loop-claude <task>")
|
||||
return None
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
import dataclasses
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Failure:
|
||||
"""A step failed and its caller decides: `retried` reruns a worker or judge run until it fails three times running; anything else becomes a Stop or a warning."""
|
||||
reason: str
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Stop:
|
||||
"""loop-claude exits with code, printing reason."""
|
||||
code: int
|
||||
reason: str
|
||||
@@ -4,21 +4,21 @@ import pathlib
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Paths:
|
||||
archive: pathlib.Path
|
||||
claude_code_transcripts: pathlib.Path
|
||||
claude_dir: pathlib.Path
|
||||
claude_json: pathlib.Path
|
||||
code: pathlib.Path
|
||||
home: pathlib.Path
|
||||
model_catalog: pathlib.Path
|
||||
models_file: pathlib.Path
|
||||
|
||||
|
||||
def paths_from(home, env) -> Paths:
|
||||
def paths_from(home: pathlib.Path) -> Paths:
|
||||
claude = home / ".claude"
|
||||
return Paths(
|
||||
archive=pathlib.Path(env["LOOP_CLAUDE_TRANSCRIPTS"]).expanduser() if env.get("LOOP_CLAUDE_TRANSCRIPTS") else claude / "loop-claude-transcripts",
|
||||
claude_code_transcripts=claude / "projects",
|
||||
claude_dir=claude,
|
||||
claude_json=home / ".claude.json",
|
||||
code=home / "code",
|
||||
home=home,
|
||||
model_catalog=claude / "cache" / "model-catalog",
|
||||
models_file=claude / "loop-claude-models.json",
|
||||
)
|
||||
|
||||
@@ -1,22 +1,25 @@
|
||||
import subprocess
|
||||
import pathlib
|
||||
|
||||
from loop_claude.outcome import Stop
|
||||
from loop_claude.effects import Effects
|
||||
from loop_claude.stop import Stop
|
||||
|
||||
|
||||
def checkout_root(cwd) -> str | Stop:
|
||||
found = subprocess.run(["git", "rev-parse", "--show-toplevel"], capture_output=True, cwd=cwd, text=True)
|
||||
def checkout_root(cwd: pathlib.Path, effects: Effects) -> str | Stop:
|
||||
try:
|
||||
found = effects.git(["rev-parse", "--show-toplevel"], str(cwd))
|
||||
except OSError as failure:
|
||||
return Stop(1, f"could not start git: {failure.strerror}")
|
||||
if found.returncode != 0:
|
||||
return Stop(1, found.stderr.strip())
|
||||
return found.stdout.strip()
|
||||
|
||||
|
||||
def checkouts(root) -> list[str]:
|
||||
def worktrees(root: str, effects: Effects) -> list[str]:
|
||||
found = [root]
|
||||
listing = subprocess.run(["git", "worktree", "list", "--porcelain"], capture_output=True, cwd=root, text=True)
|
||||
try:
|
||||
listing = effects.git(["worktree", "list", "--porcelain"], root)
|
||||
except OSError:
|
||||
return found
|
||||
if listing.returncode == 0:
|
||||
found += [line.split(" ", 1)[1] for line in listing.stdout.splitlines() if line.startswith("worktree ")]
|
||||
return sorted(set(found))
|
||||
|
||||
|
||||
def project_name(root, code) -> str:
|
||||
return root.removeprefix(f"{code}/").lstrip("/")
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import dataclasses
|
||||
import json
|
||||
import pathlib
|
||||
import sys
|
||||
import typing
|
||||
|
||||
from claude_code.model_catalog import catalog_models
|
||||
from loop_claude.effects import Effects
|
||||
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
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Models:
|
||||
judge: str
|
||||
worker: str
|
||||
|
||||
|
||||
def get_or_ask_models(project_key: str, paths: Paths, env: typing.Mapping[str, str], effects: Effects) -> Models | Stop:
|
||||
judge, worker = env.get("LOOP_CLAUDE_JUDGE_MODEL"), env.get("LOOP_CLAUDE_WORKER_MODEL")
|
||||
if judge and worker:
|
||||
return Models(judge, worker)
|
||||
chosen = get_or_ask_model(project_key, paths, effects)
|
||||
if isinstance(chosen, Stop):
|
||||
return chosen
|
||||
return Models(judge or chosen, worker or chosen)
|
||||
|
||||
|
||||
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 kept := models.get(project_key):
|
||||
return kept
|
||||
chosen = ask_for_model(project_key, saved, paths.model_catalog, effects)
|
||||
if isinstance(chosen, Stop):
|
||||
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 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)
|
||||
return chosen
|
||||
|
||||
|
||||
def read_models_file(saved: pathlib.Path) -> dict[str, str] | Stop:
|
||||
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}")
|
||||
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 models
|
||||
|
||||
|
||||
def ask_for_model(project_key: str, saved: pathlib.Path, folder: pathlib.Path, effects: Effects) -> str | Stop:
|
||||
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)
|
||||
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)
|
||||
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)
|
||||
elif picked:
|
||||
return picked
|
||||
|
||||
|
||||
def model_picked(answer: str, offered: list[tuple[str, object]]) -> str | Failure | None:
|
||||
"""The model the answer picks, a Failure naming the numbers to pick from, or None to ask again."""
|
||||
answer = answer.strip()
|
||||
if not answer:
|
||||
return None
|
||||
if not (offered and answer.isdecimal()):
|
||||
return answer
|
||||
if 1 <= int(answer) <= len(offered):
|
||||
return offered[int(answer) - 1][0]
|
||||
return Failure(f"pick 1 to {len(offered)}")
|
||||
@@ -1,81 +0,0 @@
|
||||
import dataclasses
|
||||
import json
|
||||
import sys
|
||||
|
||||
from loop_claude import human_needed
|
||||
from loop_claude.claude_code.catalog import offered_models
|
||||
from loop_claude.file_writes import replace_json
|
||||
from loop_claude.outcome import Stop
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Models:
|
||||
judge: str
|
||||
worker: str
|
||||
|
||||
|
||||
def project_models(project, paths, env) -> Models | Stop:
|
||||
judge, worker = env.get("LOOP_CLAUDE_JUDGE_MODEL"), env.get("LOOP_CLAUDE_WORKER_MODEL")
|
||||
if judge and worker:
|
||||
return Models(judge, worker)
|
||||
chosen = project_model(project, paths)
|
||||
if isinstance(chosen, Stop):
|
||||
return chosen
|
||||
return Models(judge or chosen, worker or chosen)
|
||||
|
||||
|
||||
def project_model(name, paths) -> str | Stop:
|
||||
saved = paths.models_file
|
||||
models = read_models(saved)
|
||||
if isinstance(models, Stop):
|
||||
return models
|
||||
if saved_model := models.get(name):
|
||||
return saved_model
|
||||
chosen = ask_model(name, saved, paths.model_catalog)
|
||||
if isinstance(chosen, Stop):
|
||||
return chosen
|
||||
# Reread: another loop may have saved its project while this one waited on the human.
|
||||
models = read_models(saved)
|
||||
if isinstance(models, Stop):
|
||||
return models
|
||||
if failure := replace_json(saved, {**models, name: chosen}, indent="\t", sort_keys=True):
|
||||
return Stop(1, f"could not save the model in {saved}: {failure.reason}")
|
||||
print(f"{name} runs on {chosen}", file=sys.stderr)
|
||||
return chosen
|
||||
|
||||
|
||||
def read_models(saved) -> dict[str, str] | Stop:
|
||||
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}")
|
||||
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 models
|
||||
|
||||
|
||||
def ask_model(name, saved, folder) -> str | Stop:
|
||||
if stop := human_needed.off_terminal(f"pick {name}'s model, or merge {{\"{name}\": \"<model>\"}} into {saved}"):
|
||||
return stop
|
||||
offered = offered_models(folder)
|
||||
print(f"\nThe model to run {name} 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)
|
||||
while True:
|
||||
try:
|
||||
answer = input(f"{'A number, or any' if offered else 'A'} name claude --model takes: ").strip()
|
||||
except EOFError:
|
||||
print(file=sys.stderr)
|
||||
return human_needed.stop(f"pick {name}'s model", "the input ended")
|
||||
if not answer:
|
||||
continue
|
||||
if not (offered and answer.isdecimal()):
|
||||
return answer
|
||||
if 1 <= int(answer) <= len(offered):
|
||||
return offered[int(answer) - 1][0]
|
||||
print(f"pick 1 to {len(offered)}", file=sys.stderr)
|
||||
@@ -1,16 +1,13 @@
|
||||
import pathlib
|
||||
|
||||
from loop_claude.outcome import Stop
|
||||
from loop_claude.project.text_file import read_utf8
|
||||
from markdown_text import sections
|
||||
from loop_claude.stop import Stop
|
||||
|
||||
|
||||
def read_premises(root) -> str | Stop:
|
||||
try:
|
||||
found = sections(pathlib.Path(root, "README.md").read_text(encoding="utf-8"))
|
||||
except OSError as failure:
|
||||
return Stop(1, f"README.md in {root}: {failure.strerror} - no premises.")
|
||||
except UnicodeDecodeError as failure:
|
||||
line = failure.object.count(b"\n", 0, failure.start) + 1
|
||||
return Stop(1, f"README.md is not UTF-8 on line {line} - no premises.")
|
||||
def read_premises(root: str) -> str | Stop:
|
||||
text = read_utf8(root, "README.md", "no premises")
|
||||
if isinstance(text, Stop):
|
||||
return text
|
||||
found = sections(text)
|
||||
for name in ("Goals", "Audience"):
|
||||
bodies = found.get(name, [])
|
||||
if not bodies:
|
||||
@@ -20,21 +17,3 @@ def read_premises(root) -> str | Stop:
|
||||
if not bodies[0]:
|
||||
return Stop(1, f"README.md has nothing under ## {name} - no premises.")
|
||||
return f"## Goals\n{found['Goals'][0]}\n\n## Audience\n{found['Audience'][0]}"
|
||||
|
||||
|
||||
def sections(text) -> dict[str, list[str]]:
|
||||
blocks: list[tuple[str | None, list[str]]] = []
|
||||
fenced = False
|
||||
for line in text.splitlines():
|
||||
fenced ^= line.startswith("```")
|
||||
if not fenced and line.startswith("## "):
|
||||
blocks.append((line.strip()[3:], []))
|
||||
elif not fenced and line.startswith("# "):
|
||||
blocks.append((None, []))
|
||||
elif blocks and line.strip():
|
||||
blocks[-1][1].append(line)
|
||||
found: dict[str, list[str]] = {}
|
||||
for name, body in blocks:
|
||||
if name is not None:
|
||||
found.setdefault(name, []).append("\n".join(body))
|
||||
return found
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import pathlib
|
||||
|
||||
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")
|
||||
# The human's rules for every project, under ~/.claude: CLAUDE.md, then each .md file in these folders, which a repo check keeps present.
|
||||
HUMAN_RULES_FILE = "CLAUDE.md"
|
||||
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:
|
||||
"""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]
|
||||
sources += [(str(rule.parent), rule.name, f"~/.claude/{rule.relative_to(claude_dir)}") for rule in rules]
|
||||
records = []
|
||||
for folder, name, heading in sources:
|
||||
if not pathlib.Path(folder, name).exists():
|
||||
continue
|
||||
text = read_utf8(folder, name, "the judge cannot read the records")
|
||||
if isinstance(text, Stop):
|
||||
return text
|
||||
records.append(f"From {heading}:\n{text.strip()}")
|
||||
return "\n\n".join(records)
|
||||
@@ -0,0 +1,13 @@
|
||||
import pathlib
|
||||
|
||||
from loop_claude.stop import Stop
|
||||
|
||||
|
||||
def read_utf8(folder: str, name: str, consequence: str) -> str | Stop:
|
||||
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}.")
|
||||
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}.")
|
||||
@@ -0,0 +1,19 @@
|
||||
import dataclasses
|
||||
import typing
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Stop:
|
||||
"""loop-claude exits with code, printing reason."""
|
||||
code: typing.Literal[0, 1, 2, 130]
|
||||
reason: str
|
||||
|
||||
|
||||
def needs_human(need: str, blocker: str) -> Stop:
|
||||
return Stop(2, f"the human is needed to {need}, but {blocker}")
|
||||
|
||||
|
||||
def needs_terminal(need: str, on_terminal: bool) -> Stop | None:
|
||||
if on_terminal:
|
||||
return None
|
||||
return needs_human(need, "stdin or stdout is not a terminal; rerun loop-claude on a terminal")
|
||||
@@ -1,9 +1,11 @@
|
||||
import dataclasses
|
||||
import datetime
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import pty
|
||||
import re
|
||||
import select
|
||||
import shutil
|
||||
import stat
|
||||
@@ -13,9 +15,14 @@ import tempfile
|
||||
import time
|
||||
import unittest
|
||||
|
||||
BIN = pathlib.Path(__file__).resolve().parent
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from test_env import isolated_env
|
||||
|
||||
BIN = pathlib.Path(__file__).resolve().parents[1]
|
||||
TASK = "Do the next chunk."
|
||||
|
||||
|
||||
# Plays claude from FAKE_CLAUDE_SCENARIO, one step per call, logging each call; a step for another role,
|
||||
# or none left, is Ctrl-C to loop-claude, which otherwise loops forever.
|
||||
FAKE_CLAUDE = """#!{python}
|
||||
@@ -56,6 +63,8 @@ def append(*entries):
|
||||
|
||||
|
||||
if role == "worker":
|
||||
if "--session-id" in argv and step.get("transcript", True):
|
||||
append({{"type": "custom-title"}}, {{"type": "queue-operation", "timestamp": str(time.time_ns())}})
|
||||
said = {{"type": "assistant", "message": {{"content": [{{"type": "text", "text": step.get("say", "working")}}]}}}}
|
||||
if step.get("transcript", True):
|
||||
append({{"type": "user", "promptSource": "sdk", "message": {{"content": argv[argv.index("-p") + 1]}}}})
|
||||
@@ -113,7 +122,7 @@ def worker(**step):
|
||||
|
||||
|
||||
def judge(interrupt=False, finished=False, evidence="working", question="", **step):
|
||||
verdict = {"evidence": evidence, "finished": finished, "interrupt": interrupt, "question": question}
|
||||
verdict = {"answer": "", "evidence": evidence, "finished": finished, "interrupt": interrupt, "question": question}
|
||||
return {"role": "judge", "verdict": verdict, **step}
|
||||
|
||||
|
||||
@@ -151,7 +160,7 @@ class Checkout:
|
||||
self.root.mkdir(parents=True)
|
||||
(self.root / "README.md").write_text(PREMISES)
|
||||
self.script = BIN / "loop-claude"
|
||||
self.env = {name: value for name, value in os.environ.items() if not name.startswith(("GIT_", "LOOP_CLAUDE_", "PYTHON"))}
|
||||
self.env = isolated_env()
|
||||
fake = self.temp / "fake-bin"
|
||||
fake.mkdir()
|
||||
(fake / "claude").write_text(FAKE_CLAUDE.format(python=sys.executable))
|
||||
@@ -247,17 +256,17 @@ class Checkout:
|
||||
return pathlib.Path(self.env.get("LOOP_CLAUDE_TRANSCRIPTS", self.home / ".claude" / "loop-claude-transcripts"))
|
||||
|
||||
def archived(self):
|
||||
"""Each archived transcript's verdict, after checking the copy is named by its content hash."""
|
||||
verdicts = {}
|
||||
for folder in (self.archive(), self.archive() / "proj"):
|
||||
"""Each archived transcript's outcomes, with every UTC stamp replaced by <UTC>, after checking the copy is named by its content hash."""
|
||||
outcomes = {}
|
||||
for folder in (self.archive(), self.archive() / "proj", *(self.archive() / "proj").iterdir()):
|
||||
self.test.assertEqual(stat.S_IMODE(folder.stat().st_mode), 0o700, folder)
|
||||
for copy in sorted((self.archive() / "proj").glob("*.jsonl")):
|
||||
for copy in sorted((self.archive() / "proj").glob("*/*.jsonl")):
|
||||
self.test.assertEqual(copy.stem, hashlib.sha256(copy.read_bytes()).hexdigest())
|
||||
verdict = copy.with_suffix(".verdict.md")
|
||||
for archived in (copy, verdict):
|
||||
kept = copy.with_suffix(".outcomes.md")
|
||||
for archived in (copy, kept):
|
||||
self.test.assertEqual(stat.S_IMODE(archived.stat().st_mode), 0o600)
|
||||
verdicts[copy.read_text()] = verdict.read_text()
|
||||
return verdicts
|
||||
outcomes[copy.read_text()] = re.sub(r"^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ ", "<UTC> ", kept.read_text(), flags=re.MULTILINE)
|
||||
return outcomes
|
||||
|
||||
|
||||
def argument(call, flag):
|
||||
@@ -279,7 +288,7 @@ class Premises(unittest.TestCase):
|
||||
self.assertIn("not a git repository", run.stderr)
|
||||
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 is not UTF-8 on line 3 - 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.",
|
||||
b"# P\n## Audience\nme\n": "README.md has no ## Goals heading - no premises.",
|
||||
b"# P\n## Goals\n1. g\n": "README.md has no ## Audience heading - no premises.",
|
||||
b"# P\n## Goals\n\n## Audience\nme\n": "README.md has nothing under ## Goals - no premises.",
|
||||
@@ -300,6 +309,10 @@ class Premises(unittest.TestCase):
|
||||
run = checkout.run([worker()])
|
||||
self.assertEqual((run.code, run.calls), (1, []))
|
||||
self.assertEqual(run.stderr.strip(), f"README.md in {checkout.root}: Is a directory - no premises.")
|
||||
(checkout.temp / "fake-bin" / "git").unlink()
|
||||
run = checkout.run([worker()])
|
||||
self.assertEqual((run.code, run.calls), (1, []))
|
||||
self.assertEqual(run.stderr.strip(), "could not start git: No such file or directory")
|
||||
|
||||
def test_names_the_session_by_the_checkout_relative_to_code_or_else_to_the_root(self):
|
||||
checkout = Checkout(self)
|
||||
@@ -316,6 +329,10 @@ class Cycles(unittest.TestCase):
|
||||
def test_resumes_the_session_while_unfinished_and_starts_it_fresh_after_finishing(self):
|
||||
checkout = Checkout(self)
|
||||
(checkout.root / "sub").mkdir()
|
||||
(checkout.root / "docs").mkdir()
|
||||
(checkout.root / "docs" / "decisions.md").write_text("# Decisions\n")
|
||||
(checkout.home / ".claude").mkdir()
|
||||
(checkout.home / ".claude" / "CLAUDE.md").write_text("# Global instructions\n")
|
||||
run = checkout.run([
|
||||
worker(say="started"), judge(evidence="started"),
|
||||
worker(say="landed-it", siblings=True), judge(finished=True, evidence="landed-it"),
|
||||
@@ -332,17 +349,22 @@ class Cycles(unittest.TestCase):
|
||||
self.assertEqual(argument(workers[2], "--session-id"), session)
|
||||
self.assertTrue(argument(workers[0], "-p").startswith(f"{TASK}\n\nContinue any open draft PR"))
|
||||
self.assertNotIn(TASK, argument(workers[1], "-p"))
|
||||
self.assertIn("Even then, it is finished only once every answer the human typed in it", argument(workers[1], "-p"))
|
||||
self.assertIn("as the work remaining:\n\n> started\n\n", argument(workers[1], "-p"))
|
||||
self.assertEqual({call["cwd"] for call in run.calls}, {str(checkout.root)})
|
||||
self.assertIn("1. Work.", run.calls[1]["stdin"])
|
||||
self.assertIn("From docs/decisions.md:\n# Decisions\n\nFrom ~/.claude/CLAUDE.md:\n# Global instructions", run.calls[1]["stdin"])
|
||||
self.assertEqual({argument(call, "--model") for call in workers}, {"worker-model"})
|
||||
self.assertEqual({argument(call, "--model") for call in run.calls if call["role"] == "judge"}, {"judge-model"})
|
||||
self.assertIn("landed-it", run.calls[3]["stdin"])
|
||||
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 ===", run.stdout)
|
||||
[(copy, verdict)] = checkout.archived().items()
|
||||
self.assertIn('"text": "landed-it"', copy)
|
||||
self.assertEqual(verdict, f"Task: {TASK}\n\nVerdict: finished\n")
|
||||
copies = {verdict.removeprefix(f"Task: {TASK}\n\n"): copy for copy, verdict in checkout.archived().items()}
|
||||
self.assertEqual(sorted(copies), ["<UTC> Stopped: Ctrl-C\n", "<UTC> Verdict: finished\n\nEvidence:\n> landed-it\n", "<UTC> Verdict: unfinished\n\nEvidence:\n> started\n"])
|
||||
self.assertIn('"text": "landed-it"', copies["<UTC> Verdict: finished\n\nEvidence:\n> landed-it\n"])
|
||||
self.assertIn('"text": "next chunk"', copies["<UTC> Stopped: Ctrl-C\n"])
|
||||
self.assertEqual(len(list(checkout.archive().glob(f"proj/*/session/{session}.orphaned-1-ab.jsonl"))), 1)
|
||||
|
||||
def test_exits_1_when_the_transcript_cannot_be_archived_and_resumes_on_the_next_run(self):
|
||||
checkout = Checkout(self)
|
||||
@@ -351,6 +373,7 @@ class Cycles(unittest.TestCase):
|
||||
run = checkout.run([worker(say="landed-it"), judge(finished=True, evidence="landed-it")])
|
||||
self.assertEqual((run.code, run.roles()), (1, ["worker", "judge"]))
|
||||
self.assertRegex(run.stderr.strip().splitlines()[-1], r"^could not archive the transcript: .*/loop-claude-transcripts/proj: Not a directory$")
|
||||
self.assertEqual(run.stderr.count("could not archive the transcript"), 1)
|
||||
session = argument(run.calls[0], "--session-id")
|
||||
checkout.archive().unlink()
|
||||
run = checkout.run([worker(), judge(finished=True)])
|
||||
@@ -373,13 +396,26 @@ class Cycles(unittest.TestCase):
|
||||
self.assertEqual(run.code, 130)
|
||||
self.assertEqual(run.sleeps, [60, 60, 60, 60])
|
||||
|
||||
run = checkout.run([worker(), judge(exit=1, stderr="judge down"), judge(stdout="{}"), judge(verdict={"interrupt": False})])
|
||||
run = checkout.run([worker(), judge(exit=1, stderr="judge down"), judge(stdout=""), judge(verdict={"interrupt": False})])
|
||||
self.assertEqual(run.code, 1)
|
||||
self.assertEqual(run.roles(), ["worker", "judge", "judge", "judge"])
|
||||
self.assertEqual(run.sleeps, [60, 60])
|
||||
self.assertIn("retrying the judge in a minute: judge down", run.stderr)
|
||||
self.assertIn("retrying the judge in a minute: the judge returned no verdict", run.stderr)
|
||||
self.assertEqual(run.stderr.strip().splitlines()[-1], "the judge failed three times running: the judge's verdict has no evidence of type string")
|
||||
self.assertIn("retrying the judge in a minute: the judge returned no reply; it replied: nothing\n", run.stderr)
|
||||
self.assertEqual(run.stderr.strip().splitlines()[-1], 'the judge failed three times running: the judge\'s reply has no answer of type string; it replied: {"structured_output": {"interrupt": false}}')
|
||||
|
||||
def test_waits_out_a_usage_limit_which_ends_a_run_of_failures(self):
|
||||
checkout = Checkout(self)
|
||||
checkout.env["TZ"] = "UTC"
|
||||
resets_at = int(time.time()) + 3600
|
||||
rejected = json.dumps({"type": "rate_limit_event", "rate_limit_info": {"status": "rejected", "resetsAt": resets_at}})
|
||||
limited = json.dumps({"type": "result", "api_error_status": 429, "is_error": True, "result": "You've hit your session limit"})
|
||||
run = checkout.run([worker(exit=1), worker(exit=1), worker(stream=f"{rejected}\n{limited}\n", result=False, exit=1), worker(exit=1), worker(), judge(stdout=limited, exit=1), judge()])
|
||||
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("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):
|
||||
checkout = Checkout(self)
|
||||
@@ -393,8 +429,8 @@ class Cycles(unittest.TestCase):
|
||||
self.assertEqual(run.code, 130)
|
||||
self.assertEqual(run.roles(), ["worker", "judge", "judge", "judge", "worker", "judge"])
|
||||
self.assertEqual(run.sleeps, [60, 60])
|
||||
self.assertIn("the judge quoted 'never said', nothing in the transcript, for the question: A or B?", run.stderr)
|
||||
self.assertIn("retrying the judge in a minute: the judge quoted '', nothing in the transcript\n", run.stderr)
|
||||
self.assertIn("the judge quoted 'never said', which is not in the transcript, for the question: A or B?", run.stderr)
|
||||
self.assertIn("retrying the judge in a minute: the judge quoted '', which is not in the transcript\n", run.stderr)
|
||||
|
||||
def test_retries_a_judge_claude_cannot_start(self):
|
||||
checkout = Checkout(self)
|
||||
@@ -405,10 +441,11 @@ class Cycles(unittest.TestCase):
|
||||
|
||||
def test_hands_the_judge_the_tail_of_a_long_transcript(self):
|
||||
checkout = Checkout(self)
|
||||
run = checkout.run([worker(say="early " * 20000 + "LATE")])
|
||||
run = checkout.run([worker(say="early " * 80000 + "LATE")])
|
||||
self.assertIn("LATE", run.calls[1]["stdin"])
|
||||
self.assertLess(run.calls[1]["stdin"].count("early"), 20000)
|
||||
self.assertTrue(run.calls[1]["stdin"].rstrip().endswith("an open PR, a review not yet run, CI not yet reported."))
|
||||
self.assertEqual(len(run.calls[1]["stdin"]), 400000)
|
||||
self.assertLess(run.calls[1]["stdin"].count("early"), 80000)
|
||||
self.assertTrue(run.calls[1]["stdin"].rstrip().endswith("CI not yet reported, an answer not yet recorded."))
|
||||
|
||||
def test_skips_a_malformed_transcript_or_stream_line(self):
|
||||
checkout = Checkout(self)
|
||||
@@ -423,6 +460,7 @@ class Cycles(unittest.TestCase):
|
||||
checkout = Checkout(self)
|
||||
run = checkout.run([worker(unreadable=True)])
|
||||
self.assertEqual((run.code, run.roles()), (1, ["worker"]))
|
||||
self.assertRegex(run.stderr.strip().splitlines()[-2], r"^could not archive the transcript: .*\.jsonl: Permission denied$")
|
||||
self.assertRegex(run.stderr.strip().splitlines()[-1], r"^could not read the transcript .*\.jsonl: Permission denied$")
|
||||
|
||||
def test_retries_a_worker_claude_cannot_start(self):
|
||||
@@ -450,7 +488,7 @@ class Interrupt(unittest.TestCase):
|
||||
self.assertEqual(run.stderr.strip().splitlines()[-2:], ["A or B?", "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal"])
|
||||
[(copy, verdict)] = checkout.archived().items()
|
||||
self.assertEqual(copy, (checkout.transcripts()[0]).read_text())
|
||||
self.assertEqual(verdict, f"Task: {TASK}\n\nVerdict: interrupt\n\nA or B?\n")
|
||||
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\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")
|
||||
self.assertEqual(stat.S_IMODE((checkout.temp / "deep").stat().st_mode), 0o700)
|
||||
self.assertIn(f"transcript: {checkout.archive() / 'proj'}/", run.stderr)
|
||||
session = argument(run.calls[0], "--session-id")
|
||||
@@ -642,18 +680,19 @@ 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(),
|
||||
])
|
||||
self.assertEqual(run.code, 130)
|
||||
self.assertEqual(run.roles(), ["worker", "judge"] * 4)
|
||||
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} for cycle in (2, 3)])
|
||||
self.assertIn("=== cycle 4 ===", run.stdout)
|
||||
self.assertEqual(reloads, [{"cycle_number": cycle, "root": str(checkout.root), "task": TASK, "unfinished_evidence": "working"} for cycle in (2, 3, 4)])
|
||||
self.assertIn("=== cycle 5 ===", run.stdout)
|
||||
|
||||
outside = checkout.temp / "outside"
|
||||
outside.mkdir()
|
||||
state = {"cycle_number": 3, "root": str(checkout.root), "task": TASK}
|
||||
state = {"cycle_number": 3, "root": str(checkout.root), "task": TASK, "unfinished_evidence": ""}
|
||||
run = checkout.run([worker()], argv=["--reloaded", json.dumps(state)], cwd=outside)
|
||||
self.assertEqual((run.code, run.roles()), (130, ["worker", "judge"]))
|
||||
self.assertEqual(run.calls[0]["cwd"], str(checkout.root))
|
||||
@@ -0,0 +1,592 @@
|
||||
import ast
|
||||
import contextlib
|
||||
import dataclasses
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
import uuid
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from loop_claude.project import checkout, model_choice, records
|
||||
from loop_claude.effects import Effects
|
||||
from claude_code import entries, session
|
||||
from failure import Failure
|
||||
from loop_claude.cycle.judge import Finished, Interrupt, QuotedAnswer, Unfinished, verdict_from
|
||||
from loop_claude.cycle import interrupt, judge, prompts, retry, run, states, worker
|
||||
from loop_claude.cycle.retry import Limited
|
||||
from loop_claude.loop import main, reload
|
||||
from loop_claude import paths
|
||||
from transcript_archive.location import project_archive
|
||||
from loop_claude.stop import Stop
|
||||
|
||||
CWD = pathlib.Path("/c")
|
||||
NOW = 1790000000
|
||||
|
||||
|
||||
def assistant(*parts):
|
||||
return {"type": "assistant", "message": {"content": list(parts)}}
|
||||
|
||||
|
||||
def human(content):
|
||||
return {"type": "user", "message": {"content": content}}
|
||||
|
||||
|
||||
class FakeEffects:
|
||||
"""Effects that record each call and answer from a script, one answer per call."""
|
||||
|
||||
def __init__(self, claude=(), on_terminal_claude=(), git=(), inputs=(), python=(), streams=(), on_terminal=True):
|
||||
self.calls = []
|
||||
self.scripts = {"claude": list(claude), "claude_on_terminal": list(on_terminal_claude), "git": list(git), "input": list(inputs), "python": list(python), "stream_claude": list(streams)}
|
||||
self.terminal = on_terminal
|
||||
|
||||
def effects(self):
|
||||
return Effects(
|
||||
claude=lambda args, cwd, stdin: self.answer("claude", (args, stdin)),
|
||||
claude_on_terminal=lambda args, cwd: self.answer("claude_on_terminal", args),
|
||||
execv=self.execv,
|
||||
git=lambda args, cwd: self.answer("git", args),
|
||||
input=lambda prompt: self.answer("input", prompt),
|
||||
local_time=lambda seconds: f"<{seconds}>",
|
||||
now=lambda: NOW,
|
||||
on_terminal=lambda: self.terminal,
|
||||
python=lambda args: self.answer("python", args),
|
||||
sleep=lambda seconds: self.calls.append(("sleep", seconds)),
|
||||
stream_claude=lambda args, cwd: self.answer("stream_claude", args),
|
||||
)
|
||||
|
||||
def answer(self, seam, what):
|
||||
self.calls.append((seam, what))
|
||||
answer = self.scripts[seam].pop(0)
|
||||
if isinstance(answer, BaseException):
|
||||
raise answer
|
||||
return answer(what) if callable(answer) else answer
|
||||
|
||||
def execv(self, path, args):
|
||||
self.calls.append(("execv", args))
|
||||
raise OSError(2, "No such file or directory")
|
||||
|
||||
def made(self, seam):
|
||||
return [what for called, what in self.calls if called == seam]
|
||||
|
||||
|
||||
def uuid7():
|
||||
# Python 3.11, the floor, has no uuid.uuid7.
|
||||
random = int.from_bytes(os.urandom(10))
|
||||
return uuid.UUID(int=int(time.time() * 1000) << 80 | 7 << 76 | (random >> 62 & 0xFFF) << 64 | 2 << 62 | random & (1 << 62) - 1)
|
||||
|
||||
|
||||
def ran(stdout="", code=0, stderr=""):
|
||||
return subprocess.CompletedProcess([], code, stdout, stderr)
|
||||
|
||||
|
||||
def judged(verdict, evidence="working", answer=""):
|
||||
reply = {"answer": answer, "evidence": evidence, "finished": verdict == "finished", "interrupt": verdict == "interrupt", "question": "Which one?" if verdict in ("interrupt", "quoted") else ""}
|
||||
return ran(json.dumps({"structured_output": reply}))
|
||||
|
||||
|
||||
class Worker:
|
||||
"""A worker claude: writes a line to the session's transcript, then streams a result."""
|
||||
|
||||
def __init__(self, home):
|
||||
self.home = home
|
||||
|
||||
def __call__(self, args):
|
||||
flag = "--session-id" if "--session-id" in args else "--resume"
|
||||
path = self.home / "projects" / "-fake" / f"{args[args.index(flag) + 1]}.jsonl"
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(path, "a") as handle:
|
||||
if flag == "--session-id":
|
||||
handle.write(json.dumps({"type": "custom-title"}) + "\n" + json.dumps({"type": "queue-operation", "timestamp": str(uuid7())}) + "\n")
|
||||
handle.write(json.dumps(assistant({"type": "text", "text": "working"})) + "\n")
|
||||
return Streamed(0)
|
||||
|
||||
|
||||
class Streamed:
|
||||
def __init__(self, code, *events):
|
||||
self.code = code
|
||||
self.events = events or ({"type": "result"},)
|
||||
|
||||
def lines(self):
|
||||
return [json.dumps(event) + "\n" for event in self.events]
|
||||
|
||||
def wait(self):
|
||||
return self.code
|
||||
|
||||
|
||||
class Transitions(unittest.TestCase):
|
||||
def test_each_state_moves_on_its_events_and_only_on_them(self):
|
||||
answered = states.Ruled(QuotedAnswer("e", "Which one?", "A."))
|
||||
legal = (
|
||||
(states.Working(), states.WorkerRan("/t"), states.Judging("/t")),
|
||||
(states.Working(QuotedAnswer("e", "Which one?", "A."), 3), states.WorkerRan("/t"), states.Judging("/t", 3)),
|
||||
(states.Judging("/t"), states.Ruled(Interrupt("e", "Which one?")), states.Interrupting("/t", Interrupt("e", "Which one?"))),
|
||||
(states.Judging("/t", 3), states.Ruled(Interrupt("e", "Which one?")), states.Interrupting("/t", Interrupt("e", "Which one?"), 3)),
|
||||
(states.Judging("/t"), answered, states.Working(QuotedAnswer("e", "Which one?", "A."), 1)),
|
||||
(states.Judging("/t", 2), answered, states.Working(QuotedAnswer("e", "Which one?", "A."), 3)),
|
||||
(states.Judging("/t", 3), answered, states.Interrupting("/t", QuotedAnswer("e", "Which one?", "A."), 3)),
|
||||
(states.Judging("/t"), states.Ruled(Finished("e")), states.Closing("/t", Finished("e"))),
|
||||
(states.Judging("/t", 3), states.Ruled(Finished("e")), states.Closing("/t", Finished("e"))),
|
||||
(states.Judging("/t"), states.Ruled(Unfinished("e")), states.Closing("/t", Unfinished("e"))),
|
||||
(states.Judging("/t", 3), states.Ruled(Unfinished("e")), states.Closing("/t", Unfinished("e"))),
|
||||
(states.Interrupting("/t", Interrupt("e", "q")), states.HumanAnswered(), states.Judging("/t")),
|
||||
(states.Interrupting("/t", Interrupt("e", "q"), 3), states.HumanAnswered(), states.Judging("/t", 3)),
|
||||
(states.Closing("/t", Finished("e")), states.Archived(), states.Ended(Finished("e"))),
|
||||
(states.Closing("/t", Unfinished("e")), states.Archived(), states.Ended(Unfinished("e"))),
|
||||
)
|
||||
for state, event, after in legal:
|
||||
with self.subTest(state=state, event=event):
|
||||
self.assertEqual(states.transition(state, event), after)
|
||||
every_state = (states.Working(), states.Working(QuotedAnswer("e", "Which one?", "A."), 3), states.Judging("/t"), states.Judging("/t", 3), states.Interrupting("/t", Interrupt("e", "q")), states.Interrupting("/t", Interrupt("e", "q"), 3), states.Closing("/t", Finished("e")), states.Ended(Finished("e")))
|
||||
every_event = (states.WorkerRan("/t"), states.Ruled(Interrupt("e", "Which one?")), answered, states.Ruled(Finished("e")), states.Ruled(Unfinished("e")), states.HumanAnswered(), states.Archived())
|
||||
for state in every_state:
|
||||
for event in every_event:
|
||||
if (state, event) not in [(state, event) for state, event, _ in legal]:
|
||||
with self.subTest(state=state, event=event), self.assertRaises(ValueError):
|
||||
states.transition(state, event)
|
||||
|
||||
|
||||
class QuestionFor(unittest.TestCase):
|
||||
def test_puts_an_interrupts_question_as_asked_and_a_quoted_answer_past_the_cap_with_its_quote(self):
|
||||
self.assertEqual(run.question_for(Interrupt("e", "Which one?")), "Which one?")
|
||||
self.assertEqual(run.question_for(QuotedAnswer("e", "Which one?", "A.")), "Which one?\n\nREADME.md's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or ~/.claude/skills/larv-review/standards/ says:\nA.\n\nThose files have answered 3 questions this cycle, the most allowed, so this one comes to you.")
|
||||
|
||||
|
||||
class Cycles(unittest.TestCase):
|
||||
def setUp(self):
|
||||
temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(temp.cleanup)
|
||||
self.home = pathlib.Path(temp.name)
|
||||
self.paths = paths.paths_from(self.home)
|
||||
self.session = session.session_named("A proj loop-claude", self.paths.claude_code_transcripts)
|
||||
self.archive = project_archive(str(self.home / "code" / "proj"), self.home, {})
|
||||
|
||||
def cycle(self, fake, records="", unfinished_evidence=""):
|
||||
return run.Cycle(effects=fake.effects(), models=model_choice.Models("judge-model", "worker-model"), paths=self.paths, premises="## Goals", project_archive=self.archive, records=records, root=str(self.home), session=self.session, task="Do it.", unfinished_evidence=unfinished_evidence)
|
||||
|
||||
def archived_outcomes(self):
|
||||
return sorted(path.read_text() for path in self.archive.glob("*/*.outcomes.md"))
|
||||
|
||||
def test_a_finished_chunk_is_archived_and_its_session_deleted(self):
|
||||
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("finished")])
|
||||
self.assertEqual(run.run_cycle(self.cycle(fake)), Finished("working"))
|
||||
self.assertEqual(self.archived_outcomes(), ["Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: finished\n\nEvidence:\n> working\n"])
|
||||
self.assertIsNone(session.transcript_file(self.session))
|
||||
|
||||
def test_an_unfinished_chunks_transcript_is_archived_and_the_next_cycle_resumes_its_session_with_the_judges_evidence(self):
|
||||
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 2, claude=[judged("unfinished")] * 2)
|
||||
self.assertEqual(run.run_cycle(self.cycle(fake)), Unfinished("working"))
|
||||
self.assertTrue(session.transcript_file(self.session))
|
||||
self.assertEqual(run.run_cycle(self.cycle(fake, unfinished_evidence="working")), Unfinished("working"))
|
||||
workers = fake.made("stream_claude")
|
||||
self.assertIn("--session-id", workers[0])
|
||||
self.assertIn("--resume", workers[1])
|
||||
self.assertIn("as the work remaining:\n\n> working\n\nThe chunk is finished once", workers[1][workers[1].index("-p") + 1])
|
||||
self.assertEqual(self.archived_outcomes(), ["Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: unfinished\n\nEvidence:\n> working\n"] * 2)
|
||||
|
||||
def test_a_cycle_stopped_by_a_failure_or_ctrl_c_archives_what_its_session_holds(self):
|
||||
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[ran(code=1)] * 3)
|
||||
self.assertEqual(run.run_cycle(self.cycle(fake)).code, 1)
|
||||
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[KeyboardInterrupt()])
|
||||
self.assertEqual(run.run_cycle(self.cycle(fake)), Stop(130, ""))
|
||||
self.assertEqual(self.archived_outcomes(), ["Task: Do it.\n\n2026-09-21T14:13:20Z Stopped: Ctrl-C\n", "Task: Do it.\n\n2026-09-21T14:13:20Z Stopped: the judge failed three times running: the judge exited 1\n"])
|
||||
|
||||
def test_archives_each_chunks_session_folder_replacing_a_copy_only_with_what_grew_from_it(self):
|
||||
folder = self.paths.claude_code_transcripts / "-fake" / str(self.session.id)
|
||||
(folder / "subagents" / "workflows").mkdir(parents=True)
|
||||
(folder / "subagents" / "agent-a.jsonl").write_text("a\n")
|
||||
(folder / "subagents" / "workflows" / "journal.jsonl").write_text("j\n")
|
||||
(folder / "custom-title.json").write_text("first")
|
||||
(folder.parent / f"{self.session.id}.orphaned-1.jsonl").write_text("o\n")
|
||||
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 3, claude=[judged("unfinished"), judged("finished"), judged("unfinished")])
|
||||
self.assertEqual(run.run_cycle(self.cycle(fake)), Unfinished("working"))
|
||||
[chunk] = self.archive.iterdir()
|
||||
kept = chunk / "session" / str(self.session.id)
|
||||
self.assertEqual((chunk / "session" / f"{self.session.id}.orphaned-1.jsonl").read_text(), "o\n")
|
||||
os.utime(kept / "subagents" / "workflows" / "journal.jsonl", (0, 0))
|
||||
with open(folder / "subagents" / "agent-a.jsonl", "a") as handle:
|
||||
handle.write("more\n")
|
||||
(folder / "custom-title.json").write_text("second")
|
||||
self.assertEqual(run.run_cycle(self.cycle(fake)), Finished("working"))
|
||||
self.assertFalse(folder.exists())
|
||||
self.assertEqual((kept / "subagents" / "agent-a.jsonl").read_text(), "a\nmore\n")
|
||||
self.assertEqual((kept / "subagents" / "workflows" / "journal.jsonl").stat().st_mtime, 0)
|
||||
self.assertEqual(sorted(path.read_text() for path in kept.glob("custom-title.json*")), ["first", "second"])
|
||||
self.assertEqual(stat.S_IMODE((kept / "subagents" / "agent-a.jsonl").stat().st_mode), 0o600)
|
||||
folder.mkdir()
|
||||
(folder / "custom-title.json").write_text("third")
|
||||
self.assertEqual(run.run_cycle(self.cycle(fake)), Unfinished("working"))
|
||||
[next_chunk] = set(self.archive.iterdir()) - {chunk}
|
||||
self.assertEqual(sorted(path.read_text() for path in (next_chunk / "session" / str(self.session.id)).glob("custom-title.json*")), ["third"])
|
||||
|
||||
@unittest.skipIf(os.geteuid() == 0, "root reads an unreadable folder")
|
||||
def test_stops_on_a_session_folder_it_cannot_read_whole(self):
|
||||
locked = self.paths.claude_code_transcripts / "-fake" / str(self.session.id) / "subagents"
|
||||
locked.mkdir(parents=True)
|
||||
locked.chmod(0)
|
||||
self.addCleanup(locked.chmod, 0o700)
|
||||
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("unfinished")])
|
||||
self.assertEqual(run.run_cycle(self.cycle(fake)), Stop(1, f"could not archive the transcript: {locked}: Permission denied"))
|
||||
|
||||
def test_an_interrupt_is_archived_answered_and_judged_again(self):
|
||||
def answer(args):
|
||||
with open(session.transcript_file(self.session), "a") as handle:
|
||||
handle.write(json.dumps(human("the second")) + "\n")
|
||||
return 0
|
||||
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("interrupt"), judged("unfinished")], on_terminal_claude=[answer], git=[ran()])
|
||||
self.assertEqual(run.run_cycle(self.cycle(fake)), Unfinished("working"))
|
||||
self.assertEqual(self.archived_outcomes(), ["Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: interrupt\n\nWhich one?\n\nEvidence:\n> working\n", "Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: unfinished\n\nEvidence:\n> working\n"])
|
||||
self.assertIn(str(self.session.id), fake.made("claude_on_terminal")[0])
|
||||
judge_prompts = [stdin for args, stdin in fake.made("claude")]
|
||||
self.assertEqual(len(judge_prompts), 2)
|
||||
self.assertNotIn("the second", judge_prompts[0])
|
||||
self.assertIn("[human] the second", judge_prompts[1])
|
||||
|
||||
def test_a_question_the_records_answer_resumes_the_worker_with_the_answer_three_times_a_cycle(self):
|
||||
answered = judged("quoted", answer="Use *A*.")
|
||||
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 4, claude=[answered] * 4, on_terminal_claude=[0], git=[ran()])
|
||||
with contextlib.redirect_stderr(io.StringIO()) as said, contextlib.redirect_stdout(io.StringIO()) as printed:
|
||||
self.assertEqual(run.run_cycle(self.cycle(fake, records="From AGENTS.md:\nUse A.")), Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed"))
|
||||
resumed = fake.made("stream_claude")[1]
|
||||
self.assertEqual(resumed[resumed.index("-p") + 1], "Your question: Which one?\n\nREADME.md's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or ~/.claude/skills/larv-review/standards/ answers it:\n\nUse *A*.\n\nContinue the task.")
|
||||
self.assertEqual(len(fake.made("stream_claude")), 4)
|
||||
self.assertEqual(printed.getvalue().count("=== README.md's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or ~/.claude/skills/larv-review/standards/ answered: Which one? ===\nUse *A*."), 3)
|
||||
self.assertIn("Which one?\n\nREADME.md's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or ~/.claude/skills/larv-review/standards/ says:\nUse *A*.\n\nThose files have answered 3 questions this cycle", said.getvalue())
|
||||
quoted = "2026-09-21T14:13:20Z Verdict: quoted answer\n\nWhich one?\n\nREADME.md's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or ~/.claude/skills/larv-review/standards/ says:\n> Use *A*.\n\nEvidence:\n> working\n"
|
||||
self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: interrupt\n\nWhich one?\n\nREADME.md's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or ~/.claude/skills/larv-review/standards/ says:\nUse *A*.\n\nThose files have answered 3 questions this cycle, the most allowed, so this one comes to you.\n\nEvidence:\n> working\n\n2026-09-21T14:13:20Z Stopped: the human is needed to answer the question above, but the interrupt ended with nothing typed\n", *[f"Task: Do it.\n\n{quoted}"] * 3])
|
||||
|
||||
def test_stops_when_a_quoted_answer_cannot_be_archived(self):
|
||||
self.archive.parent.mkdir(parents=True)
|
||||
self.archive.write_text("")
|
||||
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("quoted", answer="Use A.")])
|
||||
with contextlib.redirect_stdout(io.StringIO()):
|
||||
stop = run.run_cycle(self.cycle(fake, records="From AGENTS.md:\nUse A."))
|
||||
self.assertRegex(stop.reason, f"^could not archive the transcript: {self.archive}/[0-9a-f]{{64}}: Not a directory$")
|
||||
self.assertEqual(len(fake.made("stream_claude")), 1)
|
||||
|
||||
def test_an_answer_the_records_do_not_hold_is_dropped_and_the_question_goes_to_the_human(self):
|
||||
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("quoted", answer="Use ... A.")], on_terminal_claude=[0], git=[ran()])
|
||||
with contextlib.redirect_stderr(io.StringIO()) as said:
|
||||
self.assertEqual(run.run_cycle(self.cycle(fake, records="From AGENTS.md:\nUse B. Use A.")), Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed"))
|
||||
self.assertEqual(len(fake.made("stream_claude")), 1)
|
||||
self.assertIn("\nWhich one?\n", said.getvalue())
|
||||
self.assertNotIn("Use ... A.", said.getvalue())
|
||||
|
||||
@unittest.skipIf(os.geteuid() == 0, "root writes into a read-only directory")
|
||||
def test_stops_keeping_the_transcript_when_the_finished_chunks_session_cannot_be_deleted(self):
|
||||
folder = self.paths.claude_code_transcripts / "-fake" / str(self.session.id)
|
||||
(folder / "subagents").mkdir(parents=True)
|
||||
folder.chmod(0o500)
|
||||
self.addCleanup(folder.chmod, 0o700)
|
||||
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("finished")])
|
||||
stop = run.run_cycle(self.cycle(fake))
|
||||
self.assertEqual(stop, Stop(1, f"could not delete {folder}: Permission denied; delete every file and folder matching {folder}*, then rerun loop-claude; a rerun before that resumes the finished chunk's session"))
|
||||
self.assertTrue(session.session_open(self.session))
|
||||
self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: finished\n\nEvidence:\n> working\n\n2026-09-21T14:13:20Z Stopped: {stop.reason}\n"])
|
||||
|
||||
def test_stops_when_the_worker_leaves_no_transcript(self):
|
||||
fake = FakeEffects(streams=[Streamed(0)])
|
||||
self.assertEqual(run.run_cycle(self.cycle(fake)), Stop(1, f"claude left no transcript for session {self.session.id}"))
|
||||
|
||||
|
||||
class Retried(unittest.TestCase):
|
||||
def test_retries_a_minute_apart_and_stops_on_the_third_failure(self):
|
||||
fake = FakeEffects()
|
||||
results = [Failure("one"), "done"]
|
||||
self.assertEqual(retry.retried("worker", lambda: results.pop(0), fake.effects()), "done")
|
||||
self.assertEqual(fake.calls, [("sleep", 60)])
|
||||
fake = FakeEffects()
|
||||
self.assertEqual(retry.retried("judge", lambda: Failure("no"), fake.effects()), Stop(1, "the judge failed three times running: no"))
|
||||
self.assertEqual(fake.calls, [("sleep", 60), ("sleep", 60)])
|
||||
|
||||
def test_waits_out_a_usage_limit_which_ends_a_run_of_failures(self):
|
||||
fake = FakeEffects()
|
||||
results = [Failure("one"), Failure("two"), Limited(NOW + 3600, "limit"), Failure("three"), Limited(None, "limit"), Limited(NOW - 600, "limit"), Failure("four"), Failure("five"), Failure("six")]
|
||||
self.assertEqual(retry.retried("worker", lambda: results.pop(0), fake.effects()), Stop(1, "the worker failed three times running: six"))
|
||||
self.assertEqual(fake.calls, [("sleep", 60), ("sleep", 60), ("sleep", 3720), ("sleep", 60), ("sleep", 600), ("sleep", 600), ("sleep", 60), ("sleep", 60)])
|
||||
|
||||
def test_says_what_claude_said_and_when_the_next_try_is_due(self):
|
||||
results = [Limited(NOW + 3600, "You've hit your session limit"), "done"]
|
||||
with contextlib.redirect_stderr(io.StringIO()) as said:
|
||||
retry.retried("judge", lambda: results.pop(0), FakeEffects().effects())
|
||||
self.assertEqual(said.getvalue(), f"the judge hit a usage limit (You've hit your session limit); retrying at <{NOW + 3720}>\n")
|
||||
|
||||
|
||||
class Limits(unittest.TestCase):
|
||||
def test_the_worker_reports_the_latest_reset_its_stream_names(self):
|
||||
rejected = [{"type": "rate_limit_event", "rate_limit_info": {"status": "rejected", "resetsAt": resets_at}} for resets_at in (NOW + 60, NOW + 600)]
|
||||
allowed = {"type": "rate_limit_event", "rate_limit_info": {"status": "allowed", "resetsAt": NOW + 9000}}
|
||||
limited = {"type": "result", "api_error_status": 429, "result": "You've hit your session limit"}
|
||||
fake = FakeEffects(streams=[Streamed(1, rejected[1], allowed, rejected[0], limited)])
|
||||
self.assertEqual(worker.run_worker("/r", [], fake.effects()), Limited(NOW + 600, "You've hit your session limit"))
|
||||
|
||||
def test_a_limit_outranks_the_exit_code_and_its_message_fits_one_line(self):
|
||||
def limited(**said):
|
||||
return {"type": "result", "api_error_status": 429, **said}
|
||||
self.assertEqual(worker.worker_outcome(-9, limited(result="limit\n resets 7pm"), []), Limited(None, "limit resets 7pm"))
|
||||
self.assertEqual(worker.worker_outcome(1, limited(result=" \n"), [NOW]), Limited(NOW, "claude gave no message"))
|
||||
self.assertEqual(worker.worker_outcome(0, limited(), []), Limited(None, "claude gave no message"))
|
||||
self.assertEqual(worker.worker_outcome(0, None, [NOW]), Failure("claude exited 0 without a result event"))
|
||||
self.assertIsNone(worker.worker_outcome(0, {"type": "result"}, [NOW]))
|
||||
|
||||
def test_the_judge_reports_a_limit_whatever_its_exit_code(self):
|
||||
reply = json.dumps({"type": "result", "api_error_status": 429, "is_error": True, "result": "You've hit your session limit · resets 7:40pm (Europe/Stockholm)"})
|
||||
fake = FakeEffects(claude=[ran(reply, code=1, stderr="limited")])
|
||||
self.assertEqual(judge.run_judge("/r", [], "", "", "", fake.effects()), Limited(None, "You've hit your session limit · resets 7:40pm (Europe/Stockholm)"))
|
||||
|
||||
def test_reads_only_a_rejecting_events_whole_seconds(self):
|
||||
for info, want in [({"status": "rejected", "resetsAt": NOW}, NOW), ({"status": "allowed", "resetsAt": NOW}, None), ({"status": "rejected", "resetsAt": True}, None), ({"status": "rejected"}, None), ("rejected", None)]:
|
||||
self.assertEqual(entries.rejected_until({"type": "rate_limit_event", "rate_limit_info": info}), want, info)
|
||||
|
||||
|
||||
class Interrupts(unittest.TestCase):
|
||||
def test_stops_off_a_terminal_before_starting_claude(self):
|
||||
fake = FakeEffects(on_terminal=False)
|
||||
stop = interrupt.interrupt("/r", uuid7(), "m", "/t", "Which one?", paths.paths_from(pathlib.Path("/h")), fake.effects())
|
||||
self.assertEqual(stop, Stop(2, "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal"))
|
||||
self.assertEqual(fake.calls, [])
|
||||
|
||||
def test_stops_when_nothing_was_typed_in_the_handover(self):
|
||||
with tempfile.TemporaryDirectory() as home:
|
||||
path = pathlib.Path(home, "t.jsonl")
|
||||
path.write_text(json.dumps(human("a")) + "\n")
|
||||
fake = FakeEffects(on_terminal_claude=[0], git=[ran()])
|
||||
stop = interrupt.interrupt(home, uuid7(), "m", str(path), "Which one?", paths.paths_from(pathlib.Path(home)), fake.effects())
|
||||
self.assertEqual(stop, Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed"))
|
||||
|
||||
|
||||
class ModelPrompt(unittest.TestCase):
|
||||
OFFERED = [("claude-opus-5-5", "Opus 5.5"), ("claude-haiku-4-5", "Haiku 4.5")]
|
||||
|
||||
def test_reads_a_number_as_the_offered_model_and_anything_else_as_a_name(self):
|
||||
self.assertEqual(model_choice.model_picked(" 2 ", self.OFFERED), "claude-haiku-4-5")
|
||||
self.assertEqual(model_choice.model_picked("opus", self.OFFERED), "opus")
|
||||
self.assertEqual(model_choice.model_picked("3", []), "3")
|
||||
self.assertEqual(model_choice.model_picked("3", self.OFFERED), Failure("pick 1 to 2"))
|
||||
self.assertIsNone(model_choice.model_picked(" ", self.OFFERED))
|
||||
|
||||
def test_asks_again_until_an_answer_picks_a_model(self):
|
||||
with tempfile.TemporaryDirectory() as empty:
|
||||
fake = FakeEffects(inputs=["", "my-model"])
|
||||
self.assertEqual(model_choice.ask_for_model("proj", pathlib.Path("/m.json"), pathlib.Path(empty), fake.effects()), "my-model")
|
||||
self.assertEqual(len(fake.made("input")), 2)
|
||||
fake = FakeEffects(inputs=[EOFError()])
|
||||
self.assertEqual(model_choice.ask_for_model("proj", pathlib.Path("/m.json"), pathlib.Path(empty), fake.effects()), Stop(2, "the human is needed to pick proj's model, but the input ended"))
|
||||
|
||||
|
||||
class WorkerArgs(unittest.TestCase):
|
||||
def test_opens_a_fresh_session_by_name_and_resumes_an_open_one(self):
|
||||
opened = session.session_named("A proj loop-claude", pathlib.Path("/h/.claude/projects"))
|
||||
fresh = worker.worker_args(opened, "m", prompts.fresh("Do it."), resume=False)
|
||||
self.assertEqual(fresh[fresh.index("--session-id") + 1], str(opened.id))
|
||||
self.assertEqual(fresh[fresh.index("--name") + 1], "A proj loop-claude")
|
||||
resumed = worker.worker_args(opened, "m", prompts.resumed(""), resume=True)
|
||||
self.assertEqual(resumed[resumed.index("--resume") + 1], str(opened.id))
|
||||
self.assertNotIn("--session-id", resumed)
|
||||
self.assertTrue(resumed[resumed.index("-p") + 1].startswith("Continue the task; the previous run ended before the chunk was finished. The chunk is finished once"))
|
||||
|
||||
|
||||
class Records(unittest.TestCase):
|
||||
def test_heads_each_record_by_its_name_the_humans_rules_last(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
claude_md = pathlib.Path(root, "home", ".claude", "CLAUDE.md")
|
||||
self.assertEqual(records.read_records(root, claude_md.parent), "")
|
||||
claude_md.parent.mkdir(parents=True)
|
||||
claude_md.write_text("# Global\n")
|
||||
self.assertEqual(records.read_records(root, claude_md.parent), "From ~/.claude/CLAUDE.md:\n# Global")
|
||||
pathlib.Path(root, "docs").mkdir()
|
||||
pathlib.Path(root, "docs", "decisions.md").write_text("# Decisions\n")
|
||||
pathlib.Path(root, "AGENTS.md").write_text("\n# Rules\n")
|
||||
self.assertEqual(records.read_records(root, claude_md.parent), "From AGENTS.md:\n# Rules\n\nFrom docs/decisions.md:\n# Decisions\n\nFrom ~/.claude/CLAUDE.md:\n# Global")
|
||||
pathlib.Path(claude_md.parent, "rules").mkdir()
|
||||
pathlib.Path(claude_md.parent, "rules", "todo-items.md").write_text("# Todo\n")
|
||||
pathlib.Path(claude_md.parent, "rules", "goals-and-audience.md").write_text("# Goals\n")
|
||||
pathlib.Path(claude_md.parent, "rules", "notes.txt").write_text("not a rule\n")
|
||||
pathlib.Path(claude_md.parent, "skills", "larv-review", "standards").mkdir(parents=True)
|
||||
pathlib.Path(claude_md.parent, "skills", "larv-review", "standards", "comments.md").write_text("# Comments\n")
|
||||
self.assertTrue(records.read_records(root, claude_md.parent).endswith("From ~/.claude/CLAUDE.md:\n# Global\n\nFrom ~/.claude/rules/goals-and-audience.md:\n# Goals\n\nFrom ~/.claude/rules/todo-items.md:\n# Todo\n\nFrom ~/.claude/skills/larv-review/standards/comments.md:\n# Comments"))
|
||||
|
||||
def test_stops_on_a_record_it_cannot_read(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
claude_md = pathlib.Path(root, "home", ".claude", "CLAUDE.md")
|
||||
claude_md.mkdir(parents=True)
|
||||
self.assertEqual(records.read_records(root, claude_md.parent), Stop(1, f"CLAUDE.md in {claude_md.parent}: Is a directory - the judge cannot read the records."))
|
||||
pathlib.Path(root, "docs", "decisions.md").mkdir(parents=True)
|
||||
self.assertEqual(records.read_records(root, claude_md.parent), Stop(1, f"docs/decisions.md in {root}: Is a directory - the judge cannot read the records."))
|
||||
pathlib.Path(root, "AGENTS.md").write_bytes(b"# Rules\n\xff\n")
|
||||
self.assertEqual(records.read_records(root, claude_md.parent), Stop(1, f"AGENTS.md in {root} is not UTF-8 on line 2 - the judge cannot read the records."))
|
||||
|
||||
|
||||
def test_stops_on_a_rule_it_cannot_read(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
claude_md = pathlib.Path(root, "home", ".claude", "CLAUDE.md")
|
||||
rules = pathlib.Path(claude_md.parent, "rules")
|
||||
rules.mkdir(parents=True)
|
||||
pathlib.Path(rules, "todo-items.md").write_bytes(b"\xff\n")
|
||||
self.assertEqual(records.read_records(root, claude_md.parent), Stop(1, f"todo-items.md in {rules} is not UTF-8 on line 1 - the judge cannot read the records."))
|
||||
|
||||
class JudgePrompt(unittest.TestCase):
|
||||
def test_shows_the_transcripts_tail_and_returns_what_it_showed(self):
|
||||
prompt, shown = judge.judge_prompt("Do it.", "## Goals", "", "old " + "x" * judge.JUDGE_PROMPT_CHARS + " new")
|
||||
self.assertTrue(shown.endswith(" new"))
|
||||
self.assertNotIn("old", shown)
|
||||
self.assertIn(shown, prompt)
|
||||
self.assertLessEqual(len(prompt), judge.JUDGE_PROMPT_CHARS)
|
||||
|
||||
|
||||
class Grounded(unittest.TestCase):
|
||||
def test_every_verdict_must_quote_the_transcript(self):
|
||||
self.assertTrue(judge.grounded("Needs you: x", "so.\n\nNeeds you: x\n"))
|
||||
self.assertFalse(judge.grounded("invented", "the transcript"))
|
||||
self.assertFalse(judge.grounded("", "the transcript"))
|
||||
self.assertFalse(judge.grounded(" ", "the transcript"))
|
||||
transcript = "done.\n\n**Your step:**\n```\n./run.sh\n```\nRun it."
|
||||
self.assertTrue(judge.grounded("Your step:\n```\n./run.sh\n```\nRun it.", transcript))
|
||||
self.assertTrue(judge.grounded("Your step: ``` ./run.sh ``` Run it.", transcript))
|
||||
self.assertFalse(judge.grounded("**", transcript))
|
||||
|
||||
def test_an_elided_quote_holds_when_its_fragments_appear_in_order(self):
|
||||
transcript = "**Decision for you:** security, or not.\n\nI recommend one more round of each.\n\nI recommend skipping it: it costs."
|
||||
self.assertTrue(judge.grounded("**Decision for you:** security, … ... I recommend one more round of each ... I recommend skipping it: …", transcript))
|
||||
self.assertFalse(judge.grounded("I recommend skipping it ... Decision for you", transcript))
|
||||
self.assertFalse(judge.grounded("Decision for you ... invented", transcript))
|
||||
self.assertFalse(judge.grounded("... …", transcript))
|
||||
|
||||
def test_an_answer_holds_only_word_for_word(self):
|
||||
self.assertTrue(judge.verbatim("Merge **ff-only**.", "Merge ff-only.\nNever squash."))
|
||||
self.assertFalse(judge.verbatim("Merge ... squash.", "Merge ff-only.\nNever squash."))
|
||||
self.assertFalse(judge.verbatim("", "Merge ff-only."))
|
||||
|
||||
|
||||
class Verdict(unittest.TestCase):
|
||||
def test_needs_every_field_the_schema_requires(self):
|
||||
self.assertEqual(verdict_from({"answer": "", "interrupt": False, "evidence": "e", "finished": True, "question": ""}), Finished("e"))
|
||||
self.assertEqual(verdict_from({"answer": "", "interrupt": False, "evidence": "e", "finished": False, "question": "ignored"}), Unfinished("e"))
|
||||
self.assertEqual(verdict_from({"answer": "", "interrupt": True, "evidence": "e", "finished": True, "question": "Which one?"}), Interrupt("e", "Which one?"))
|
||||
self.assertEqual(verdict_from({"answer": "A.", "interrupt": False, "evidence": "e", "finished": False, "question": "Which one?"}), QuotedAnswer("e", "Which one?", "A."))
|
||||
self.assertEqual(verdict_from({"answer": "A.", "interrupt": True, "evidence": "e", "finished": False, "question": "Which one?"}), Interrupt("e", "Which one?"))
|
||||
self.assertEqual(verdict_from({"answer": "A.", "interrupt": False, "evidence": "e", "finished": True, "question": ""}), Failure("the judge quoted an answer without a question"))
|
||||
self.assertEqual(verdict_from({"answer": "", "interrupt": "no", "evidence": "", "finished": True, "question": ""}), Failure("the judge's reply has no interrupt of type boolean"))
|
||||
self.assertEqual(verdict_from({"answer": "", "interrupt": False, "evidence": None, "finished": True, "question": ""}), Failure("the judge's reply has no evidence of type string"))
|
||||
self.assertEqual(verdict_from({"answer": "", "interrupt": True, "evidence": "x", "finished": False, "question": " "}), Failure("the judge interrupted without a question"))
|
||||
self.assertEqual(verdict_from(None), Failure("the judge returned no reply"))
|
||||
|
||||
|
||||
class LoopRuns(unittest.TestCase):
|
||||
def test_stops_naming_the_reload_when_it_hands_over_anything_but_the_state_with_a_task(self):
|
||||
for handed in (["3", "2", "/r", "do it"], ["3"], ["[1]"], [json.dumps({"cycle_number": 3, "root": "/r", "unfinished_evidence": ""})], [json.dumps({"cycle_number": 3, "root": "/r", "task": "", "unfinished_evidence": ""})], [json.dumps({"cycle_number": "3", "root": "/r", "task": "do it", "unfinished_evidence": ""})], [json.dumps({"cycle_number": 3, "root": "", "task": "do it", "unfinished_evidence": ""})], [json.dumps({"cycle_number": 3, "root": "/r", "task": "do it", "turns": 1, "unfinished_evidence": ""})], [json.dumps({"cycle_number": 3, "failures": 0, "root": "/r", "task": "do it", "unfinished_evidence": ""})]):
|
||||
with self.subTest(handed=handed):
|
||||
self.assertEqual(main.loop_run_from([main.RELOAD_FLAG, *handed], CWD, FakeEffects().effects()), Stop(1, f"the edited loop-claude cannot read the state the running one handed it, likely because the edit changed that handover; rerun loop-claude <task>. Handed: {' '.join(handed)}"))
|
||||
|
||||
def test_decodes_a_state_whose_annotations_are_strings(self):
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Stringly:
|
||||
count: "int"
|
||||
name: "str"
|
||||
self.assertEqual(reload.decode_handed('{"count": 1, "name": "n"}', Stringly), Stringly(1, "n"))
|
||||
self.assertIsNone(reload.decode_handed('{"count": "1", "name": "n"}', Stringly))
|
||||
|
||||
def test_stops_when_the_reload_cannot_start_python(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
launcher = pathlib.Path(root, "loop-claude")
|
||||
launcher.write_text("")
|
||||
fake = FakeEffects(python=[ran()])
|
||||
self.assertEqual(reload.exec_if_edited(launcher, "stale", main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence=""), fake.effects()), Stop(1, "could not reload loop-claude: No such file or directory; rerun loop-claude <task>"))
|
||||
|
||||
|
||||
class HelpLimits(unittest.TestCase):
|
||||
def test_help_states_the_limits_the_code_holds(self):
|
||||
said = " ".join(main.__doc__.split())
|
||||
self.assertIn(f"The {['second', 'third', 'fourth', 'fifth'][states.QUOTED_ANSWERS_PER_CYCLE - 1]} question they answer in one cycle", said)
|
||||
# The retry messages say these limits in words too.
|
||||
self.assertEqual((retry.FAILURES_RUNNING, retry.RETRY_DELAY), (3, 60))
|
||||
self.assertIn("fails three times running, retried a minute apart", said)
|
||||
self.assertIn(f"retried {retry.PAST_RESET // 60} minutes after the limit resets, or every {retry.UNKNOWN_RESET_POLL // 60} minutes", said)
|
||||
|
||||
|
||||
class ExitContract(unittest.TestCase):
|
||||
def test_every_exit_1_stop_has_its_clause_in_help(self):
|
||||
read, git, premises_ = "a transcript cannot be read or archived", "git cannot start or finds no checkout", "README.md holds no premises"
|
||||
models_ = "the models file cannot be read or written"
|
||||
names = (*records.RECORD_FILES, records.HUMAN_RULE_NAMES[0], *(f"{folder}*.md" for folder in records.HUMAN_RULE_NAMES[1:]))
|
||||
unreadable = f"README.md, or {', '.join(names[:-1])} or {names[-1]} where they exist, cannot be read or is not UTF-8"
|
||||
# Every Stop whose code is not a literal 0, 2 or 130, in source order: path, function, code, start of reason, its --help clause.
|
||||
clauses = [
|
||||
("cycle/interrupt.py", "interrupt", "1", "entries.reason", read),
|
||||
("cycle/interrupt.py", "interrupt", "1", "f'could not start claude for the interrupt:", "claude cannot start for an interrupt"),
|
||||
("cycle/interrupt.py", "interrupt", "1", "f'could not tell whether you typed anything:", read),
|
||||
("cycle/retry.py", "retried", "1", "f'the {who} failed three times running:", "the worker or the judge fails three times running"),
|
||||
("cycle/run.py", "stopped", "1", "f'{failure.reason}", read),
|
||||
("cycle/run.py", "work", "1", "f'claude left no transcript for session", "claude leaves no transcript"),
|
||||
("cycle/run.py", "keep_answer", "1", "failure.reason", read),
|
||||
("cycle/run.py", "rule", "1", "entries.reason", read),
|
||||
("cycle/run.py", "ask", "1", "failure.reason", read),
|
||||
("cycle/run.py", "close", "1", "failure.reason", read),
|
||||
("cycle/run.py", "close", "1", "failure.reason", "a finished chunk's session cannot be deleted"),
|
||||
("loop/main.py", "loop_run_from", "0 if task else 1", "__doc__.strip()", "no task is given"),
|
||||
("loop/main.py", "loop_run_from", "1", 'f"the edited loop-claude cannot read the state', "a reload cannot read the state the running script handed it"),
|
||||
("loop/reload.py", "exec_if_edited", "1", "f'could not reload loop-claude:", "python cannot start for a reload"),
|
||||
("project/checkout.py", "checkout_root", "1", "f'could not start git:", git),
|
||||
("project/checkout.py", "checkout_root", "1", "found.stderr.strip()", git),
|
||||
("project/model_choice.py", "get_or_ask_model", "1", "f'could not save the model in", models_),
|
||||
("project/model_choice.py", "read_models_file", "1", 'f"could not read {saved}: {getattr(', models_),
|
||||
("project/model_choice.py", "read_models_file", "1", "f'could not read {saved}: not an object", models_),
|
||||
("project/premises.py", "read_premises", "1", "f'README.md has no ##", premises_),
|
||||
("project/premises.py", "read_premises", "1", "f'README.md has ## {name} more than once", premises_),
|
||||
("project/premises.py", "read_premises", "1", "f'README.md has nothing under", premises_),
|
||||
("project/text_file.py", "read_utf8", "1", "f'{name} in {folder}:", unreadable),
|
||||
("project/text_file.py", "read_utf8", "1", "f'{name} in {folder} is not UTF-8", unreadable),
|
||||
]
|
||||
root = pathlib.Path(main.__file__).parents[1]
|
||||
found = []
|
||||
for path in sorted(path for path in root.rglob("*.py") if not path.name.startswith("test_")):
|
||||
functions = [node for node in ast.walk(ast.parse(path.read_text())) if isinstance(node, ast.FunctionDef)]
|
||||
stops = [(call.lineno, function.name, ast.unparse(call.args[0]), ast.unparse(call.args[1])) for function in functions for call in ast.walk(function) if isinstance(call, ast.Call) and getattr(call.func, "id", None) == "Stop" and not (isinstance(call.args[0], ast.Constant) and call.args[0].value in (0, 2, 130))]
|
||||
found += [(str(path.relative_to(root)), function, code, reason) for _, function, code, reason in sorted(stops)]
|
||||
self.assertEqual(len(found), len(clauses), found)
|
||||
for (path, function, code, reason), (want_path, want_function, want_code, reason_start, _) in zip(found, clauses):
|
||||
self.assertEqual((path, function, code), (want_path, want_function, want_code))
|
||||
self.assertTrue(reason.startswith(reason_start), f"{path} {function}: {reason}")
|
||||
help_exit_1 = " ".join(main.__doc__[main.__doc__.index("Exit 1"):main.__doc__.index("Exit 2")].split())
|
||||
self.assertEqual([clause for *_, clause in clauses if f"- {clause}" not in help_exit_1], [])
|
||||
|
||||
|
||||
class JudgeFailures(unittest.TestCase):
|
||||
def test_every_failed_judge_run_has_its_clause_in_help(self):
|
||||
started, field, unasked = "claude cannot start or exits non-zero", "its reply misses or mistypes a field", "interrupts or quotes an answer without a question"
|
||||
# Every Failure the judge's run returns, in source order: path, function, start of reason, its --help clause.
|
||||
clauses = [
|
||||
("verdict_from", "'the judge returned no reply'", field),
|
||||
("verdict_from", 'f"the judge\'s reply has no {name}', field),
|
||||
("verdict_from", "'the judge interrupted without a question'", unasked),
|
||||
("verdict_from", "'the judge quoted an answer without a question'", unasked),
|
||||
("run_judge", "f'could not start claude:", started),
|
||||
("run_judge", "proc.stderr.strip() or f'the judge exited", started),
|
||||
("run_judge", 'f"{verdict.reason}; it replied:', field),
|
||||
("run_judge", "f'the judge quoted {verdict.evidence!r}, which is not in the transcript", "quotes a passage the transcript does not hold"),
|
||||
]
|
||||
functions = [node for node in ast.walk(ast.parse(pathlib.Path(judge.__file__).read_text())) if isinstance(node, ast.FunctionDef)]
|
||||
found = sorted((call.lineno, function.name, ast.unparse(call.args[0])) for function in functions for call in ast.walk(function) if isinstance(call, ast.Call) and getattr(call.func, "id", None) == "Failure")
|
||||
self.assertEqual(len(found), len(clauses), found)
|
||||
for (_, function, reason), (want_function, reason_start, _) in zip(found, clauses):
|
||||
self.assertEqual(function, want_function)
|
||||
self.assertTrue(reason.startswith(reason_start), f"{function}: {reason}")
|
||||
judge_clause = " ".join(main.__doc__[main.__doc__.index("a judge when"):main.__doc__.index("A usage limit")].split())
|
||||
self.assertEqual([clause for *_, clause in clauses if clause not in judge_clause], [])
|
||||
|
||||
|
||||
class Worktrees(unittest.TestCase):
|
||||
def test_lists_the_root_alone_when_git_cannot_start(self):
|
||||
fake = FakeEffects(git=[FileNotFoundError(2, "No such file or directory")])
|
||||
self.assertEqual(checkout.worktrees("/r", fake.effects()), ["/r"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,32 @@
|
||||
import re
|
||||
|
||||
FENCE = re.compile(r"^ {0,3}(`{3,}|~{3,})", re.M)
|
||||
|
||||
|
||||
def sections(text: str) -> dict[str, list[str]]:
|
||||
blocks: list[tuple[str | None, list[str]]] = []
|
||||
opener = ""
|
||||
for line in text.splitlines():
|
||||
if fence := FENCE.match(line):
|
||||
marker = fence.group(1)
|
||||
if not opener:
|
||||
opener = marker
|
||||
elif marker[0] == opener[0] and len(marker) >= len(opener) and not line[fence.end():].strip():
|
||||
opener = ""
|
||||
fenced = bool(opener or fence)
|
||||
if not fenced and line.startswith("## "):
|
||||
blocks.append((line.strip()[3:], []))
|
||||
elif not fenced and line.startswith("# "):
|
||||
blocks.append((None, []))
|
||||
elif blocks and line.strip():
|
||||
blocks[-1][1].append(line)
|
||||
found: dict[str, list[str]] = {}
|
||||
for name, body in blocks:
|
||||
if name is not None:
|
||||
found.setdefault(name, []).append("\n".join(body))
|
||||
return found
|
||||
|
||||
|
||||
# Blockquoted, so a passage holding blank lines still ends visibly where the text after it starts.
|
||||
def quoted(passage: str) -> str:
|
||||
return "\n".join(f"> {line}" for line in passage.splitlines())
|
||||
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 metric_bench import main
|
||||
|
||||
sys.exit(main.main(sys.argv[1:]))
|
||||
@@ -0,0 +1,100 @@
|
||||
from typing import Callable
|
||||
import collections
|
||||
import dataclasses
|
||||
import os
|
||||
import statistics
|
||||
|
||||
from comprehension_history import Place
|
||||
from metric_bench.python_units import Unit
|
||||
|
||||
METRICS: dict[str, Callable[[Unit, dict[str, int]], int]] = {
|
||||
"cognitive complexity": lambda unit, spread: unit.cognitive,
|
||||
"length": lambda unit, spread: unit.length,
|
||||
"shared state": lambda unit, spread: unit.shared_state,
|
||||
"change spread": lambda unit, spread: spread.get(unit.path, 0),
|
||||
}
|
||||
|
||||
|
||||
# Code Maat's default --max-changeset-size: a sweep across the tree couples every file to every other.
|
||||
LARGEST_CHANGESET = 30
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Score:
|
||||
auc: float
|
||||
top_k: float
|
||||
constant: bool
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class RunScores:
|
||||
units: int
|
||||
named: int
|
||||
unmeasured: int
|
||||
scores: dict[str, Score]
|
||||
|
||||
|
||||
def co_changed(log: str) -> dict[str, int]:
|
||||
"""For each file, how many other files changed in a commit with it, commits of more than LARGEST_CHANGESET files left out; log is `git log --format=tformat:@@ --name-only`."""
|
||||
partners: dict[str, set[str]] = collections.defaultdict(set)
|
||||
for commit in log.split("@@\n"):
|
||||
files = set(filter(None, commit.split("\n")))
|
||||
if len(files) > LARGEST_CHANGESET:
|
||||
continue
|
||||
for path in files:
|
||||
partners[path] |= files - {path}
|
||||
return {path: len(others) for path, others in partners.items()}
|
||||
|
||||
|
||||
def bench(units: list[Unit], places: list[Place], unresolved: int, spread: dict[str, int]) -> RunScores | None:
|
||||
"""How well each metric ranks the units the seats named above the rest; None when the named units are none or all of them. unresolved counts the places that named no tracked file."""
|
||||
names = {(place.path, place.name) for place in places}
|
||||
named = [unit for unit in units if (unit.path, unit.name) in names]
|
||||
if not named or len(named) == len(units):
|
||||
return None
|
||||
rest = [unit for unit in units if (unit.path, unit.name) not in names]
|
||||
found = {(unit.path, unit.name) for unit in named}
|
||||
unmeasured = unresolved + len({place for place in places if (place.path, place.name) not in found})
|
||||
scores = {}
|
||||
for metric, value in METRICS.items():
|
||||
named_values = [value(unit, spread) for unit in named]
|
||||
rest_values = [value(unit, spread) for unit in rest]
|
||||
scores[metric] = Score(auc(named_values, rest_values), top_k(named_values, rest_values), len(set(named_values + rest_values)) == 1)
|
||||
return RunScores(len(units), len(named), unmeasured, scores)
|
||||
|
||||
|
||||
def auc(named: list[int], rest: list[int]) -> float:
|
||||
"""The chance a named unit outranks one not named, a tie counting half: 0.5 is a coin toss, 1.0 a perfect ranking."""
|
||||
wins = sum((a > b) + 0.5 * (a == b) for a in named for b in rest)
|
||||
return wins / (len(named) * len(rest))
|
||||
|
||||
|
||||
def top_k(named: list[int], rest: list[int]) -> float:
|
||||
"""The share of the metric's k highest units the seats named, k being how many they named. Units tied at the cut share its remaining slots evenly, as a random order of them would."""
|
||||
k = len(named)
|
||||
cut = sorted(named + rest, reverse=True)[k - 1]
|
||||
above = sum(value > cut for value in named)
|
||||
slots = k - above - sum(value > cut for value in rest)
|
||||
tied_named = sum(value == cut for value in named)
|
||||
tied = tied_named + sum(value == cut for value in rest)
|
||||
return (above + slots * tied_named / tied) / k
|
||||
|
||||
|
||||
def medians(runs: list[RunScores]) -> dict[str, Score]:
|
||||
return {metric: Score(statistics.median(run.scores[metric].auc for run in runs), statistics.median(run.scores[metric].top_k for run in runs), all(run.scores[metric].constant for run in runs)) for metric in METRICS}
|
||||
|
||||
|
||||
def tracked_places(places: list[Place], tracked: list[str]) -> tuple[list[Place], list[Place]]:
|
||||
"""Entries written before paths were written from the repository's root shorten a path once they have named its folder: `cycle/run.py` after `bin/loop_claude/cycle/states.py`. Each place resolves to the one tracked file it names, or, where several match, the one in the folder of the place resolved before it; a place naming no file, or several, is dropped. Returns the resolved places and the dropped ones."""
|
||||
found = []
|
||||
dropped = []
|
||||
before = ""
|
||||
for place in places:
|
||||
candidates = [place.path] if place.path in tracked else [path for path in tracked if path.endswith("/" + place.path)]
|
||||
nearest = [path for path in candidates if path.startswith(os.path.dirname(before) + "/")] if len(candidates) > 1 else candidates
|
||||
if len(nearest) == 1:
|
||||
before = nearest[0]
|
||||
found.append(Place(before, place.name))
|
||||
else:
|
||||
dropped.append(place)
|
||||
return found, dropped
|
||||
@@ -0,0 +1,160 @@
|
||||
"""Bench cheap static metrics against the places a project's comprehension panel named as hardest.
|
||||
|
||||
usage: metric-bench [history]
|
||||
|
||||
history defaults to docs/comprehension-history.md in the checkout it runs in, and the bench reads
|
||||
the checkout that holds the history. For each scoring run in it, those a fall called inside a paired
|
||||
ruling included, at the commit the panel read, it measures each module-level function and each
|
||||
method of a module-level class in the Python files git tracks, leaving out test_*.py, *_test.py and
|
||||
anything under a tests/ folder:
|
||||
|
||||
- cognitive complexity: SonarSource's white paper, read for Python;
|
||||
- length: lines;
|
||||
- shared state: attributes on self that another method of the class also writes, plus names
|
||||
declared global or nonlocal;
|
||||
- change spread: how many other files changed in a commit with the unit's file, up to that commit,
|
||||
leaving out commits of more than 30 files.
|
||||
|
||||
It then prints, for each metric, how well it ranks the units the panel named above the rest: AUC
|
||||
(0.5 is a coin toss, 1.0 a perfect ranking) and top k (the share of the metric's k highest units
|
||||
the panel named, k being how many it named; Chance is what top k scores at random). A metric that
|
||||
gave every unit one value reads "constant". A last row gives the medians. Unmeasured counts the
|
||||
distinct places that name no Python function or method, such as a section of a markdown file, or no
|
||||
single tracked file.
|
||||
|
||||
Below the table it names:
|
||||
- each run it skipped because its commit is not in the checkout;
|
||||
- each run it could not score because its places name no measured unit, or every one;
|
||||
- each file left out of its run because it does not parse on this Python.
|
||||
|
||||
Exit 1, saying why, on unknown arguments, or when git cannot start or finds no checkout, the history
|
||||
cannot be read, or no scoring run could be scored.
|
||||
"""
|
||||
import pathlib
|
||||
import statistics
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
from metric_bench.bench import bench, co_changed, medians, METRICS, RunScores, Score, tracked_places
|
||||
from comprehension_history import entries, Entry
|
||||
from failure import Failure
|
||||
from metric_bench.python_units import measured, python_units, Unit
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
if argv in (["-h"], ["--help"]):
|
||||
print(__doc__.strip())
|
||||
return 0
|
||||
if len(argv) > 1 or argv[:1] and argv[0].startswith("-"):
|
||||
print(f"unknown arguments {' '.join(argv)}; usage: metric-bench [history]", file=sys.stderr)
|
||||
return 1
|
||||
read = read_history(pathlib.Path(argv[0]).resolve() if argv else None)
|
||||
if isinstance(read, Failure):
|
||||
return failed(read)
|
||||
top, history, text = read
|
||||
benched = bench_runs(text, top)
|
||||
if isinstance(benched, Failure):
|
||||
return failed(benched)
|
||||
rows, notes = benched
|
||||
if not rows:
|
||||
return failed(Failure(f"no scoring run in {history} could be scored; its format is what ~/.claude/bin/larv-review writes{noted(notes)}"))
|
||||
print(table(rows) + noted(notes))
|
||||
return 0
|
||||
|
||||
|
||||
def read_history(given: pathlib.Path | None) -> tuple[str, pathlib.Path, str] | Failure:
|
||||
"""The checkout that holds the history, the history's path and its text."""
|
||||
if given and not given.parent.is_dir():
|
||||
return Failure(f"could not read {given}: no folder {given.parent}")
|
||||
found = git(["rev-parse", "--show-toplevel"], str(given.parent) if given else None)
|
||||
if isinstance(found, Failure):
|
||||
return found
|
||||
history = given or pathlib.Path(found.strip(), "docs", "comprehension-history.md")
|
||||
if not given and not history.exists():
|
||||
return Failure(f"no comprehension history at {history}; larv-review writes one at a project's first paired ruling or scoring run")
|
||||
try:
|
||||
return found.strip(), history, history.read_text(encoding="utf-8")
|
||||
except (OSError, UnicodeDecodeError) as failure:
|
||||
return Failure(f"could not read {history}: {failure}")
|
||||
|
||||
|
||||
def scored_runs(found: list[Entry]) -> list[Entry]:
|
||||
"""Each scoring run, and each paired ruling holding the scores a fall called unless a scoring run on its commit records them too."""
|
||||
runs = {entry.commit for entry in found if not entry.paired}
|
||||
return [entry for entry in found if not entry.paired or entry.scored_places and entry.commit not in runs]
|
||||
|
||||
|
||||
def bench_runs(text: str, top: str) -> tuple[list[tuple[str, RunScores]], list[str]] | Failure:
|
||||
"""Each scored run's heading and scores, and a note for each run skipped or not scored and each file left out."""
|
||||
rows = []
|
||||
notes = []
|
||||
for run in scored_runs(entries(text)):
|
||||
if isinstance(missing := git(["cat-file", "-e", f"{run.commit}^{{commit}}"], top), Failure):
|
||||
notes.append(f"Skipped, its commit is not in {top}: {run.heading} ({missing.reason})")
|
||||
continue
|
||||
scored = run_scores(run, top)
|
||||
if isinstance(scored, Failure):
|
||||
return scored
|
||||
scores, unparsed = scored
|
||||
notes += [f"Left out of {run.heading}: {reason}" for reason in unparsed]
|
||||
if scores:
|
||||
rows.append((run.heading, scores))
|
||||
else:
|
||||
notes.append(f"Not scored, its places name no measured unit or every one: {run.heading}")
|
||||
return rows, notes
|
||||
|
||||
|
||||
def noted(notes: list[str]) -> str:
|
||||
return "\n\n" + "\n".join(notes) if notes else ""
|
||||
|
||||
|
||||
def run_scores(run: Entry, top: str) -> tuple[RunScores | None, list[str]] | Failure:
|
||||
"""The run's scores, and why each file that does not parse was left out."""
|
||||
listed = git(["ls-tree", "-r", "-z", "--name-only", run.commit], top)
|
||||
if isinstance(listed, Failure):
|
||||
return listed
|
||||
tracked = list(filter(None, listed.split("\0")))
|
||||
units: list[Unit] = []
|
||||
unparsed = []
|
||||
for path in filter(measured, tracked):
|
||||
source = git(["show", f"{run.commit}:{path}"], top)
|
||||
if isinstance(source, Failure):
|
||||
return source
|
||||
found = python_units(path, source)
|
||||
if isinstance(found, Failure):
|
||||
unparsed.append(found.reason)
|
||||
else:
|
||||
units += found
|
||||
log = git(["-c", "core.quotePath=false", "log", "--no-merges", "--format=tformat:@@", "--name-only", run.commit], top)
|
||||
if isinstance(log, Failure):
|
||||
return log
|
||||
places, dropped = tracked_places(run.scored_places, tracked)
|
||||
return bench(units, places, len(set(dropped)), co_changed(log)), unparsed
|
||||
|
||||
|
||||
def table(rows: list[tuple[str, RunScores]]) -> str:
|
||||
head = ["Scoring run", "Units", "Named", "Unmeasured", "Chance", *METRICS]
|
||||
lines = ["| " + " | ".join(head) + " |", "|" + "---|" * len(head)]
|
||||
for heading, run in rows:
|
||||
lines.append("| " + " | ".join([heading, str(run.units), str(run.named), str(run.unmeasured), f"top k {run.named / run.units:.2f}", *(cell(run.scores[metric]) for metric in METRICS)]) + " |")
|
||||
medianed = medians([run for _, run in rows])
|
||||
chance = statistics.median(run.named / run.units for _, run in rows)
|
||||
lines.append("| " + " | ".join(["Median", "", "", "", f"top k {chance:.2f}", *(cell(medianed[metric]) for metric in METRICS)]) + " |")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def cell(score: Score) -> str:
|
||||
return "constant" if score.constant else f"AUC {score.auc:.2f}, top k {score.top_k:.2f}"
|
||||
|
||||
|
||||
def git(args: list[str], cwd: str | None) -> str | Failure:
|
||||
try:
|
||||
ran = subprocess.run(["git", *args], capture_output=True, cwd=cwd, encoding="utf-8", errors="replace")
|
||||
except OSError as failure:
|
||||
return Failure(f"could not start git: {failure.strerror}")
|
||||
return ran.stdout if ran.returncode == 0 else Failure(f"git {' '.join(args)}: {ran.stderr.strip()}")
|
||||
|
||||
|
||||
def failed(failure: Failure) -> int:
|
||||
print(failure.reason, file=sys.stderr)
|
||||
return 1
|
||||
@@ -0,0 +1,127 @@
|
||||
import ast
|
||||
import collections
|
||||
import dataclasses
|
||||
import sys
|
||||
|
||||
from failure import Failure
|
||||
|
||||
FUNCTION = (ast.FunctionDef, ast.AsyncFunctionDef)
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Unit:
|
||||
path: str
|
||||
name: str
|
||||
cognitive: int
|
||||
length: int
|
||||
shared_state: int
|
||||
|
||||
|
||||
def measured(path: str) -> bool:
|
||||
"""A Python file outside the tests."""
|
||||
folders, _, name = path.rpartition("/")
|
||||
return name.endswith(".py") and not name.startswith("test_") and not name.endswith("_test.py") and "tests" not in folders.split("/")
|
||||
|
||||
|
||||
def python_units(path: str, source: str) -> list[Unit] | Failure:
|
||||
"""Each module-level function and each method of a module-level class in source, with its metrics."""
|
||||
try:
|
||||
tree = ast.parse(source)
|
||||
except (SyntaxError, ValueError) as failure:
|
||||
return Failure(f"{path} does not parse on Python {sys.version_info[0]}.{sys.version_info[1]}: {failure}")
|
||||
units = []
|
||||
for node in tree.body:
|
||||
if isinstance(node, FUNCTION):
|
||||
units.append(unit(path, node, 0))
|
||||
elif isinstance(node, ast.ClassDef):
|
||||
shared = shared_writes(node)
|
||||
units += [unit(path, method, shared[method.name]) for method in node.body if isinstance(method, FUNCTION)]
|
||||
return units
|
||||
|
||||
|
||||
def unit(path: str, node: ast.FunctionDef | ast.AsyncFunctionDef, shared: int) -> Unit:
|
||||
globals_written = sum(len(statement.names) for statement in ast.walk(node) if isinstance(statement, ast.Global | ast.Nonlocal))
|
||||
return Unit(path, node.name, cognitive(node), (node.end_lineno or node.lineno) - node.lineno + 1, shared + globals_written)
|
||||
|
||||
|
||||
def shared_writes(cls: ast.ClassDef) -> collections.Counter[str]:
|
||||
"""For each method, how many of the attributes it writes on self another method of the class writes too."""
|
||||
writers = collections.defaultdict(set)
|
||||
for method in cls.body:
|
||||
if isinstance(method, FUNCTION):
|
||||
for node in ast.walk(method):
|
||||
for target in written(node):
|
||||
if isinstance(target, ast.Attribute) and isinstance(target.value, ast.Name) and target.value.id == "self":
|
||||
writers[target.attr].add(method.name)
|
||||
return collections.Counter(method for methods in writers.values() if len(methods) > 1 for method in methods)
|
||||
|
||||
|
||||
def written(node: ast.AST) -> list[ast.expr]:
|
||||
if isinstance(node, ast.Assign):
|
||||
targets = node.targets
|
||||
elif isinstance(node, ast.AugAssign | ast.AnnAssign | ast.For | ast.AsyncFor | ast.comprehension):
|
||||
targets = [node.target]
|
||||
elif isinstance(node, ast.withitem) and node.optional_vars:
|
||||
targets = [node.optional_vars]
|
||||
else:
|
||||
return []
|
||||
return [leaf for target in targets for leaf in assigned(target)]
|
||||
|
||||
|
||||
def assigned(target: ast.expr) -> list[ast.expr]:
|
||||
"""What a target writes: each part of an unpacking, and for `x[i] = …` the x."""
|
||||
if isinstance(target, ast.Tuple | ast.List):
|
||||
return [leaf for element in target.elts for leaf in assigned(element)]
|
||||
if isinstance(target, ast.Starred | ast.Subscript):
|
||||
return assigned(target.value)
|
||||
return [target]
|
||||
|
||||
|
||||
# SonarSource's "Cognitive Complexity" white paper (G. Ann Campbell, 2017), read for Python: a comprehension counts as a loop and each of its `if` clauses as a condition.
|
||||
def cognitive(function: ast.FunctionDef | ast.AsyncFunctionDef) -> int:
|
||||
return inside(function.body, 0, function.name)
|
||||
|
||||
|
||||
# One case per node type, as the white paper gives one rule per structure.
|
||||
def score(node: ast.AST, nesting: int, name: str) -> int:
|
||||
"""The cognitive complexity `node` adds, its children included, at nesting depth `nesting`; a call to `name`, the function's own, counts as recursion."""
|
||||
if isinstance(node, ast.If):
|
||||
return 1 + nesting + branches(node, nesting, name)
|
||||
if isinstance(node, ast.For | ast.AsyncFor | ast.While):
|
||||
head = node.test if isinstance(node, ast.While) else node.iter
|
||||
return 1 + nesting + score(head, nesting, name) + inside(node.body, nesting + 1, name) + (1 + inside(node.orelse, nesting + 1, name) if node.orelse else 0)
|
||||
if isinstance(node, ast.Try | ast.TryStar):
|
||||
handlers = sum(1 + nesting + inside(handler.body, nesting + 1, name) for handler in node.handlers)
|
||||
return inside(node.body + node.orelse + node.finalbody, nesting, name) + handlers
|
||||
if isinstance(node, ast.Match):
|
||||
return 1 + nesting + score(node.subject, nesting, name) + sum(inside(case.body, nesting + 1, name) for case in node.cases)
|
||||
if isinstance(node, ast.IfExp):
|
||||
return 1 + nesting + inside([node.test, node.body, node.orelse], nesting + 1, name)
|
||||
if isinstance(node, ast.ListComp | ast.SetComp | ast.DictComp | ast.GeneratorExp):
|
||||
return sum(1 + nesting + len(generator.ifs) for generator in node.generators) + inside(list(ast.iter_child_nodes(node)), nesting + 1, name)
|
||||
if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef | ast.Lambda):
|
||||
return inside(node.body if isinstance(node.body, list) else [node.body], nesting + 1, name)
|
||||
return (isinstance(node, ast.BoolOp) or called(node) == name) + inside(list(ast.iter_child_nodes(node)), nesting, name)
|
||||
|
||||
|
||||
def called(node: ast.AST) -> str | None:
|
||||
"""The function a call names, or the method it calls on self."""
|
||||
if not isinstance(node, ast.Call):
|
||||
return None
|
||||
if isinstance(node.func, ast.Name):
|
||||
return node.func.id
|
||||
if isinstance(node.func, ast.Attribute) and isinstance(node.func.value, ast.Name) and node.func.value.id == "self":
|
||||
return node.func.attr
|
||||
return None
|
||||
|
||||
|
||||
def inside(nodes: list, nesting: int, name: str) -> int:
|
||||
return sum(score(node, nesting, name) for node in nodes)
|
||||
|
||||
|
||||
def branches(node: ast.If, nesting: int, name: str) -> int:
|
||||
"""An if's test and bodies; an elif or else adds 1 at no extra depth."""
|
||||
total = score(node.test, nesting, name) + inside(node.body, nesting + 1, name)
|
||||
if len(node.orelse) == 1 and isinstance(node.orelse[0], ast.If):
|
||||
return total + 1 + branches(node.orelse[0], nesting, name)
|
||||
return total + (1 + inside(node.orelse, nesting + 1, name) if node.orelse else 0)
|
||||
@@ -0,0 +1,253 @@
|
||||
import ast
|
||||
import os
|
||||
import pathlib
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import textwrap
|
||||
import unittest
|
||||
|
||||
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 failure import Failure
|
||||
from test_env import isolated_env
|
||||
from metric_bench.main import scored_runs
|
||||
|
||||
TOOL = pathlib.Path(__file__).resolve().parents[1] / "metric-bench"
|
||||
|
||||
|
||||
def scored(source: str) -> int:
|
||||
function = ast.parse(textwrap.dedent(source)).body[0]
|
||||
assert isinstance(function, ast.FunctionDef)
|
||||
return cognitive(function)
|
||||
|
||||
|
||||
class Cognitive(unittest.TestCase):
|
||||
def test_scores_the_white_papers_sum_of_primes_without_its_labelled_continue(self):
|
||||
self.assertEqual(scored("""
|
||||
def sum_of_primes(limit):
|
||||
total = 0
|
||||
for i in range(1, limit + 1):
|
||||
for j in range(2, i):
|
||||
if i % j == 0:
|
||||
break
|
||||
total += i
|
||||
return total
|
||||
"""), 6)
|
||||
|
||||
def test_counts_elif_and_else_flat_and_a_nested_ternary_by_its_depth(self):
|
||||
self.assertEqual(scored("""
|
||||
def f(a):
|
||||
if a:
|
||||
return 1 if a > 1 else 2
|
||||
elif a is None:
|
||||
return 3
|
||||
else:
|
||||
return 4
|
||||
"""), 5)
|
||||
|
||||
def test_counts_each_boolean_operator_sequence_a_handler_a_match_and_recursion(self):
|
||||
self.assertEqual(scored("""
|
||||
def f(a, b, c):
|
||||
try:
|
||||
if a and b and c or a:
|
||||
match a:
|
||||
case 1:
|
||||
return f(b, c, a)
|
||||
except ValueError:
|
||||
pass
|
||||
"""), 1 + 2 + 2 + 1 + 1)
|
||||
|
||||
def test_nests_a_while_a_lambda_and_an_inner_function(self):
|
||||
self.assertEqual(scored("""
|
||||
def f(a):
|
||||
while a:
|
||||
g = lambda b: 1 if b else 2
|
||||
def h():
|
||||
if a:
|
||||
pass
|
||||
"""), 1 + 3 + 3)
|
||||
|
||||
def test_counts_a_call_to_itself_on_self_as_recursion(self):
|
||||
self.assertEqual(scored("""
|
||||
def walk(self, node):
|
||||
return self.walk(node.child)
|
||||
"""), 1)
|
||||
|
||||
def test_counts_a_comprehension_as_a_loop_and_its_conditions(self):
|
||||
self.assertEqual(scored("""
|
||||
def f(rows):
|
||||
return [row for row in rows if row if row > 1]
|
||||
"""), 3)
|
||||
|
||||
|
||||
class Units(unittest.TestCase):
|
||||
def test_measures_functions_and_methods_with_the_state_methods_share(self):
|
||||
units = python_units("a.py", textwrap.dedent("""
|
||||
COUNT = 0
|
||||
|
||||
def bump():
|
||||
global COUNT
|
||||
COUNT += 1
|
||||
|
||||
class Box:
|
||||
def __init__(self):
|
||||
self.size = 0
|
||||
|
||||
def grow(self):
|
||||
self.size += 1
|
||||
self.name = "x"
|
||||
|
||||
def rename(self):
|
||||
self.name, self.other = "y", 1
|
||||
self.buf[self.size] = 0
|
||||
"""))
|
||||
self.assertEqual(units, [Unit("a.py", "bump", 0, 3, 1), Unit("a.py", "__init__", 0, 2, 1), Unit("a.py", "grow", 0, 3, 2), Unit("a.py", "rename", 0, 3, 1)])
|
||||
|
||||
def test_measures_python_files_outside_the_tests(self):
|
||||
self.assertEqual([path for path in ["a.py", "bin/test_a.py", "a_test.py", "tests/b.py", "e2e-tests/c.py", "README.md"] if measured(path)], ["a.py", "e2e-tests/c.py"])
|
||||
|
||||
def test_a_source_that_does_not_parse_is_a_failure_naming_it(self):
|
||||
failure = python_units("a.py", "def (")
|
||||
assert isinstance(failure, Failure)
|
||||
self.assertIn("a.py does not parse on Python", failure.reason)
|
||||
|
||||
|
||||
class Places(unittest.TestCase):
|
||||
HISTORY = textwrap.dedent("""
|
||||
# Comprehension history
|
||||
|
||||
## 2026-10-08T12:50:49Z, PR #224 at a58a0a8
|
||||
|
||||
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|
||||
|---|---|---|---|---|---|
|
||||
| Mean | 7 | 7 | 7 | 7 | 7 |
|
||||
|
||||
Junior A, hardest first:
|
||||
|
||||
- `skills/x/SKILL.md:77` "Architecture"
|
||||
- `bin/tool/cycle/states.py:69` `transition`, with `cycle/run.py:55` `step` and `:90` `close`
|
||||
|
||||
Inherited architect, would restructure first:
|
||||
|
||||
- `bin/tool/cycle/judge.py:31` `run_judge`
|
||||
|
||||
## 2026-10-08T18:37:21Z, PR #228 at 2682668, against 8c9bf09
|
||||
|
||||
Mid A, decided by:
|
||||
|
||||
- `bin/tool/cycle/run.py:1` `step`
|
||||
""")
|
||||
|
||||
def test_reads_each_scoring_runs_places_and_leaves_rulings_out_unless_they_hold_a_falls_scores(self):
|
||||
runs = scored_runs(entries(self.HISTORY))
|
||||
self.assertEqual([(run.heading, run.commit) for run in runs], [("2026-10-08T12:50:49Z, PR #224 at a58a0a8", "a58a0a8")])
|
||||
fall = "\n## 2026-10-09T09:00:00Z, PR #232 at {commit}, against 12d6d75\n\nRuling: worse\n\nJunior A, hardest first:\n\n- `bin/a.py:3` `f`\n"
|
||||
self.assertEqual([run.commit for run in scored_runs(entries(self.HISTORY + fall.format(commit="bbbbbbb")))], ["a58a0a8", "bbbbbbb"])
|
||||
self.assertEqual([run.commit for run in scored_runs(entries(self.HISTORY + fall.format(commit="a58a0a8")))], ["a58a0a8"])
|
||||
self.assertEqual(runs[0].scored_places, [Place("skills/x/SKILL.md", None), Place("bin/tool/cycle/states.py", "transition"), Place("cycle/run.py", "step"), Place("cycle/run.py", "close"), Place("bin/tool/cycle/judge.py", "run_judge")])
|
||||
|
||||
def test_resolves_a_shortened_path_to_the_file_nearest_the_one_before_it(self):
|
||||
tracked = ["bin/tool/cycle/states.py", "bin/tool/cycle/run.py", "bin/other/cycle/run.py"]
|
||||
places = [Place("bin/tool/cycle/states.py", "transition"), Place("cycle/run.py", "step"), Place("gone.py", "x")]
|
||||
self.assertEqual(tracked_places(places, tracked), ([Place("bin/tool/cycle/states.py", "transition"), Place("bin/tool/cycle/run.py", "step")], [Place("gone.py", "x")]))
|
||||
|
||||
def test_a_full_path_wins_over_a_file_in_the_folder_before_it(self):
|
||||
self.assertEqual(tracked_places([Place("pkg/x.py", "a"), Place("main.py", "f")], ["pkg/x.py", "main.py", "pkg/main.py"])[0][-1], Place("main.py", "f"))
|
||||
|
||||
def test_resolves_a_shortened_path_after_a_repeated_place_by_the_repeat(self):
|
||||
tracked = ["bin/a/main.py", "bin/b/main.py", "bin/b/bench.py"]
|
||||
places = [Place("bin/a/main.py", "main"), Place("bin/b/bench.py", "bench"), Place("bin/a/main.py", "main"), Place("main.py", "figures")]
|
||||
self.assertEqual(tracked_places(places, tracked)[0][-1], Place("bin/a/main.py", "figures"))
|
||||
|
||||
def test_drops_a_shortened_path_two_files_match_with_no_place_before_it(self):
|
||||
self.assertEqual(tracked_places([Place("cycle/run.py", "step")], ["bin/tool/cycle/run.py", "bin/other/cycle/run.py"]), ([], [Place("cycle/run.py", "step")]))
|
||||
|
||||
|
||||
class Bench(unittest.TestCase):
|
||||
def test_auc_is_one_for_a_perfect_ranking_and_counts_a_tie_half(self):
|
||||
self.assertEqual(auc([5, 4], [1, 2]), 1.0)
|
||||
self.assertEqual(auc([3], [3]), 0.5)
|
||||
|
||||
def test_co_changed_counts_each_files_distinct_partners_past_a_sweep(self):
|
||||
sweep = "".join(f"f{i}.py\n" for i in range(31))
|
||||
self.assertEqual(co_changed(f"@@\na.py\nmy b.py\n@@\na.py\nc.py\n@@\na.py\n@@\n{sweep}"), {"a.py": 2, "my b.py": 1, "c.py": 1})
|
||||
|
||||
def test_top_k_shares_the_seats_at_a_tied_cut_evenly(self):
|
||||
self.assertEqual(top_k([0, 0], [0, 0, 0, 0]), 1 / 3)
|
||||
self.assertEqual(top_k([5, 1], [1, 1]), 2 / 3)
|
||||
|
||||
def test_scores_the_named_units_and_counts_places_no_unit_measures(self):
|
||||
units = [Unit("a.py", "hard", 9, 40, 0), Unit("a.py", "easy", 1, 5, 0), Unit("b.py", "plain", 2, 6, 0)]
|
||||
run = bench(units, [Place("a.py", "hard"), Place("doc.md", None)], 2, {"a.py": 1})
|
||||
assert run is not None
|
||||
self.assertEqual((run.units, run.named, run.unmeasured), (3, 1, 3))
|
||||
self.assertEqual((run.scores["cognitive complexity"].auc, run.scores["cognitive complexity"].top_k), (1.0, 1.0))
|
||||
self.assertEqual((run.scores["shared state"].auc, run.scores["shared state"].top_k), (0.5, 1 / 3))
|
||||
|
||||
def test_a_run_naming_no_unit_or_every_unit_is_not_scored(self):
|
||||
self.assertIsNone(bench([Unit("a.py", "f", 1, 1, 0)], [Place("doc.md", None)], 0, {}))
|
||||
self.assertIsNone(bench([Unit("a.py", "f", 1, 1, 0)], [Place("a.py", "f")], 0, {}))
|
||||
|
||||
|
||||
class BlackBox(unittest.TestCase):
|
||||
def project(self, history: str) -> str:
|
||||
directory = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(directory.cleanup)
|
||||
top = directory.name
|
||||
env = isolated_env()
|
||||
for args in (["init", "-q"], ["config", "user.email", "t@t"], ["config", "user.name", "t"]):
|
||||
subprocess.run(["git", *args], cwd=top, check=True, env=env)
|
||||
pathlib.Path(top, "a.py").write_text("def hard(a):\n\tif a:\n\t\tfor x in a:\n\t\t\tif x:\n\t\t\t\treturn x\n\n\ndef easy():\n\treturn 1\n")
|
||||
pathlib.Path(top, "test_a.py").write_text("def test_hard():\n\tif 1:\n\t\tpass\n")
|
||||
subprocess.run(["git", "add", "."], cwd=top, check=True, env=env)
|
||||
subprocess.run(["git", "commit", "-qm", "a"], cwd=top, check=True, env=env)
|
||||
commit = subprocess.run(["git", "rev-parse", "--short", "HEAD"], cwd=top, check=True, capture_output=True, text=True, env=env).stdout.strip()
|
||||
os.makedirs(pathlib.Path(top, "docs"))
|
||||
pathlib.Path(top, "docs", "comprehension-history.md").write_text(history.replace("COMMIT", commit))
|
||||
return top
|
||||
|
||||
def run_tool(self, top: str, *args: str) -> subprocess.CompletedProcess:
|
||||
return subprocess.run([sys.executable, str(TOOL), *args], cwd=top, capture_output=True, text=True, env=isolated_env())
|
||||
|
||||
def test_prints_each_metrics_score_on_each_run_and_the_medians(self):
|
||||
top = self.project("# Comprehension history\n\n## 2026-10-08T12:50:49Z, PR #1 at COMMIT\n\nJunior A, hardest first:\n\n- `a.py:1` `hard`\n")
|
||||
ran = self.run_tool(top)
|
||||
self.assertEqual(ran.returncode, 0, ran.stderr)
|
||||
self.assertIn("| 2026-10-08T12:50:49Z, PR #1 at ", ran.stdout)
|
||||
self.assertIn("| 2 | 1 | 0 | top k 0.50 | AUC 1.00, top k 1.00 | AUC 1.00, top k 1.00 | constant | constant |", ran.stdout)
|
||||
self.assertIn("| Median |", ran.stdout)
|
||||
|
||||
def test_exits_1_when_no_run_names_a_measured_unit(self):
|
||||
top = self.project("# Comprehension history\n\n## 2026-10-08T12:50:49Z, PR #1 at COMMIT\n\nJunior A, hardest first:\n\n- `README.md:1` \"Install\"\n")
|
||||
ran = self.run_tool(top)
|
||||
self.assertEqual((ran.returncode, ran.stdout), (1, ""))
|
||||
self.assertIn("no scoring run in", ran.stderr)
|
||||
|
||||
def test_exits_1_naming_a_history_it_cannot_read_and_unknown_arguments(self):
|
||||
top = self.project("")
|
||||
self.assertIn("could not read", self.run_tool(top, str(pathlib.Path(top, "missing.md"))).stderr)
|
||||
pathlib.Path(top, "docs", "comprehension-history.md").unlink()
|
||||
self.assertIn("no comprehension history at", self.run_tool(top).stderr)
|
||||
self.assertIn("could not read", self.run_tool(top, str(pathlib.Path(top, "gone", "x.md"))).stderr)
|
||||
self.assertEqual(self.run_tool(top, "--x").returncode, 1)
|
||||
|
||||
def test_skips_and_names_a_run_whose_commit_the_checkout_lacks(self):
|
||||
top = self.project("# Comprehension history\n\n## 2026-10-07T12:00:00Z, PR #0 at 0123456\n\nJunior A, hardest first:\n\n- `a.py:1` `hard`\n\n## 2026-10-08T12:50:49Z, PR #1 at COMMIT\n\nJunior A, hardest first:\n\n- `a.py:1` `hard`\n")
|
||||
ran = self.run_tool(top)
|
||||
self.assertEqual(ran.returncode, 0, ran.stderr)
|
||||
self.assertIn("Skipped, its commit is not in", ran.stdout)
|
||||
self.assertIn("PR #0 at 0123456", ran.stdout.split("Skipped")[1])
|
||||
|
||||
def test_names_a_run_it_cannot_score_below_the_table(self):
|
||||
top = self.project("# Comprehension history\n\n## 2026-10-07T12:00:00Z, PR #0 at COMMIT\n\nJunior A, hardest first:\n\n- `README.md:1` \"Install\"\n\n## 2026-10-08T12:50:49Z, PR #1 at COMMIT\n\nJunior A, hardest first:\n\n- `a.py:1` `hard`\n")
|
||||
ran = self.run_tool(top)
|
||||
self.assertIn("Not scored, its places name no measured unit or every one: 2026-10-07T12:00:00Z, PR #0", ran.stdout)
|
||||
|
||||
def test_reads_the_checkout_that_holds_a_history_named_from_elsewhere(self):
|
||||
top = self.project("# Comprehension history\n\n## 2026-10-08T12:50:49Z, PR #1 at COMMIT\n\nJunior A, hardest first:\n\n- `a.py:1` `hard`\n")
|
||||
ran = self.run_tool(tempfile.gettempdir(), str(pathlib.Path(top, "docs", "comprehension-history.md")))
|
||||
self.assertEqual(ran.returncode, 0, ran.stderr)
|
||||
@@ -0,0 +1,6 @@
|
||||
import pathlib
|
||||
|
||||
|
||||
def project_key(checkout_root: str, home: pathlib.Path) -> str:
|
||||
"""The checkout's path relative to ~/code, or to / outside it: what names a project's loop-claude session, its entry in the models file and its archive folder."""
|
||||
return checkout_root.removeprefix(f"{home / 'code'}/").lstrip("/")
|
||||
Executable
+399
@@ -0,0 +1,399 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Score todo.md's items by the formula and goal weights it states, and hold them to its bar.
|
||||
|
||||
usage: rank_todo.py [--check] [todo.md]
|
||||
|
||||
Reads todo.md (default: ./todo.md), the README.md beside it, and docs/decisions.md when there is
|
||||
one. Rewrites each item's Score from the formula and sorts the items by release; within a release,
|
||||
security rows come first, then the rest by score from highest, then by ID. Orders the details to
|
||||
match. --check writes nothing and fails when the file is not ranked as it would be.
|
||||
|
||||
A valid todo.md; ## Details and each item's detail are optional:
|
||||
|
||||
# todo
|
||||
|
||||
## Scoring
|
||||
|
||||
`Score = -R - S/4 + 2*A + 2*G*W`
|
||||
|
||||
`Bar = 9`
|
||||
|
||||
`Next ID = 2`
|
||||
|
||||
| Goal | W |
|
||||
|---|---|
|
||||
| 1 | 1.00 |
|
||||
|
||||
## Items
|
||||
|
||||
| ID | Release | Exempt | Item | R | S | A | G | Goals | Score |
|
||||
|---|---|---|---|---|---|---|---|---|---|
|
||||
| 1 | 0.1.0 | | **Make the first thing work.** | 2 | 3 | 8 | 9 | 1 | 0 |
|
||||
|
||||
## Details
|
||||
|
||||
### 1. Make the first thing work.
|
||||
|
||||
What the tagline cannot say.
|
||||
|
||||
- The formula holds numbers, + - * / and parentheses over R, S, A, G and W.
|
||||
- The bar is judged on the Score as shown, to one decimal.
|
||||
- A new item takes Next ID, and Next ID then goes up by one; every ID stays below it.
|
||||
- The goal weights list README.md's numbered goals in order, a sub-goal such as 1.1 included.
|
||||
- An item's R, S, A and G are whole numbers from 1 to 10; Goals lists goal numbers, comma separated.
|
||||
- An item's Exempt cell is empty, or names why the bar does not apply: decision, defect,
|
||||
principle, question or security. An item docs/decisions.md cites as "`todo.md` item N" must be
|
||||
exempt, and a row marked decision must be cited there.
|
||||
- An item's Item cell is one bold tagline; its detail, if any, sits under its ID in ## Details.
|
||||
|
||||
Exit 1, saying why, on bad arguments, a file that cannot be read or written, a todo.md, README.md or
|
||||
docs/decisions.md that breaks the rules above, an item that is not exempt scoring under the bar, or
|
||||
--check finding the file unranked.
|
||||
"""
|
||||
import ast
|
||||
import dataclasses
|
||||
import math
|
||||
import pathlib
|
||||
import re
|
||||
import sys
|
||||
|
||||
from todo_table import cells, Item, ITEMS_HEADER, parse_row, table_rows
|
||||
from failure import Failure
|
||||
from markdown_text import FENCE, sections
|
||||
from file_writes import replace_file
|
||||
|
||||
LARGEST_FORMULA = 200
|
||||
LONGEST_FORMULA = 4 * LARGEST_FORMULA
|
||||
OPERATORS = (ast.Add, ast.BinOp, ast.Div, ast.Expression, ast.Load, ast.Mult, ast.Sub, ast.UAdd, ast.UnaryOp, ast.USub)
|
||||
VARIABLES = ("A", "G", "R", "S", "W")
|
||||
WEIGHTS_HEADER = "| Goal | W |"
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Scoring:
|
||||
formula: ast.Expression
|
||||
bar: float
|
||||
next_id: int
|
||||
weights: dict[str, float]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Ranked:
|
||||
text: str
|
||||
under_bar: list[str]
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
if argv[:1] in (["-h"], ["--help"]):
|
||||
print(__doc__.strip())
|
||||
return 0
|
||||
args = parse_args(argv)
|
||||
if isinstance(args, Failure):
|
||||
return fail(args)
|
||||
check, todo = args
|
||||
if check:
|
||||
failures = check_failures(todo)
|
||||
for line in failures:
|
||||
print(line, file=sys.stderr)
|
||||
return 1 if failures else 0
|
||||
texts = read_all(todo)
|
||||
if isinstance(texts, Failure):
|
||||
return fail(texts)
|
||||
ranked = rank(*texts)
|
||||
if isinstance(ranked, Failure):
|
||||
return fail(ranked)
|
||||
if ranked.text != texts[0]:
|
||||
unwritten = write(todo, ranked.text)
|
||||
if unwritten:
|
||||
return fail(unwritten)
|
||||
for line in ranked.under_bar:
|
||||
print(f"{todo}: {line}", file=sys.stderr)
|
||||
return 1 if ranked.under_bar else 0
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
def parse_args(argv: list[str]) -> tuple[bool, pathlib.Path] | Failure:
|
||||
paths = [arg for arg in argv if arg != "--check"]
|
||||
if len(paths) > 1 or any(path.startswith("-") for path in paths):
|
||||
return Failure(f"rank_todo.py: cannot read the arguments {' '.join(argv)}; usage: rank_todo.py [--check] [todo.md]")
|
||||
return "--check" in argv, pathlib.Path(paths[0] if paths else "todo.md")
|
||||
|
||||
|
||||
def read_all(todo: pathlib.Path) -> tuple[str, str, str] | Failure:
|
||||
"""todo.md, the README.md beside it, and its docs/decisions.md, 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)):
|
||||
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]
|
||||
|
||||
|
||||
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) -> Ranked | Failure:
|
||||
lines = text.split("\n")
|
||||
scoring = read_scoring(text, lines, readme)
|
||||
if isinstance(scoring, Failure):
|
||||
return scoring
|
||||
table = read_items(lines, scoring)
|
||||
if isinstance(table, Failure):
|
||||
return table
|
||||
items, start = table
|
||||
if uncited := check_citations(items, decisions):
|
||||
return uncited
|
||||
scored = []
|
||||
for item in items:
|
||||
value = score(scoring.formula, item, scoring.weights)
|
||||
if isinstance(value, Failure):
|
||||
return value
|
||||
scored.append((item, value))
|
||||
scored.sort(key=lambda pair: (pair[0].release, pair[0].exempt != "security", -pair[1], pair[0].id))
|
||||
lines[start:start + len(scored)] = [render_item(item, value) for item, value in scored]
|
||||
ranked = rank_details("\n".join(lines), [item for item, _ in scored])
|
||||
if isinstance(ranked, Failure):
|
||||
return ranked
|
||||
under_bar = [f"item {item.id} scores {value:.1f}, under the bar {scoring.bar:g}; delete it and any item that needs it, or mark it with a reason the bar does not apply" for item, value in scored if not item.exempt and round(value, 1) < scoring.bar]
|
||||
return Ranked(ranked, under_bar)
|
||||
|
||||
|
||||
def read_scoring(text: str, lines: list[str], readme: str) -> Scoring | Failure:
|
||||
if ITEMS_HEADER not in lines and "## Items" not in lines:
|
||||
return Failure("todo.md is not in the scored-table format; rank_todo.py --help shows a valid one")
|
||||
goals = readme_goals(readme)
|
||||
if isinstance(goals, Failure):
|
||||
return goals
|
||||
formula = parse_formula(stated(text, "Score"))
|
||||
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 = parse_weights(lines, goals)
|
||||
if isinstance(weights, Failure):
|
||||
return weights
|
||||
return Scoring(formula, bar, int(next_id), weights)
|
||||
|
||||
|
||||
def read_items(lines: list[str], scoring: Scoring) -> tuple[list[Item], int] | Failure:
|
||||
"""The items, and the index of the first row in lines."""
|
||||
table = table_rows(lines, ITEMS_HEADER)
|
||||
if isinstance(table, Failure):
|
||||
return table
|
||||
if stray_row(lines[table.start + len(table.rows):]):
|
||||
return Failure("## Items holds a row outside its table; keep the rows together under the header")
|
||||
items = []
|
||||
for row in table.rows:
|
||||
item = parse_item(row, scoring.weights)
|
||||
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")
|
||||
return items, table.start
|
||||
|
||||
|
||||
def stray_row(after: list[str]) -> bool:
|
||||
"""Whether a table row follows the table before the next ## heading."""
|
||||
section = after[:next((index for index, line in enumerate(after) if line.startswith("## ")), len(after))]
|
||||
return any(line.startswith("|") for line in section)
|
||||
|
||||
|
||||
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[str] | Failure:
|
||||
"""The numbers of README.md's goals in reading order, a sub-goal as 4.1."""
|
||||
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[str] = []
|
||||
path: list[tuple[int, str]] = []
|
||||
for indent, position in re.findall(r"^([ \t]*)(\d+)\. ", 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))
|
||||
if not goals:
|
||||
return Failure("README.md's ## Goals has no numbered goal")
|
||||
if len(set(goals)) < len(goals):
|
||||
return Failure(f"README.md's ## Goals numbers {', '.join(goals)}; number each goal by its position")
|
||||
return goals
|
||||
|
||||
|
||||
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) -> 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 gives 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
|
||||
return math.nan
|
||||
|
||||
|
||||
def score(formula: ast.Expression, item: Item, weights: dict[str, float]) -> float | Failure:
|
||||
# An item serving several goals is weighed by the heaviest; summing them would reward citing more.
|
||||
value = evaluate(formula, {**item.scores, "W": max(weights[goal] for goal in item.goals)})
|
||||
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, weights: dict[str, float]) -> Item | Failure:
|
||||
item = parse_row(row)
|
||||
if isinstance(item, Failure):
|
||||
return item
|
||||
if unknown := [goal for goal in item.goals if goal not in weights]:
|
||||
return Failure(f"item {item.id} cites goal {', '.join(unknown)}, which the goal weights do not list")
|
||||
return item
|
||||
|
||||
|
||||
def render_item(item: Item, value: float) -> str:
|
||||
release = ".".join(str(part) for part in item.release)
|
||||
scores = " | ".join(str(item.scores[name]) for name in "RSAG")
|
||||
return f"| {item.id} | {release} | {item.exempt} | {item.tagline} | {scores} | {', '.join(item.goals)} | {value:.1f} |"
|
||||
|
||||
|
||||
def rank_details(text: str, items: list[Item]) -> str | Failure:
|
||||
section = re.search(r"^## Details\n(.*?)(?=^## |\Z)", text, re.M | re.S)
|
||||
if section is None:
|
||||
return text
|
||||
body = section.group(1)
|
||||
# A fenced line such as "## Goals" or "### 2. x" would read as a heading and split a detail.
|
||||
if FENCE.search(body):
|
||||
return Failure("## Details holds a fenced code block; indent quoted markdown by four spaces instead")
|
||||
parts = re.split(r"^### (\d+)\. [^\n]*\n", body, flags=re.M)
|
||||
if parts[0].strip():
|
||||
return Failure("## Details holds text before its first ### <ID>. heading")
|
||||
details: dict[int, str] = {}
|
||||
for id_, detail in zip(parts[1::2], parts[2::2]):
|
||||
if int(id_) in details:
|
||||
return Failure(f"## Details holds item {id_} twice")
|
||||
details[int(id_)] = detail.strip("\n")
|
||||
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:]))
|
||||
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 reading_cost import main
|
||||
|
||||
sys.exit(main.main(sys.argv[1:]))
|
||||
@@ -0,0 +1,72 @@
|
||||
import collections
|
||||
import re
|
||||
import statistics
|
||||
|
||||
from failure import Failure
|
||||
from transcript_archive.read import FinishedChunk
|
||||
from reading_cost.measure import Reading
|
||||
from markdown_text import sections
|
||||
from utc_stamp import STAMPED
|
||||
|
||||
FIGURE = re.compile(rf"^Reading cost, chunk (\w+), finished ({STAMPED})$")
|
||||
FIGURE_PLACE = re.compile(r"^- `(.+)` (\d+)$")
|
||||
PLACES_KEPT = 10
|
||||
RESET = "Reading cost reset, "
|
||||
RESET_AT = re.compile(rf"^{RESET}({STAMPED})$")
|
||||
TOKENS = re.compile(r"^(\d+) new input tokens before the first commit\.$")
|
||||
WINDOW = 5
|
||||
|
||||
|
||||
def unheld(chunks: list[FinishedChunk], record: str) -> list[FinishedChunk]:
|
||||
held = {match.group(1) for heading in sections(record) if (match := FIGURE.match(heading))}
|
||||
return [chunk for chunk in chunks if chunk_id(chunk) not in held]
|
||||
|
||||
|
||||
def chunk_id(chunk: FinishedChunk) -> str:
|
||||
return chunk.folder[:12]
|
||||
|
||||
|
||||
def figure(chunk: FinishedChunk, reading: Reading) -> str:
|
||||
places = "".join(f"- `{path}` {times}\n" for path, times in ranked(reading.places))
|
||||
return f"## Reading cost, chunk {chunk_id(chunk)}, finished {chunk.finished}\n\n{reading.tokens} new input tokens before the first commit.\n" + (f"\nRead most (opens and searches):\n\n{places}" if places else "")
|
||||
|
||||
|
||||
# The figures after the last reset, in the order their chunks finished: each machine appends its own archive's chunks.
|
||||
def readings_of(record: str) -> list[Reading] | Failure:
|
||||
dated = []
|
||||
resets = [""]
|
||||
for heading, bodies in sections(record).items():
|
||||
if reset := RESET_AT.match(heading):
|
||||
resets.append(reset.group(1))
|
||||
elif named := FIGURE.match(heading):
|
||||
lines = bodies[0].splitlines() if bodies else []
|
||||
tokens = [int(match.group(1)) for line in lines if (match := TOKENS.match(line))]
|
||||
if len(tokens) != 1:
|
||||
return Failure(f"the figure under \"## {heading}\" holds no single tokens line; restore it from git history")
|
||||
dated.append((named.group(2), heading, Reading(tokens[0], collections.Counter({match.group(1): int(match.group(2)) for line in lines if (match := FIGURE_PLACE.match(line))}))))
|
||||
elif heading.startswith("Reading cost"):
|
||||
return Failure(f"\"## {heading}\" names no chunk and UTC time, or no reset time; restore it from git history")
|
||||
return [reading for finished, _, reading in sorted(dated, key=lambda item: item[:2]) if finished > max(resets)]
|
||||
|
||||
|
||||
def ranked(places: collections.Counter[str]) -> list[tuple[str, int]]:
|
||||
return sorted(places.items(), key=lambda item: (-item[1], item[0]))[:PLACES_KEPT]
|
||||
|
||||
|
||||
def merged(record: str, figures: list[str]) -> str:
|
||||
return record.rstrip("\n") + "\n\n" + "\n".join(figures)
|
||||
|
||||
|
||||
def trend(readings: list[Reading]) -> str:
|
||||
if len(readings) < 2 * WINDOW:
|
||||
return f"{len(readings)} chunks measured since the last reset; the trend needs {2 * WINDOW}."
|
||||
last, earlier = median_tokens(readings[-WINDOW:]), median_tokens(readings[-2 * WINDOW:-WINDOW])
|
||||
medians = f"the last {WINDOW} chunks' median is {last} new input tokens before their first commit, the {WINDOW} before them {earlier}."
|
||||
if last <= earlier:
|
||||
return f"Not rising: {medians}"
|
||||
read_most = "".join(f"\n- `{path}` {times}" for path, times in ranked(sum((reading.places for reading in readings[-WINDOW:]), collections.Counter())))
|
||||
return f"Rising: {medians}\n\nRead most over the last {WINDOW} (opens and searches):\n{read_most}"
|
||||
|
||||
|
||||
def median_tokens(readings: list[Reading]) -> int:
|
||||
return round(statistics.median(reading.tokens for reading in readings))
|
||||
@@ -0,0 +1,133 @@
|
||||
"""Measure each chunk loop-claude finished, append the figures to a project's record, and say whether they rise.
|
||||
|
||||
usage: reading-cost [--reset] [record]
|
||||
|
||||
Run it inside a project checkout or one of its worktrees. record defaults to docs/reading-cost.md
|
||||
there, created when missing. It reads loop-claude's archive of the project,
|
||||
$LOOP_CLAUDE_TRANSCRIPTS/<key> (default ~/.claude/loop-claude-transcripts), <key> being the
|
||||
checkout's path relative to ~/code, or to / outside it. For each finished chunk the record does not
|
||||
yet hold, it measures what the worker and its subagents read before the worker's first commit: their
|
||||
new input tokens (uncached and cache-written; cache reads excluded), and how often they opened or
|
||||
searched each file git tracks in the checkout. A chunk whose worker never committed is not measured.
|
||||
Each figure is appended under a "## Reading cost, chunk <id>, finished <UTC time>" heading, in the
|
||||
order the chunks finished.
|
||||
|
||||
--reset also appends a "## Reading cost reset, <UTC time>" heading: the trend then counts only
|
||||
figures of chunks that finished after it.
|
||||
|
||||
It then compares the median tokens of the record's last 5 figures with the 5 before them, in the
|
||||
order their chunks finished, and prints "Rising:" or "Not rising:" with both medians. Rising, it
|
||||
lists the files the last 5 chunks read most. With fewer than 10 figures, it says so.
|
||||
|
||||
Exit 1, saying why, on unknown arguments, or when git cannot start or finds no checkout, the
|
||||
archive or the record cannot be read or written, or a figure in the record cannot be read back.
|
||||
"""
|
||||
import dataclasses
|
||||
import os
|
||||
import pathlib
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
from reading_cost.measure import Checkout, measure, Reading
|
||||
from failure import Failure
|
||||
from reading_cost.figures import figure, merged, readings_of, RESET, trend, unheld
|
||||
from transcript_archive.read import finished_chunks, read_threads
|
||||
from transcript_archive.location import project_archive
|
||||
from file_writes import replace_file
|
||||
from utc_stamp import utc
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Updated:
|
||||
appended: int
|
||||
readings: list[Reading]
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
reset = argv[:1] == ["--reset"]
|
||||
given = argv[1:] if reset else argv
|
||||
if given in (["-h"], ["--help"]):
|
||||
print(__doc__.strip())
|
||||
return 0
|
||||
if len(given) > 1 or given[:1] and given[0].startswith("-"):
|
||||
print(f"unknown arguments {' '.join(given)}; usage: reading-cost [--reset] [record]", file=sys.stderr)
|
||||
return 1
|
||||
checkout = located()
|
||||
if isinstance(checkout, Failure):
|
||||
return failed(checkout)
|
||||
home = pathlib.Path.home()
|
||||
archive = project_archive(checkout.main_root, home, os.environ)
|
||||
record = pathlib.Path(given[0]) if given else pathlib.Path(checkout.current_root, "docs", "reading-cost.md")
|
||||
updated = update(record, archive, checkout, str(home), utc(time.time()) if reset else None)
|
||||
if isinstance(updated, Failure):
|
||||
return failed(updated)
|
||||
print(f"Appended {updated.appended} reading-cost figure{'' if updated.appended == 1 else 's'} from {archive}{' and a reset' if reset else ''} to {record}.")
|
||||
print(trend(updated.readings))
|
||||
return 0
|
||||
|
||||
|
||||
def update(record: pathlib.Path, archive: pathlib.Path, checkout: Checkout, home: str, reset_at: str | None) -> Updated | Failure:
|
||||
text = read_record(record)
|
||||
if isinstance(text, Failure):
|
||||
return text
|
||||
figures = new_figures(text, archive, checkout, home)
|
||||
if isinstance(figures, Failure):
|
||||
return figures
|
||||
marks = [*figures, f"## {RESET}{reset_at}\n"] if reset_at else figures
|
||||
text = merged(text, marks) if marks else text
|
||||
readings = readings_of(text)
|
||||
if isinstance(readings, Failure):
|
||||
return readings
|
||||
if marks and (unwritten := write_record(record, text)):
|
||||
return unwritten
|
||||
return Updated(len(figures), readings)
|
||||
|
||||
|
||||
def new_figures(record: str, archive: pathlib.Path, checkout: Checkout, home: str) -> list[str] | Failure:
|
||||
chunks = finished_chunks(archive)
|
||||
if isinstance(chunks, Failure):
|
||||
return chunks
|
||||
figures = []
|
||||
for chunk in unheld(chunks, record):
|
||||
threads = read_threads(chunk)
|
||||
if isinstance(threads, Failure):
|
||||
return threads
|
||||
if reading := measure(threads, checkout, home):
|
||||
figures.append(figure(chunk, reading))
|
||||
return figures
|
||||
|
||||
|
||||
def write_record(record: pathlib.Path, text: str) -> Failure | None:
|
||||
try:
|
||||
record.parent.mkdir(parents=True, exist_ok=True)
|
||||
except OSError as failure:
|
||||
return Failure(f"could not write {record}: {failure.strerror}")
|
||||
unwritten = replace_file(record, text.encode())
|
||||
return Failure(f"could not write {record}: {unwritten.reason}") if unwritten else None
|
||||
|
||||
|
||||
def failed(failure: Failure) -> int:
|
||||
print(failure.reason, file=sys.stderr)
|
||||
return 1
|
||||
|
||||
|
||||
def located() -> Checkout | Failure:
|
||||
try:
|
||||
found = subprocess.run(["git", "rev-parse", "--path-format=absolute", "--show-toplevel", "--git-common-dir"], capture_output=True, text=True)
|
||||
if found.returncode != 0:
|
||||
return Failure(found.stderr.strip())
|
||||
top, common = found.stdout.splitlines()
|
||||
listed = subprocess.run(["git", "ls-files", "-z"], capture_output=True, cwd=top, text=True)
|
||||
except (OSError, ValueError) as failure:
|
||||
return Failure(f"could not find the checkout: {failure}")
|
||||
if listed.returncode != 0:
|
||||
return Failure(listed.stderr.strip())
|
||||
# The common dir is the main checkout's .git, whichever worktree runs this.
|
||||
return Checkout(top, str(pathlib.Path(common).parent), frozenset(filter(None, listed.stdout.split("\0"))))
|
||||
|
||||
|
||||
def read_record(record: pathlib.Path) -> str | Failure:
|
||||
try:
|
||||
return record.read_text(encoding="utf-8") if record.exists() else "# Reading cost\n"
|
||||
except (OSError, UnicodeDecodeError) as failure:
|
||||
return Failure(f"could not read {record}: {failure}")
|
||||
@@ -0,0 +1,80 @@
|
||||
import collections
|
||||
import dataclasses
|
||||
|
||||
from claude_code.entries import assistant_parts, parse_entry, tool_call
|
||||
from git_command import commits
|
||||
from reading_cost.shell_reads import Reads, shell_reads
|
||||
from shell_command import resolved, simple_commands
|
||||
|
||||
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Reading:
|
||||
"""What the worker and its subagents took in before the worker's first commit."""
|
||||
tokens: int
|
||||
places: collections.Counter[str]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Checkout:
|
||||
"""main_root is the main checkout, whose path keys the archive; current_root is the checkout or worktree this runs in."""
|
||||
current_root: str
|
||||
main_root: str
|
||||
tracked: frozenset[str]
|
||||
|
||||
|
||||
def measure(threads: list[bytes], checkout: Checkout, home: str) -> Reading | None:
|
||||
worker, *subagents = [entries_of(thread) for thread in threads]
|
||||
commit = commit_time(worker, home)
|
||||
if commit is None:
|
||||
return None
|
||||
before = [[entry for entry in thread if entry.get("type") == "assistant" and str(entry.get("timestamp", "")) < commit] for thread in (worker, *subagents)]
|
||||
reads = [reads_of(part, str(entry.get("cwd") or "/"), home) for thread in before for entry in thread for part in assistant_parts(entry)]
|
||||
roots = [checkout.main_root, *(added for found in reads for added in found.added)]
|
||||
places = collections.Counter(place for found in reads for path in found.read if (place := relative(path, roots)) in checkout.tracked)
|
||||
return Reading(sum(map(tokens_in, before)), places)
|
||||
|
||||
|
||||
def entries_of(raw: bytes) -> list[dict]:
|
||||
return [entry for line in raw.splitlines() if (entry := parse_entry(line))]
|
||||
|
||||
|
||||
def commit_time(worker: list[dict], home: str) -> str | None:
|
||||
for entry in worker:
|
||||
for part in assistant_parts(entry):
|
||||
name, arguments = call_of(part)
|
||||
if name == "Bash" and commits(simple_commands(str(arguments.get("command", "")), str(entry.get("cwd") or "/"), home), home):
|
||||
return str(entry.get("timestamp", ""))
|
||||
return None
|
||||
|
||||
|
||||
def tokens_in(entries: list[dict]) -> int:
|
||||
# Claude Code writes one entry per content block of a message, each with the message's usage.
|
||||
usages = {str(message.get("id") or entry.get("uuid")): message.get("usage") for entry in entries if isinstance(message := entry.get("message"), dict)}
|
||||
return sum(count(usage, "input_tokens") + count(usage, "cache_creation_input_tokens") for usage in usages.values() if isinstance(usage, dict))
|
||||
|
||||
|
||||
# A count Claude Code left out or wrote as another type adds nothing, so one odd entry leaves the rest of the figure standing.
|
||||
def count(usage: dict, field: str) -> int:
|
||||
value = usage.get(field)
|
||||
return value if isinstance(value, int) else 0
|
||||
|
||||
|
||||
def call_of(part: object) -> tuple[object, dict]:
|
||||
call = tool_call(part)
|
||||
return (call[0], call[1]) if call and isinstance(call[1], dict) else (None, {})
|
||||
|
||||
|
||||
def reads_of(part: object, cwd: str, home: str) -> Reads:
|
||||
name, arguments = call_of(part)
|
||||
path = arguments.get("file_path") if name == "Read" else arguments.get("path") if name == "Grep" else None
|
||||
if path:
|
||||
return Reads([resolved(cwd, str(path), home)], [])
|
||||
return shell_reads(str(arguments.get("command", "")), cwd, home) if name == "Bash" else Reads([], [])
|
||||
|
||||
|
||||
# Relative to the deepest root holding it, so the checkout and each worktree name a file alike.
|
||||
def relative(path: str, roots: list[str]) -> str | None:
|
||||
holding = [root for root in roots if path.startswith(root.rstrip("/") + "/")]
|
||||
return path[len(max(holding, key=len).rstrip("/")) + 1:] if holding else None
|
||||
@@ -0,0 +1,50 @@
|
||||
"""The files a shell command reads, and the worktrees it adds, as absolute paths."""
|
||||
import dataclasses
|
||||
import posixpath
|
||||
import re
|
||||
|
||||
from shell_command import resolved, simple_commands
|
||||
|
||||
NOT_A_PATH = re.compile(r"[*?\[\]{}$\\'\",=()<>|;&]|://|^\d+$")
|
||||
# Their first operand is a pattern or a program, unless -e or -f gives it.
|
||||
PATTERN_FIRST = {"awk", "egrep", "grep", "rg", "sed"}
|
||||
READERS = {"awk", "bat", "cat", "egrep", "grep", "head", "less", "more", "nl", "rg", "sed", "tail", "wc"}
|
||||
WORKTREE_OPTIONS_WITH_VALUE = {"-b", "-B", "--reason"}
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Reads:
|
||||
read: list[str]
|
||||
added: list[str]
|
||||
|
||||
|
||||
def shell_reads(command: str, cwd: str, home: str) -> Reads:
|
||||
read: list[str] = []
|
||||
added: list[str] = []
|
||||
for simple in simple_commands(command, cwd, home):
|
||||
read += [resolved(simple.directory, word, home) for word in operands(simple.words)]
|
||||
added += [resolved(simple.directory, path, home) for path in worktree_added(simple.words)]
|
||||
return Reads(read, added)
|
||||
|
||||
|
||||
def operands(words: list[str]) -> list[str]:
|
||||
program = posixpath.basename(words[0])
|
||||
if program not in READERS or (program == "sed" and any(word.startswith("-i") for word in words)):
|
||||
return []
|
||||
given = [word for word in words[1:] if not word.startswith("-")]
|
||||
if program in PATTERN_FIRST and not {"-e", "-f"} & set(words):
|
||||
given = given[1:]
|
||||
return [word for word in given if ("/" in word or re.search(r"\.[A-Za-z0-9]+$", word)) and not NOT_A_PATH.search(word)]
|
||||
|
||||
|
||||
# git worktree add [-b <branch>] <path> [<commit>]
|
||||
def worktree_added(words: list[str]) -> list[str]:
|
||||
if words[:1] != ["git"] or "worktree" not in words or words[words.index("worktree") + 1:][:1] != ["add"]:
|
||||
return []
|
||||
after = iter(words[words.index("worktree") + 2:])
|
||||
for word in after:
|
||||
if word in WORKTREE_OPTIONS_WITH_VALUE:
|
||||
next(after, None)
|
||||
elif not word.startswith("-"):
|
||||
return [word]
|
||||
return []
|
||||
@@ -0,0 +1,164 @@
|
||||
import collections
|
||||
import contextlib
|
||||
import hashlib
|
||||
import io
|
||||
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 transcript_archive.write import archive
|
||||
from reading_cost.measure import Checkout, Reading
|
||||
from failure import Failure
|
||||
from reading_cost import figures, measure
|
||||
from transcript_archive.read import finished_chunks, FinishedChunk
|
||||
from test_env import isolated_env
|
||||
from transcript_archive import outcomes
|
||||
from transcript_archive.location import project_archive
|
||||
from reading_cost.shell_reads import Reads, shell_reads
|
||||
|
||||
TOOL = pathlib.Path(__file__).resolve().parents[1] / "reading-cost"
|
||||
|
||||
|
||||
def said(timestamp, message_id, command=None, tokens=0, cwd="/c/p", **call):
|
||||
part = {"type": "tool_use", "name": "Bash", "input": {"command": command}} if command else {"type": "tool_use", **call}
|
||||
return {"type": "assistant", "timestamp": timestamp, "cwd": cwd, "message": {"id": message_id, "content": [part], "usage": {"input_tokens": tokens, "cache_creation_input_tokens": 2 * tokens, "cache_read_input_tokens": 1000}}}
|
||||
|
||||
|
||||
def jsonl(entries):
|
||||
return b"".join(json.dumps(entry).encode() + b"\n" for entry in entries)
|
||||
|
||||
|
||||
def folder_name():
|
||||
return hashlib.sha256(os.urandom(8)).hexdigest()
|
||||
|
||||
|
||||
class ShellReads(unittest.TestCase):
|
||||
def test_reads_operands_past_a_cd_and_skips_patterns_redirect_targets_and_heredoc_bodies(self):
|
||||
command = "cd ../w && sed -n 1,5p src/a.py | grep -n x\ngrep -rn 'def x' bin/t.py > out.txt\npython3 - <<'EOF'\ncat secret.py\nEOF\ncat ~/README.md\nsed -i s/a/b/ c.py"
|
||||
self.assertEqual(shell_reads(command, "/c/p", "/h"), Reads(["/c/w/src/a.py", "/c/w/bin/t.py", "/h/README.md"], []))
|
||||
|
||||
def test_ends_a_dashed_heredoc_at_its_marker(self):
|
||||
self.assertEqual(shell_reads("cat <<-EOF > x.md\ncat secret.py\nEOF\ncat a.py", "/c/p", "/h"), Reads(["/c/p/a.py"], []))
|
||||
|
||||
def test_names_the_worktree_a_git_worktree_add_makes(self):
|
||||
self.assertEqual(shell_reads("git worktree add -q -b topic ../p-topic origin/main", "/c/p", "/h"), Reads([], ["/c/p-topic"]))
|
||||
|
||||
|
||||
class Measure(unittest.TestCase):
|
||||
def test_counts_each_message_once_and_the_tracked_files_read_before_the_first_commit(self):
|
||||
worker = [
|
||||
said("1", "m1", tokens=10, name="Read", input={"file_path": "/c/p/README.md"}),
|
||||
said("2", "m1", tokens=10, name="Read", input={"file_path": "/c/p/.env"}),
|
||||
said("3", "m2", command="git worktree add ../w && cd ../w && cat src/a.py && cd src && cat b.py"),
|
||||
said("4", "m3", command="cd /tmp && cat x.py"),
|
||||
said("5", "m4", command="git -C ../w commit -m 'x'", tokens=100),
|
||||
said("6", "m5", tokens=100, name="Read", input={"file_path": "/c/p/late.py"}),
|
||||
]
|
||||
subagent = [said("2", "s1", tokens=1, name="Grep", input={"path": "/c/w/src/a.py"}), said("7", "s2", tokens=100, name="Read", input={"file_path": "/c/p/late.py"})]
|
||||
checkout = Checkout("/c/w", "/c/p", frozenset({"README.md", "late.py", "src/a.py", "src/b.py", "x.py"}))
|
||||
self.assertEqual(measure.measure([jsonl(worker), jsonl(subagent)], checkout, "/h"), Reading(33, collections.Counter({"src/a.py": 2, "README.md": 1, "src/b.py": 1})))
|
||||
|
||||
def test_measures_nothing_for_a_worker_that_never_committed(self):
|
||||
self.assertIsNone(measure.measure([jsonl([said("1", "m1", command="git log --grep commit")])], Checkout("/c/p", "/c/p", frozenset()), "/h"))
|
||||
self.assertIsNone(measure.measure([jsonl([said("1", "m1", command="echo git commit")])], Checkout("/c/p", "/c/p", frozenset()), "/h"))
|
||||
|
||||
def test_finds_a_commit_behind_git_options(self):
|
||||
self.assertIsNotNone(measure.measure([jsonl([said("1", "m1", command="git -c user.name=t commit -m x")])], Checkout("/c/p", "/c/p", frozenset()), "/h"))
|
||||
|
||||
def test_skips_a_usage_that_is_not_a_count(self):
|
||||
self.assertEqual(measure.tokens_in([{"message": {"id": "m", "usage": {"input_tokens": "7", "cache_creation_input_tokens": 2}}}]), 2)
|
||||
|
||||
|
||||
class Figures(unittest.TestCase):
|
||||
def test_rises_only_above_the_five_before_and_needs_ten(self):
|
||||
flat = [Reading(100, collections.Counter({"a.py": 1}))] * 10
|
||||
self.assertEqual(figures.trend(flat[:9]), "9 chunks measured since the last reset; the trend needs 10.")
|
||||
self.assertTrue(figures.trend(flat).startswith("Not rising: the last 5 chunks' median is 100 new input tokens"))
|
||||
self.assertTrue(figures.trend(flat[:9] + [Reading(3000000, collections.Counter())]).startswith("Not rising:"))
|
||||
self.assertEqual(figures.trend(flat[:5] + [Reading(101, collections.Counter({"b.py": 2}))] * 5), "Rising: the last 5 chunks' median is 101 new input tokens before their first commit, the 5 before them 100.\n\nRead most over the last 5 (opens and searches):\n\n- `b.py` 10")
|
||||
|
||||
def test_a_figure_reads_back_as_the_reading_it_was_written_from_and_a_damaged_one_fails(self):
|
||||
reading = Reading(7, collections.Counter({"b.py": 1, "a.py": 3}))
|
||||
written = figures.figure(FinishedChunk("abcdef0123456789", "2026-10-08T00:00:00Z", pathlib.Path(), []), reading)
|
||||
self.assertEqual(written, "## Reading cost, chunk abcdef012345, finished 2026-10-08T00:00:00Z\n\n7 new input tokens before the first commit.\n\nRead most (opens and searches):\n\n- `a.py` 3\n- `b.py` 1\n")
|
||||
self.assertEqual(figures.readings_of(written), [reading])
|
||||
self.assertEqual(figures.readings_of(written.replace("7 new", "seven new")), Failure('the figure under "## Reading cost, chunk abcdef012345, finished 2026-10-08T00:00:00Z" holds no single tokens line; restore it from git history'))
|
||||
for damaged in (written.replace(", finished", ""), "## Reading cost reset, x\n"):
|
||||
with self.subTest(damaged=damaged):
|
||||
self.assertIsInstance(figures.readings_of(damaged), Failure)
|
||||
|
||||
|
||||
def test_counts_only_figures_finished_after_the_last_reset_in_the_order_they_finished(self):
|
||||
def written(chunk, finished, tokens):
|
||||
return figures.figure(FinishedChunk(chunk, finished, pathlib.Path(), []), Reading(tokens, collections.Counter()))
|
||||
history = "\n".join([written("a", "2026-10-01T00:00:00Z", 1), written("c", "2026-10-03T00:00:00Z", 3), "## Reading cost reset, 2026-10-02T00:00:00Z\n", written("b", "2026-10-04T00:00:00Z", 2)])
|
||||
self.assertEqual(figures.readings_of(history), [Reading(3, collections.Counter()), Reading(2, collections.Counter())])
|
||||
|
||||
|
||||
class ReadingCostTool(unittest.TestCase):
|
||||
def setUp(self):
|
||||
temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(temp.cleanup)
|
||||
self.home = pathlib.Path(os.path.realpath(temp.name))
|
||||
self.env = {**isolated_env(), "GIT_CONFIG_GLOBAL": os.devnull, "HOME": str(self.home)}
|
||||
self.checkout = self.home / "code" / "proj"
|
||||
self.checkout.mkdir(parents=True)
|
||||
(self.checkout / "a.py").write_text("")
|
||||
self.git("init", "-q")
|
||||
self.git("add", "a.py")
|
||||
self.git("-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "-m", "x")
|
||||
self.archive = project_archive(str(self.checkout), self.home, {})
|
||||
|
||||
def git(self, *args):
|
||||
subprocess.run(["git", *args], cwd=self.checkout, check=True, env=self.env)
|
||||
|
||||
def archive_chunk(self, at, outcome=outcomes.finished):
|
||||
transcript = self.home / ".claude" / "projects" / "-proj" / f"{folder_name()}.jsonl"
|
||||
(transcript.with_suffix("") / "subagents").mkdir(parents=True)
|
||||
worker = [said("1", "m1", tokens=10, cwd=str(self.checkout), name="Read", input={"file_path": str(self.checkout / "a.py")}), said("2", "m2", command="git commit -m x")]
|
||||
transcript.write_bytes(jsonl([{"timestamp": str(at)}, *worker]))
|
||||
(transcript.with_suffix("") / "subagents" / "agent-a.jsonl").write_bytes(jsonl([said("1", "s1", tokens=1)]))
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
self.assertIsNone(archive(self.archive, str(transcript), "Do it.", outcome("merged"), at))
|
||||
|
||||
def run_tool(self, cwd, *args):
|
||||
return subprocess.run([sys.executable, str(TOOL), *args], capture_output=True, cwd=cwd, env=self.env, text=True)
|
||||
|
||||
def test_appends_each_finished_chunk_once_in_the_order_they_finished_from_a_worktree(self):
|
||||
self.archive_chunk(1790000200)
|
||||
self.archive_chunk(1790000100)
|
||||
self.archive_chunk(1790000000, outcomes.unfinished)
|
||||
chunks = finished_chunks(self.archive)
|
||||
self.assertEqual([chunk.finished for chunk in chunks], ["2026-09-21T14:15:00Z", "2026-09-21T14:16:40Z"])
|
||||
worktree = self.home / "code" / "proj-wt"
|
||||
self.git("worktree", "add", "-q", str(worktree))
|
||||
ran = self.run_tool(worktree)
|
||||
self.assertEqual(ran.returncode, 0, ran.stderr)
|
||||
history = worktree / "docs" / "reading-cost.md"
|
||||
self.assertEqual(ran.stdout, f"Appended 2 reading-cost figures from {self.home / '.claude' / 'loop-claude-transcripts' / 'proj'} to {history}.\n2 chunks measured since the last reset; the trend needs 10.\n")
|
||||
figure = "## Reading cost, chunk {}, finished {}\n\n33 new input tokens before the first commit.\n\nRead most (opens and searches):\n\n- `a.py` 1\n"
|
||||
self.assertEqual(history.read_text(), "# Reading cost\n\n" + "\n".join(figure.format(chunk.folder[:12], chunk.finished) for chunk in chunks))
|
||||
self.assertTrue(self.run_tool(worktree).stdout.startswith(f"Appended 0 reading-cost figures from"))
|
||||
self.assertEqual(history.read_text().count("## Reading cost"), 2)
|
||||
reset = self.run_tool(worktree, "--reset")
|
||||
self.assertEqual(reset.stdout, f"Appended 0 reading-cost figures from {self.home / '.claude' / 'loop-claude-transcripts' / 'proj'} and a reset to {history}.\n0 chunks measured since the last reset; the trend needs 10.\n")
|
||||
self.assertRegex(history.read_text(), r"\n## Reading cost reset, \d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ\n$")
|
||||
|
||||
def test_refuses_an_option_it_does_not_know(self):
|
||||
ran = self.run_tool(self.checkout, "--rest")
|
||||
self.assertEqual((ran.returncode, ran.stdout), (1, ""))
|
||||
|
||||
def test_exits_1_outside_a_checkout(self):
|
||||
ran = self.run_tool(self.home)
|
||||
self.assertEqual(ran.returncode, 1)
|
||||
self.assertIn("not a git repository", ran.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,48 @@
|
||||
import pathlib
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from loop_claude.project.records import HUMAN_RULE_DIRS
|
||||
from repo_checks.test_python_floor import ROOT
|
||||
|
||||
RULE_PATH = rf"(?:{'|'.join(map(re.escape, HUMAN_RULE_DIRS))})/[\w-]+\.md"
|
||||
CITATION = re.compile(rf'`?(?:~/\.claude/)?(CLAUDE\.md|{RULE_PATH})`? → ("[^"]+"(?:,? (?:and )?"[^"]+")*)')
|
||||
HEADING = re.compile(r"^#+ (.+?)(?: \(.*\))?$", re.MULTILINE)
|
||||
LEAD = re.compile(r"^(?:- )?\*\*(.+?)(?:\*\*|[:.](?=\*\*| )| —)", re.MULTILINE)
|
||||
NAME = re.compile(r'"([^"]+)"')
|
||||
RULE_FILE = re.compile(rf"(?<![\w/.-])(?:~/\.claude/)?({RULE_PATH})")
|
||||
STRAY = re.compile(rf'(?:CLAUDE\.md|{RULE_PATH})(?!`? → "|:\d)[^\n"]{{1,5}}"')
|
||||
|
||||
|
||||
class Citations(unittest.TestCase):
|
||||
def test_every_citation_names_a_heading_then_headings_or_bold_leads_of_the_file_it_cites(self):
|
||||
tracked = subprocess.run(["git", "ls-files", "-z"], capture_output=True, check=True, cwd=ROOT, text=True).stdout.split("\0")
|
||||
texts = [(path, (ROOT / path).read_text()) for path in filter(None, tracked)]
|
||||
self.assertEqual([f"{path}: {stray}" for path, text in texts for stray in STRAY.findall(text)], [], 'spell a citation `CLAUDE.md` → "Vocabulary"')
|
||||
cited = [(path, file, NAME.findall(run)) for path, text in texts for file, run in CITATION.findall(text)]
|
||||
self.assertTrue(cited)
|
||||
unresolved = []
|
||||
for path, file, names in cited:
|
||||
if not (ROOT / file).exists():
|
||||
unresolved.append(f"{path}: {file}")
|
||||
continue
|
||||
text = (ROOT / file).read_text()
|
||||
headings = set(HEADING.findall(text))
|
||||
leads = headings | set(LEAD.findall(text))
|
||||
unresolved += [f"{path}: {file} → {name}" for i, name in enumerate(names) if name not in (headings if i == 0 else leads)]
|
||||
self.assertEqual(unresolved, [], "the first name is a heading of the cited file, each later one a heading or a bold lead")
|
||||
|
||||
def test_every_rule_file_named_exists_and_topic_rules_lists_each(self):
|
||||
tracked = subprocess.run(["git", "ls-files", "-z"], capture_output=True, check=True, cwd=ROOT, text=True).stdout.split("\0")
|
||||
named = {(path, rule) for path in filter(None, tracked) if not pathlib.Path(path).name.startswith("test_") for rule in RULE_FILE.findall((ROOT / path).read_text())}
|
||||
self.assertTrue(named)
|
||||
self.assertEqual(sorted(f"{path}: {rule}" for path, rule in named if not (ROOT / rule).exists()), [])
|
||||
topic_rules = (ROOT / "CLAUDE.md").read_text().split("## Topic rules\n")[1].split("\n## ")[0]
|
||||
self.assertEqual(sorted(set(RULE_FILE.findall(topic_rules))), sorted(f"rules/{rule.name}" for rule in (ROOT / "rules").glob("*.md")))
|
||||
|
||||
def test_every_folder_the_judge_reads_rules_from_exists(self):
|
||||
self.assertEqual([folder for folder in HUMAN_RULE_DIRS if not (ROOT / folder).is_dir()], [])
|
||||
@@ -0,0 +1,46 @@
|
||||
import pathlib
|
||||
import subprocess
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from repo_checks.test_python_floor import ROOT
|
||||
|
||||
PRIVATE = [
|
||||
".claude/settings.local.json",
|
||||
".credentials.json",
|
||||
"auto-mode-transcripts/a.jsonl",
|
||||
"backups/.claude.json.backup.1",
|
||||
"daemon-auth-status.json",
|
||||
"daemon.log",
|
||||
"daemon/control.key",
|
||||
"debug/a.txt",
|
||||
"file-history/a/b.md",
|
||||
"history.jsonl",
|
||||
"jobs/a/b.json",
|
||||
"loop-claude-transcripts/a/b.jsonl",
|
||||
"memory/MEMORY.md",
|
||||
"paste-cache/a.txt",
|
||||
"projects/-home-a/a.jsonl",
|
||||
"projects/-home-a/memory/MEMORY.md",
|
||||
"projects/-home-a/memory/a.md",
|
||||
"session-env/a/b.sh",
|
||||
"sessions/a.json",
|
||||
"shell-snapshots/a.sh",
|
||||
"tasks/a/b.json",
|
||||
"workflow-bench/a-1-1.md",
|
||||
"workflow-bench/a-1-1/README.md",
|
||||
"workflow-bench/compare/a/A1/fixes.diff",
|
||||
"workflow-bench/logs/a.jsonl",
|
||||
]
|
||||
|
||||
|
||||
class Gitignore(unittest.TestCase):
|
||||
def test_ignores_no_tracked_file(self):
|
||||
ignored = subprocess.run(["git", "ls-files", "-ci", "--exclude-standard"], capture_output=True, check=True, cwd=ROOT, text=True).stdout
|
||||
self.assertEqual(ignored, "")
|
||||
|
||||
def test_ignores_every_private_file(self):
|
||||
ignored = subprocess.run(["git", "check-ignore", "--no-index", "--stdin"], capture_output=True, cwd=ROOT, input="\n".join(PRIVATE), text=True).stdout
|
||||
self.assertEqual(ignored.splitlines(), PRIVATE)
|
||||
@@ -0,0 +1,33 @@
|
||||
import ast
|
||||
import pathlib
|
||||
import subprocess
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from repo_checks.test_python_floor import ROOT
|
||||
|
||||
|
||||
def bound(node: ast.Import | ast.ImportFrom) -> list[str]:
|
||||
return [alias.asname or alias.name for alias in node.names]
|
||||
|
||||
|
||||
def unsorted_imports(source: str) -> list[int]:
|
||||
"""The line numbers of imports whose names are out of order, or whose first name sorts before the first name of the import on the line above, ignoring case."""
|
||||
imports = [node for node in ast.parse(source).body if isinstance(node, ast.Import | ast.ImportFrom)]
|
||||
names_out = [node.lineno for node in imports if bound(node) != sorted(bound(node), key=str.casefold)]
|
||||
lines_out = [node.lineno for above, node in zip(imports, imports[1:]) if node.lineno == above.end_lineno + 1 and bound(node)[0].casefold() < bound(above)[0].casefold()]
|
||||
return sorted(set(names_out + lines_out))
|
||||
|
||||
|
||||
class ImportOrder(unittest.TestCase):
|
||||
def test_each_python_file_sorts_its_imports_by_their_first_binding(self):
|
||||
listed = subprocess.run(["git", "ls-files", "*.py", "bin/loop-claude"], capture_output=True, check=True, cwd=ROOT, text=True).stdout.split()
|
||||
self.assertIn("bin/loop-claude", listed)
|
||||
for name in listed:
|
||||
with self.subTest(name):
|
||||
self.assertEqual(unsorted_imports((ROOT / name).read_text(encoding="utf-8")), [])
|
||||
|
||||
def test_a_case_insensitive_name_out_of_order_is_found(self):
|
||||
self.assertEqual(unsorted_imports("import B\nimport a\n\nfrom x import C, b\n"), [2, 4])
|
||||
@@ -0,0 +1,20 @@
|
||||
import json
|
||||
import pathlib
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from repo_checks.test_python_floor import ROOT
|
||||
|
||||
|
||||
class Install(unittest.TestCase):
|
||||
def test_the_readme_adds_each_settings_marketplace_and_installs_every_enabled_plugin(self):
|
||||
settings = json.loads((ROOT / "settings.json").read_text(encoding="utf-8"))
|
||||
readme = (ROOT / "README.md").read_text(encoding="utf-8")
|
||||
for plugin, enabled in settings["enabledPlugins"].items():
|
||||
if enabled:
|
||||
self.assertIn(f"claude plugin install {plugin}\n", readme)
|
||||
# settings.json declares the marketplace, or `claude plugin marketplace add` writes it there.
|
||||
marketplace = settings["extraKnownMarketplaces"][plugin.split("@")[1]]["source"]["repo"]
|
||||
self.assertIn(f"claude plugin marketplace add {marketplace}\n", readme)
|
||||
@@ -5,7 +5,7 @@ import subprocess
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[1]
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[2]
|
||||
FLOOR = re.compile(r"Python 3\.(\d+) or newer")
|
||||
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import pathlib
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from repo_checks.test_python_floor import readme_floor, ROOT
|
||||
|
||||
|
||||
class Types(unittest.TestCase):
|
||||
def test_mypy_passes_on_the_tools_at_the_floor(self):
|
||||
floor = readme_floor()
|
||||
self.assertIsNotNone(floor, "README.md's Install names `Python 3.N or newer`")
|
||||
if shutil.which("uv") is None:
|
||||
self.fail("uv on PATH fetches mypy; see README.md's Test line")
|
||||
ran = subprocess.run(["uv", "tool", "run", "--python", "%d.%d" % floor, "mypy==2.3.1", "--cache-dir=/dev/null", "--check-untyped-defs", "--disallow-untyped-defs", "--exclude", "/test_", "-p", "claude_code", "-m", "comprehension_history", "-p", "larv_review", "-p", "loop_claude", "-m", "markdown_text", "-p", "metric_bench", "-m", "project_key", "-m", "rank_todo", "-p", "reading_cost", "-p", "rule_hook", "-m", "shell_command", "-m", "statusline", "-m", "todo_table", "-p", "transcript_archive", "-m", "utc_stamp"], capture_output=True, cwd=ROOT / "bin", text=True)
|
||||
self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr)
|
||||
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 rule_hook import main
|
||||
|
||||
sys.exit(main.main(sys.argv[1:], "" if sys.argv[1:] or sys.stdin.isatty() else sys.stdin.read()))
|
||||
@@ -0,0 +1,40 @@
|
||||
import dataclasses
|
||||
import typing
|
||||
|
||||
from failure import Failure
|
||||
|
||||
FILE_TOOLS = ("Edit", "MultiEdit", "Write")
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Call:
|
||||
tool: str
|
||||
given: dict[str, typing.Any]
|
||||
cwd: str
|
||||
|
||||
|
||||
def parsed_call(hook_input: object) -> Call | Failure:
|
||||
if not isinstance(hook_input, dict):
|
||||
return Failure("the hook input is no object")
|
||||
tool, given, cwd = hook_input.get("tool_name"), hook_input.get("tool_input"), hook_input.get("cwd")
|
||||
if not isinstance(tool, str) or not isinstance(given, dict) or not isinstance(cwd, str):
|
||||
return Failure("the hook input has no string tool_name and cwd and object tool_input")
|
||||
return Call(tool, given, cwd)
|
||||
|
||||
|
||||
def text(given: dict[str, typing.Any], key: str) -> str:
|
||||
value = given.get(key)
|
||||
return value if isinstance(value, str) else ""
|
||||
|
||||
|
||||
def applied(call: Call, before: str) -> tuple[str, str]:
|
||||
"""The text a file call writes, and the whole file it leaves."""
|
||||
if call.tool == "Write":
|
||||
content = text(call.given, "content")
|
||||
return content, content
|
||||
edits = [call.given] if call.tool == "Edit" else [edit for edit in call.given.get("edits") or [] if isinstance(edit, dict)]
|
||||
after = before
|
||||
for edit in edits:
|
||||
old, new = text(edit, "old_string"), text(edit, "new_string")
|
||||
after = after.replace(old, new) if edit.get("replace_all") else after.replace(old, new, 1)
|
||||
return "\n".join(text(edit, "new_string") for edit in edits), after
|
||||
@@ -0,0 +1,24 @@
|
||||
import os
|
||||
import pathlib
|
||||
import subprocess
|
||||
|
||||
from failure import Failure
|
||||
|
||||
# A -c given here outranks the checkout's own config, which may allow one transport by name; GIT_NO_LAZY_FETCH needs git 2.44.
|
||||
GUARDS = [option for setting in ["core.fsmonitor=false", "log.showSignature=false", "protocol.allow=never", *(f"protocol.{name}.allow=never" for name in ("ext", "file", "git", "http", "https", "ssh"))] for option in ("-c", setting)]
|
||||
|
||||
|
||||
def git(directory: str, *args: str) -> str | Failure:
|
||||
# The hook runs git in a checkout the call has not yet been allowed to touch, whose config could name a program: no fsmonitor, no signature check, and no fetch of a partial clone's missing objects through its transport.
|
||||
try:
|
||||
ran = subprocess.run(["git", *GUARDS, "-C", directory, *args], capture_output=True, env={**os.environ, "GIT_NO_LAZY_FETCH": "1"}, text=True)
|
||||
except OSError as failure:
|
||||
return Failure(f"git could not start: {failure}")
|
||||
return ran.stdout.strip() if ran.returncode == 0 else Failure(f"git {' '.join(args)}: {ran.stderr.strip()}")
|
||||
|
||||
|
||||
def existing(directory: str) -> str:
|
||||
path = pathlib.Path(directory or ".").absolute()
|
||||
while not path.is_dir():
|
||||
path = path.parent
|
||||
return str(path)
|
||||
@@ -0,0 +1,109 @@
|
||||
"""Block a Claude Code tool call that breaks a checkable rule, unless the call overrides the rule.
|
||||
|
||||
usage: rule-hook (a PreToolUse hook: reads the call as JSON on stdin)
|
||||
rule-hook overrides (prints this chunk's overrides)
|
||||
|
||||
settings.json runs it before each Bash, Edit, MultiEdit and Write call, in every session and
|
||||
subagent. The rules:
|
||||
|
||||
{rules}
|
||||
|
||||
A file a Bash command writes, such as through `cat > Dockerfile`, is not checked.
|
||||
|
||||
A call overrides a rule with `# rule-override <rule>: <reason>`:
|
||||
|
||||
- anywhere in a Bash command, such as a trailing comment
|
||||
- in a file, as a comment line in the text the edit writes
|
||||
- in Markdown, as `<!-- rule-override <rule>: <reason> -->`
|
||||
|
||||
Each override that let a call through is appended to rule-overrides.tsv in the git directory of
|
||||
the checkout it touched: UTC time, branch, the commit checked out, rule, reason, and the file
|
||||
written or the command's first line. An override outside any git checkout is not logged.
|
||||
`rule-hook overrides` prints the lines whose commit the current branch's reflog holds: those the
|
||||
default branch lacks, and those logged under the branch's own name.
|
||||
|
||||
Run with no arguments in a terminal, it prints this help.
|
||||
|
||||
Exit 2 with the rule, why it holds and how to override it, when a rule blocks the call, or when an
|
||||
override cannot be logged; 0 otherwise. `rule-hook overrides` exits 1 when git cannot read the
|
||||
checkout or the branch's reflog. Exit 1, a non-blocking error to Claude Code, on input it
|
||||
cannot read.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import sys
|
||||
import time
|
||||
|
||||
from rule_hook.call import applied, Call, FILE_TOOLS, parsed_call, text
|
||||
from rule_hook.rules import Breach, command_breaches, file_breaches, Outcome, rules_help, verdict
|
||||
from git_command import commits
|
||||
from failure import Failure
|
||||
from rule_hook.override_log import Log, log_path, logged, print_overrides, write_override
|
||||
from shell_command import simple_commands
|
||||
from rule_hook.todo_check import todo_breaches
|
||||
|
||||
|
||||
def main(argv: list[str], stdin: str) -> int:
|
||||
if argv in (["-h"], ["--help"]) or not argv and not stdin:
|
||||
print(__doc__.strip().replace("{rules}", rules_help()))
|
||||
return 0
|
||||
if argv == ["overrides"]:
|
||||
return print_overrides(os.getcwd())
|
||||
if argv:
|
||||
print(f"unknown arguments: {' '.join(argv)}; see rule-hook --help", file=sys.stderr)
|
||||
return 1
|
||||
try:
|
||||
call = parsed_call(json.loads(stdin))
|
||||
except json.JSONDecodeError as failure:
|
||||
call = Failure(str(failure))
|
||||
if isinstance(call, Failure):
|
||||
print(f"rule-hook cannot read the hook input: {call.reason}", file=sys.stderr)
|
||||
return 1
|
||||
found = breaches_of(call, os.path.expanduser("~"))
|
||||
if found is None:
|
||||
return 0
|
||||
written, what, breaches = found
|
||||
return answer(verdict(breaches, written, text(call.given, "file_path").endswith(".md"), call.tool == "Bash"), what, time.time())
|
||||
|
||||
|
||||
def breaches_of(call: Call, home: str) -> tuple[str, str, list[Breach]] | None:
|
||||
"""The text that may carry an override, what the log names the call by, and its breaches; None for a call no rule checks."""
|
||||
if call.tool == "Bash":
|
||||
command = text(call.given, "command")
|
||||
return command, command.split("\n", 1)[0], bash_breaches(command, call.cwd, home)
|
||||
path = text(call.given, "file_path")
|
||||
if call.tool not in FILE_TOOLS or not path:
|
||||
return None
|
||||
before = read(path)
|
||||
added, after = applied(call, before)
|
||||
return added, path, file_breaches(path, before, added, after)
|
||||
|
||||
|
||||
def answer(judged: Outcome, what: str, now: float) -> int:
|
||||
for message in judged.messages:
|
||||
print(message, file=sys.stderr)
|
||||
if judged.blocked:
|
||||
return 2
|
||||
logs = [(breach, reason, log_path(breach.directory)) for breach, reason in judged.overridden]
|
||||
# Resolve every log before writing any, so a call that ends blocked has logged nothing.
|
||||
unloggable = [f"{breach.rule}: {log.reason}" for breach, _, log in logs if isinstance(log, Failure)]
|
||||
if not unloggable:
|
||||
for breach, reason, log in logs:
|
||||
unwritten = write_override(log, logged(log, breach, reason, what, now)) if isinstance(log, Log) else None
|
||||
unloggable += [f"{breach.rule}: {unwritten.reason}"] if unwritten else []
|
||||
for unlogged in unloggable:
|
||||
print(f"rule-hook cannot log the override of {unlogged}; unlogged, it would escape review.", file=sys.stderr)
|
||||
return 2 if unloggable else 0
|
||||
|
||||
|
||||
def bash_breaches(command: str, cwd: str, home: str) -> list[Breach]:
|
||||
simples = simple_commands(command, cwd, home)
|
||||
return command_breaches(command, simples, home) + [breach for commit in commits(simples, home) for breach in todo_breaches(commit.directory)]
|
||||
|
||||
|
||||
def read(path: str) -> str:
|
||||
try:
|
||||
return pathlib.Path(path).read_text(encoding="utf-8")
|
||||
except (OSError, UnicodeDecodeError):
|
||||
return ""
|
||||
@@ -0,0 +1,123 @@
|
||||
import dataclasses
|
||||
import os
|
||||
import pathlib
|
||||
import stat
|
||||
import sys
|
||||
import typing
|
||||
|
||||
from rule_hook.rules import Breach
|
||||
from rule_hook.git import existing, git
|
||||
from failure import Failure
|
||||
from utc_stamp import utc
|
||||
|
||||
LOG = "rule-overrides.tsv"
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class LogLine:
|
||||
"""One line of the log, its fields tab-separated in this order."""
|
||||
at: str
|
||||
branch: str
|
||||
# The commit checked out when the override let its call through; empty on a branch with no commit yet.
|
||||
commit: str
|
||||
rule: str
|
||||
reason: str
|
||||
what: str
|
||||
|
||||
def line(self) -> str:
|
||||
return "\t".join(" ".join(field.split()) for field in dataclasses.astuple(self)) + "\n"
|
||||
|
||||
|
||||
def parsed_entry(line: str) -> LogLine | None:
|
||||
fields = line.rstrip("\n").split("\t")
|
||||
return LogLine(*fields) if len(fields) == len(dataclasses.fields(LogLine)) else None
|
||||
|
||||
|
||||
def this_chunks(entry: LogLine, reflog: set[str], branch: str, on_default: typing.Callable[[str], bool]) -> bool:
|
||||
"""Whether the override is the current branch's: its commit is in the branch's reflog, which keeps a commit an amend or a rebase replaced, follows `git branch -m`, and holds no other branch's commit."""
|
||||
if entry.commit == "":
|
||||
return True
|
||||
# The default branch's commits are in every branch's reflog, so such a line counts only under the branch's own name: one logged before the branch's first commit.
|
||||
return entry.commit in reflog and (entry.branch == branch or not on_default(entry.commit))
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Log:
|
||||
path: pathlib.Path
|
||||
branch: str
|
||||
head: str
|
||||
|
||||
|
||||
def log_path(directory: str) -> Log | Failure | None:
|
||||
"""Where an override in this directory is logged; None outside any git checkout."""
|
||||
directory = existing(directory)
|
||||
if not any((parent / ".git").exists() for parent in [pathlib.Path(directory), *pathlib.Path(directory).parents]):
|
||||
return None
|
||||
common = git(directory, "rev-parse", "--path-format=absolute", "--git-common-dir")
|
||||
branch = git(directory, "branch", "--show-current")
|
||||
for found in (common, branch):
|
||||
if isinstance(found, Failure):
|
||||
return found
|
||||
head = git(directory, "rev-parse", "--verify", "--quiet", "HEAD")
|
||||
return Log(pathlib.Path(str(common)) / LOG, str(branch) or "HEAD", "" if isinstance(head, Failure) else head)
|
||||
|
||||
|
||||
def write_override(log: Log, entry: LogLine) -> Failure | None:
|
||||
try:
|
||||
# No symlink, and no FIFO to hang on: the checkout, and so its git directory, may come from anyone.
|
||||
descriptor = os.open(log.path, os.O_WRONLY | os.O_APPEND | os.O_CREAT | os.O_NOFOLLOW | os.O_NONBLOCK, 0o600)
|
||||
except OSError as failure:
|
||||
return Failure(str(failure))
|
||||
try:
|
||||
if not stat.S_ISREG(os.fstat(descriptor).st_mode):
|
||||
return Failure(f"{log.path} is no regular file")
|
||||
os.write(descriptor, entry.line().encode("utf-8"))
|
||||
except OSError as failure:
|
||||
return Failure(str(failure))
|
||||
finally:
|
||||
os.close(descriptor)
|
||||
return None
|
||||
|
||||
|
||||
def logged(log: Log, breach: Breach, reason: str, what: str, now: float) -> LogLine:
|
||||
return LogLine(utc(now), log.branch, log.head, breach.rule, reason, what)
|
||||
|
||||
|
||||
def print_overrides(directory: str) -> int:
|
||||
common = git(directory, "rev-parse", "--path-format=absolute", "--git-common-dir")
|
||||
if isinstance(common, Failure):
|
||||
print(f"rule-hook overrides runs in a git checkout: {common.reason}", file=sys.stderr)
|
||||
return 1
|
||||
found = git(directory, "branch", "--show-current")
|
||||
branch = found if isinstance(found, str) and found else "HEAD"
|
||||
reflog = git(directory, "reflog", "show", "--format=%H", branch)
|
||||
head = git(directory, "rev-parse", "HEAD")
|
||||
unread = unread_reflog(reflog, head)
|
||||
if unread:
|
||||
print(f"rule-hook overrides cannot read the branch's reflog, so it cannot tell which overrides are this chunk's: {unread.reason}", file=sys.stderr)
|
||||
return 1
|
||||
default = default_branch(directory)
|
||||
log = pathlib.Path(common) / LOG
|
||||
entries = [parsed_entry(line) for line in log.read_text(encoding="utf-8").splitlines()] if log.is_file() else []
|
||||
on_default = (lambda commit: holds(directory, default, commit)) if default else (lambda commit: False)
|
||||
for entry in entries:
|
||||
if entry and this_chunks(entry, set(str(reflog).split()), branch, on_default):
|
||||
print(entry.line(), end="")
|
||||
return 0
|
||||
|
||||
|
||||
def unread_reflog(reflog: str | Failure, head: str | Failure) -> Failure | None:
|
||||
if isinstance(reflog, Failure):
|
||||
return reflog
|
||||
if isinstance(head, Failure):
|
||||
return head
|
||||
# A reflog missing HEAD is off or expired, and would hide this chunk's overrides.
|
||||
return None if head in reflog.split() else Failure("it does not hold HEAD")
|
||||
|
||||
|
||||
def default_branch(directory: str) -> str | None:
|
||||
return next((name for name in ("origin/HEAD", "main", "master") if not isinstance(git(directory, "rev-parse", "--verify", "--quiet", name), Failure)), None)
|
||||
|
||||
|
||||
def holds(directory: str, descendant: str, ancestor: str) -> bool:
|
||||
return bool(ancestor) and not isinstance(git(directory, "merge-base", "--is-ancestor", ancestor, descendant), Failure)
|
||||
@@ -0,0 +1,165 @@
|
||||
import dataclasses
|
||||
import posixpath
|
||||
import re
|
||||
import typing
|
||||
|
||||
from git_command import commits
|
||||
from shell_command import Simple
|
||||
|
||||
RuleName = typing.Literal["action-pin", "commit-one-line", "ignorefile-sorted", "image-pin", "no-ai-attribution", "todo-rank-check"]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Rule:
|
||||
holds: str
|
||||
checked: str
|
||||
|
||||
|
||||
RULES: dict[RuleName, Rule] = {
|
||||
"action-pin": Rule(
|
||||
"a GitHub or Gitea Action is pinned to a semver tag, such as @v3 or @v3.1.2, never to a branch, and to a commit SHA only in a pipeline that tests our own specific builds",
|
||||
"`uses:` in a .github or .gitea workflow, or in action.yml",
|
||||
),
|
||||
"commit-one-line": Rule(
|
||||
"a commit message is one line, prefixed with the ticket ID when the work has one",
|
||||
"git commit takes its message as one -m with no line break; -F, a second -m and a heredoc are blocked",
|
||||
),
|
||||
"ignorefile-sorted": Rule(
|
||||
"each block of an ignore file is sorted in code-point order, as LC_ALL=C sort does, since its order carries no meaning; where order matters, such as a re-include after its exclude, split the block with a blank line or a comment",
|
||||
"a .*ignore file; a block already unsorted before the edit is left alone",
|
||||
),
|
||||
"image-pin": Rule(
|
||||
"a container image is pinned to its full patch version, such as node:24.18.1-bookworm-slim, or to a date-stamped tag or an @sha256: digest, so the same commit builds the same image on every day; an image that publishes no three-part tag, such as postgres:16.4, takes an override",
|
||||
"a Dockerfile's FROM and COPY --from, and `image:` and `container:` in a compose file or workflow",
|
||||
),
|
||||
"no-ai-attribution": Rule(
|
||||
"no commit, PR, issue comment or file carries a Claude or Anthropic attribution, such as a co-author trailer or a generated-with line",
|
||||
"a git, gh or tea command, and any file written",
|
||||
),
|
||||
"todo-rank-check": Rule(
|
||||
"while todo.md has changes, staged or not, a git commit waits until ~/.claude/bin/rank_todo.py --check passes on it",
|
||||
"a git commit in a checkout whose todo.md has changes",
|
||||
),
|
||||
}
|
||||
OVERRIDE = re.compile(r"(?:#|<!--)\s*rule-override ([a-z-]+):([^\n]*?)(?=[ \t]*(?:#|<!--)\s*rule-override |$)", re.MULTILINE)
|
||||
# [-] keeps this file from matching itself.
|
||||
ATTRIBUTION = re.compile(r"co-authored[-]by:[^\n]*\b(?:claude|anthropic)\b|generated with \[?claude code", re.IGNORECASE)
|
||||
SEMVER = re.compile(r"v?\d+(?:\.\d+){0,2}")
|
||||
# Two-part tags such as postgres:16.4 stay blocked: the rule bans node:24.18, which reads the same, so such an image takes an override.
|
||||
PATCH = re.compile(r"v?\d+\.\d+\.\d+(?:[-+_.].*)?|.*\d{8}.*")
|
||||
FROM = re.compile(r"^[ \t]*FROM[ \t]+(?:--\S+[ \t]+)*(\S+)(?:[ \t]+AS[ \t]+(\S+))?", re.IGNORECASE | re.MULTILINE)
|
||||
COPIED = re.compile(r"^[ \t]*COPY[ \t].*?--from=(\S+)", re.IGNORECASE | re.MULTILINE)
|
||||
IMAGE = re.compile(r"^[ \t]*(?:-[ \t]+)?(?:image|container):[ \t]*[\"']?([^\s\"'#{]+)", re.MULTILINE)
|
||||
USES = re.compile(r"^[ \t]*(?:-[ \t]+)?uses:[ \t]*[\"']?([^\s\"'#]+)", re.MULTILINE)
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Breach:
|
||||
rule: RuleName
|
||||
detail: str
|
||||
# The checkout whose log records an override of this breach.
|
||||
directory: str
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Outcome:
|
||||
messages: list[str]
|
||||
blocked: bool
|
||||
# Each breach an override let through, with its reason; logged only when the call goes through.
|
||||
overridden: list[tuple[Breach, str]]
|
||||
|
||||
|
||||
def overrides(written: str) -> tuple[dict[str, str], list[str]]:
|
||||
"""The rules the text overrides with their reasons, and the markers that name no rule or give no reason."""
|
||||
given = [(rule, reason.strip().removesuffix("-->").strip()) for rule, reason in OVERRIDE.findall(written)]
|
||||
granted = {rule: reason for rule, reason in given if rule in RULES and reason}
|
||||
return granted, [f"rule-override {rule}: {reason}" for rule, reason in given if rule not in granted]
|
||||
|
||||
|
||||
def verdict(breaches: list[Breach], written: str, markdown: bool, bash: bool) -> Outcome:
|
||||
granted, malformed = overrides(written)
|
||||
blocking = [breach for breach in breaches if breach.rule not in granted]
|
||||
messages = [f"`{marker}` names no rule below, or gives no reason." for marker in malformed] if blocking else []
|
||||
where = "the command" if bash else "the text you write, as a comment line"
|
||||
for rule in sorted({breach.rule for breach in blocking}):
|
||||
details = "; ".join(breach.detail for breach in blocking if breach.rule == rule)
|
||||
marker = f"<!-- rule-override {rule}: <reason> -->" if markdown else f"# rule-override {rule}: <reason>"
|
||||
messages.append(f"Blocked by rule {rule}: {details}. The rule: {RULES[rule].holds}. Where it does not fit this case, add `{marker}` to {where}; larv-review rules on the reason.")
|
||||
return Outcome(messages, bool(blocking), [(breach, granted[breach.rule]) for breach in breaches if breach.rule in granted])
|
||||
|
||||
|
||||
def command_breaches(command: str, simples: list[Simple], home: str) -> list[Breach]:
|
||||
breaches = []
|
||||
found = commits(simples, home)
|
||||
publishing = [simple for simple in simples if simple.words[0] in ("gh", "git", "tea")]
|
||||
if publishing and ATTRIBUTION.search(command):
|
||||
breaches.append(Breach("no-ai-attribution", "the command carries an attribution", publishing[0].directory))
|
||||
for commit in found:
|
||||
if commit.from_file:
|
||||
breaches.append(Breach("commit-one-line", "pass the message as one -m '<line>', not from a file", commit.directory))
|
||||
elif len(commit.messages) > 1 or any("\n" in message.strip() for message in commit.messages):
|
||||
breaches.append(Breach("commit-one-line", "pass the message as one -m '<line>', with no heredoc, second -m or newline", commit.directory))
|
||||
return breaches
|
||||
|
||||
|
||||
def file_breaches(path: str, before: str, added: str, after: str) -> list[Breach]:
|
||||
"""Breaches in an edit of path: added is the text the edit writes, after the whole file it leaves."""
|
||||
breaches = [Breach("no-ai-attribution", f"{path} would carry an attribution", posixpath.dirname(path))] if ATTRIBUTION.search(added) else []
|
||||
return breaches + image_breaches(path, before, added, after) + action_breaches(path, added) + ignore_breaches(path, before, after)
|
||||
|
||||
|
||||
def image_breaches(path: str, before: str, added: str, after: str) -> list[Breach]:
|
||||
name = posixpath.basename(path)
|
||||
if name.startswith(("Dockerfile", "Containerfile")) or name.endswith((".dockerfile", ".Dockerfile", ".containerfile")):
|
||||
stages = {stage.lower() for _, stage in FROM.findall(before + "\n" + after) if stage} | {"scratch"}
|
||||
images = [image for image, _ in FROM.findall(added) if image.lower() not in stages] + [image for image in COPIED.findall(added) if image.lower() not in stages and not image.isdigit()]
|
||||
elif "compose" in name and name.endswith((".yml", ".yaml")) or workflow(path):
|
||||
images = IMAGE.findall(added)
|
||||
else:
|
||||
images = []
|
||||
return [Breach("image-pin", f"{path}: {image}", posixpath.dirname(path)) for image in images if not pinned(image)]
|
||||
|
||||
|
||||
def action_breaches(path: str, added: str) -> list[Breach]:
|
||||
actions = USES.findall(added) if workflow(path) else []
|
||||
return [Breach("action-pin", f"{path}: uses: {action}", posixpath.dirname(path)) for action in actions if not tagged(action)]
|
||||
|
||||
|
||||
def ignore_breaches(path: str, before: str, after: str) -> list[Breach]:
|
||||
name = posixpath.basename(path)
|
||||
if not (name.startswith(".") and name.endswith("ignore")):
|
||||
return []
|
||||
already = [block for block in blocks(before) if block != sorted(block)]
|
||||
return [Breach("ignorefile-sorted", f"{path}: sort the block {block[0]!r} through {block[-1]!r} as {', '.join(sorted(block))}", posixpath.dirname(path)) for block in blocks(after) if block != sorted(block) and block not in already]
|
||||
|
||||
|
||||
def workflow(path: str) -> bool:
|
||||
return any(folder in "/" + path for folder in ("/.github/workflows/", "/.gitea/workflows/")) or posixpath.basename(path) in ("action.yml", "action.yaml")
|
||||
|
||||
|
||||
def pinned(image: str) -> bool:
|
||||
if "$" in image or "{{" in image or "@sha256:" in image:
|
||||
return True
|
||||
tail = image.rsplit("/", 1)[-1]
|
||||
return ":" in tail and PATCH.fullmatch(tail.split(":", 1)[1]) is not None
|
||||
|
||||
|
||||
def tagged(action: str) -> bool:
|
||||
if action.startswith(("./", "docker://")) or "$" in action or "{{" in action:
|
||||
return True
|
||||
return "@" in action and SEMVER.fullmatch(action.rsplit("@", 1)[1]) is not None
|
||||
|
||||
|
||||
def blocks(written: str) -> list[list[str]]:
|
||||
"""An ignore file's runs of patterns, split at each blank line and comment."""
|
||||
runs: list[list[str]] = [[]]
|
||||
for line in written.splitlines():
|
||||
if line.strip() and not line.startswith("#"):
|
||||
runs[-1].append(line)
|
||||
elif runs[-1]:
|
||||
runs.append([])
|
||||
return [run for run in runs if run]
|
||||
|
||||
|
||||
def rules_help() -> str:
|
||||
return "\n".join(f" {name}\n The rule: {rule.holds}.\n Checked in: {rule.checked}." for name, rule in RULES.items())
|
||||
@@ -0,0 +1,279 @@
|
||||
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 rule_hook.rules import blocks, Breach, command_breaches, file_breaches, overrides, verdict
|
||||
from git_command import Commit, commit_message, commits
|
||||
from test_rank_todo import DECISIONS, README, TODO
|
||||
from test_env import isolated_env
|
||||
from rule_hook.override_log import LogLine, parsed_entry, this_chunks
|
||||
from shell_command import simple_commands
|
||||
|
||||
HOOK = pathlib.Path(__file__).resolve().parents[1] / "rule-hook"
|
||||
# Built from parts, so this file carries no attribution of its own.
|
||||
TRAILER = "Co-Authored-" + "By: Claude <noreply@anthropic.com>"
|
||||
|
||||
|
||||
def rules(breaches: list[Breach]) -> list[str]:
|
||||
return [breach.rule for breach in breaches]
|
||||
|
||||
|
||||
def committed(command: str, cwd: str = "/r") -> list[Commit]:
|
||||
return commits(simple_commands(command, cwd, "/h"), "/h")
|
||||
|
||||
|
||||
def checked(command: str) -> list[str]:
|
||||
return rules(command_breaches(command, simple_commands(command, "/r", "/h"), "/h"))
|
||||
|
||||
|
||||
def hook(call: dict, cwd: str) -> subprocess.CompletedProcess:
|
||||
return subprocess.run([str(HOOK)], capture_output=True, cwd=cwd, env=isolated_env(), input=json.dumps(call), text=True)
|
||||
|
||||
|
||||
def git(cwd: str, *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
|
||||
|
||||
|
||||
class Commits(unittest.TestCase):
|
||||
def test_cd_and_dash_capital_c_move_the_commit(self):
|
||||
self.assertEqual(committed("cd a && git -C ~/b commit -am 'x'"), [Commit("/h/b", ["x"], False)])
|
||||
self.assertEqual(committed("cd a && git -c x=y -C b commit -m x")[0].directory, "/r/a/b")
|
||||
|
||||
def test_each_message_spelling_is_read(self):
|
||||
self.assertEqual(commit_message(["--message=a", "-m", "b=c", "--message", "c", "-mz", "-am", "d"]), (["a", "b=c", "c", "z", "d"], False))
|
||||
|
||||
def test_a_file_message_is_seen(self):
|
||||
self.assertEqual(commit_message(["-F", "-"]), ([], True))
|
||||
self.assertEqual(commit_message(["--file=x"]), ([], True))
|
||||
|
||||
def test_other_git_commands_are_no_commit(self):
|
||||
self.assertEqual(committed("git log --grep commit; echo git commit"), [])
|
||||
|
||||
def test_a_line_break_or_a_comment_separates_commands(self):
|
||||
self.assertEqual(committed("cd a # go there\nGIT_EDITOR=true git commit -m x"), [Commit("/r/a", ["x"], False)])
|
||||
|
||||
def test_a_commit_after_a_heredoc_or_a_blank_line_is_seen(self):
|
||||
self.assertEqual(len(committed("cat <<EOF > notes\nhello\nEOF\ngit commit -m a")), 1)
|
||||
self.assertEqual(len(committed("git status &&\n\ngit commit -m a")), 1)
|
||||
|
||||
def test_an_arithmetic_shift_is_no_heredoc(self):
|
||||
self.assertEqual(len(committed("echo $((1<<2))\ngit commit -m a\n2")), 1)
|
||||
|
||||
def test_a_line_that_does_not_parse_hides_only_itself(self):
|
||||
self.assertEqual(len(committed("echo 'open\ngit commit -m a")), 1)
|
||||
|
||||
|
||||
class CommandBreaches(unittest.TestCase):
|
||||
def test_one_line_passes(self):
|
||||
self.assertEqual(checked("git add . && git commit -m 'ABC-1 - Fix #2'"), [])
|
||||
|
||||
def test_a_heredoc_a_second_message_or_a_file_breaks_commit_one_line(self):
|
||||
for command in ["git commit -m \"$(cat <<'EOF'\nIt's one line\nEOF\n)\"", "git commit -m a -m b", "git commit -F - <<'EOF'\nTitle\n\nIt's the body\nEOF\necho done", "git commit --author '' -m a -m b"]:
|
||||
with self.subTest(command):
|
||||
self.assertEqual(checked(command), ["commit-one-line"])
|
||||
|
||||
def test_an_attribution_breaks_only_in_a_git_gh_or_tea_command(self):
|
||||
self.assertEqual(checked(f"tea pr create --description '{TRAILER}'"), ["no-ai-attribution"])
|
||||
self.assertEqual(checked(f"grep -rn '{TRAILER}' ."), [])
|
||||
|
||||
def test_a_commit_breach_names_the_commit_s_checkout(self):
|
||||
self.assertEqual(command_breaches("cd w && git commit -m a -m b", simple_commands("cd w && git commit -m a -m b", "/r", "/h"), "/h")[0].directory, "/r/w")
|
||||
|
||||
|
||||
class FileBreaches(unittest.TestCase):
|
||||
def test_an_image_needs_a_patch_version_a_date_or_a_digest(self):
|
||||
added = "FROM node:24 AS build\nFROM node:24.18.1-bookworm-slim\nFROM alpine@sha256:ab\nFROM debian:bookworm-20240926-slim\nFROM build\nFROM scratch\nFROM ${BASE}\nFROM python\nCOPY --from=build /a /a\nCOPY --from=0 /b /b\nCOPY --chown=1 --from=alpine:3 /c /c\n"
|
||||
self.assertEqual([breach.detail for breach in file_breaches("/r/Dockerfile", "", added, added)], ["/r/Dockerfile: node:24", "/r/Dockerfile: python", "/r/Dockerfile: alpine:3"])
|
||||
|
||||
def test_a_stage_named_outside_the_edit_is_no_image(self):
|
||||
self.assertEqual(file_breaches("app.dockerfile", "FROM node:24.1.0 AS base\n", "FROM base\n", "FROM node:24.1.0 AS base\nFROM base\n"), [])
|
||||
|
||||
def test_a_workflow_checks_its_images_and_actions(self):
|
||||
added = " container: node:24\n image: mysql:8.4\n - image: 'mysql:8.4.7'\n - uses: actions/checkout@v4\n - uses: a/b@0123456789abcdef0123456789abcdef01234567\n - uses: ./local\n"
|
||||
self.assertEqual(rules(file_breaches("/r/.gitea/workflows/ci.yml", "", added, added)), ["image-pin", "image-pin", "action-pin"])
|
||||
|
||||
def test_a_compose_file_checks_its_images(self):
|
||||
self.assertEqual(rules(file_breaches("compose.yaml", "", " image: redis\n", " image: redis\n")), ["image-pin"])
|
||||
|
||||
def test_other_yaml_is_not_checked(self):
|
||||
added = "image: /assets/og.png\nimage: { type: string }\nuses: a/b@main\n"
|
||||
self.assertEqual(file_breaches("_config.yml", "", added, added), [])
|
||||
|
||||
def test_an_ignore_file_sorts_each_block_split_by_blank_lines_and_comments(self):
|
||||
self.assertEqual(blocks("b\na\n\n# c\nd\n# e\nf\n"), [["b", "a"], ["d"], ["f"]])
|
||||
self.assertEqual(rules(file_breaches(".dockerignore", "", "x", "b\na\n")), ["ignorefile-sorted"])
|
||||
self.assertEqual(file_breaches(".gitignore", "", "x", "*\n\n!a\n!b\n"), [])
|
||||
|
||||
def test_a_block_unsorted_before_the_edit_is_left_alone(self):
|
||||
self.assertEqual(file_breaches(".gitignore", "node_modules\n.env\n\ndist\n", "out", "node_modules\n.env\n\ndist\nout\n"), [])
|
||||
|
||||
def test_an_attribution_in_any_file_breaks(self):
|
||||
self.assertEqual(rules(file_breaches("notes.md", "", TRAILER, TRAILER)), ["no-ai-attribution"])
|
||||
|
||||
|
||||
class Overrides(unittest.TestCase):
|
||||
def test_a_marker_names_a_known_rule_and_a_reason(self):
|
||||
self.assertEqual(overrides("x # rule-override image-pin: vendor ships floating tags only\n# rule-override nope: x\n# rule-override action-pin:"), ({"image-pin": "vendor ships floating tags only"}, ["rule-override nope: x", "rule-override action-pin: "]))
|
||||
|
||||
def test_two_markers_on_a_line_are_read_apart(self):
|
||||
self.assertEqual(overrides("git x # rule-override image-pin: a # rule-override nope: b")[1], ["rule-override nope: b"])
|
||||
|
||||
def test_markdown_takes_an_html_comment(self):
|
||||
self.assertEqual(overrides("<!-- rule-override no-ai-attribution: quotes the banned line -->")[0], {"no-ai-attribution": "quotes the banned line"})
|
||||
|
||||
def test_a_blocked_call_overrides_nothing_yet(self):
|
||||
breaches = [Breach("image-pin", "x", "/r"), Breach("action-pin", "y", "/r")]
|
||||
judged = verdict(breaches, "# rule-override image-pin: a", False, False)
|
||||
self.assertTrue(judged.blocked)
|
||||
passed = verdict(breaches[:1], "# rule-override image-pin: a", False, False)
|
||||
self.assertEqual((passed.blocked, passed.overridden), (False, [(breaches[0], "a")]))
|
||||
|
||||
def test_a_markdown_file_is_told_the_html_comment(self):
|
||||
self.assertIn("`<!-- rule-override no-ai-attribution: <reason> -->`", verdict([Breach("no-ai-attribution", "x", "/r")], "", True, False).messages[0])
|
||||
|
||||
|
||||
class OverrideLog(unittest.TestCase):
|
||||
def test_an_entry_reads_back_as_written(self):
|
||||
entry = LogLine("2026-10-13T00:00:00Z", "chunk", "c1", "image-pin", "the vendor\ttags no patch", "Dockerfile")
|
||||
self.assertEqual(parsed_entry(entry.line()), LogLine("2026-10-13T00:00:00Z", "chunk", "c1", "image-pin", "the vendor tags no patch", "Dockerfile"))
|
||||
self.assertIsNone(parsed_entry("a\tb"))
|
||||
|
||||
def test_an_override_is_the_chunk_s_by_its_reflog_and_name(self):
|
||||
on_default = {"base"}.__contains__
|
||||
cases = [("chunk", "c1", True), ("other", "c1", True), ("other", "c9", False), ("chunk", "base", True), ("other", "base", False), ("other", "", True)]
|
||||
for branch, commit, expected in cases:
|
||||
with self.subTest(branch=branch, commit=commit):
|
||||
self.assertEqual(this_chunks(LogLine("t", branch, commit, "image-pin", "r", "w"), {"base", "c1"}, "chunk", on_default), expected)
|
||||
|
||||
|
||||
class Hook(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.repo = tempfile.mkdtemp()
|
||||
self.addCleanup(subprocess.run, ["rm", "-rf", self.repo])
|
||||
git(self.repo, "init", "-q", "-b", "main")
|
||||
git(self.repo, "commit", "-q", "--allow-empty", "-m", "base")
|
||||
git(self.repo, "checkout", "-q", "-b", "chunk")
|
||||
|
||||
def listed(self) -> str:
|
||||
return subprocess.run([str(HOOK), "overrides"], capture_output=True, check=True, cwd=self.repo, env=isolated_env(), text=True).stdout
|
||||
|
||||
def test_a_breach_exits_2_naming_the_rule_and_the_override(self):
|
||||
ran = hook({"cwd": self.repo, "tool_input": {"file_path": f"{self.repo}/Dockerfile", "content": "FROM node:24\n"}, "tool_name": "Write"}, self.repo)
|
||||
self.assertEqual(ran.returncode, 2)
|
||||
self.assertIn("Blocked by rule image-pin: ", ran.stderr)
|
||||
self.assertIn("`# rule-override image-pin: <reason>`", ran.stderr)
|
||||
|
||||
def test_an_override_passes_and_is_listed_for_the_chunk(self):
|
||||
content = "# rule-override image-pin: the vendor tags no patch versions\nFROM vendor/tool:2\n"
|
||||
ran = hook({"cwd": self.repo, "tool_input": {"file_path": f"{self.repo}/sub/Dockerfile", "content": content}, "tool_name": "Write"}, self.repo)
|
||||
self.assertEqual((ran.returncode, ran.stderr), (0, ""))
|
||||
self.assertRegex(self.listed(), r"^\S+Z\tchunk\t[0-9a-f]{40}\timage-pin\tthe vendor tags no patch versions\t\S+/sub/Dockerfile\n$")
|
||||
git(self.repo, "checkout", "-q", "main")
|
||||
git(self.repo, "commit", "-q", "--allow-empty", "-m", "elsewhere")
|
||||
self.assertEqual(self.listed(), "", "the default branch holds no override of its own")
|
||||
|
||||
def test_an_override_outlives_an_amend(self):
|
||||
git(self.repo, "commit", "-q", "--allow-empty", "-m", "work")
|
||||
content = "# rule-override image-pin: the vendor tags no patch versions\nFROM vendor/tool:2\n"
|
||||
hook({"cwd": self.repo, "tool_input": {"file_path": f"{self.repo}/Dockerfile", "content": content}, "tool_name": "Write"}, self.repo)
|
||||
git(self.repo, "commit", "-q", "--amend", "--allow-empty", "-m", "reworded")
|
||||
git(self.repo, "branch", "-m", "renamed")
|
||||
self.assertIn("\timage-pin\t", self.listed(), "the reflog keeps the amended commit")
|
||||
|
||||
def test_an_unreadable_reflog_fails_the_listing(self):
|
||||
unborn = tempfile.mkdtemp()
|
||||
self.addCleanup(subprocess.run, ["rm", "-rf", unborn])
|
||||
git(unborn, "init", "-q", "-b", "chunk")
|
||||
ran = subprocess.run([str(HOOK), "overrides"], capture_output=True, cwd=unborn, env=isolated_env(), text=True)
|
||||
self.assertEqual(ran.returncode, 1)
|
||||
self.assertIn("cannot read the branch's reflog", ran.stderr)
|
||||
git(self.repo, "reflog", "expire", "--expire=now", "--all")
|
||||
self.assertEqual(subprocess.run([str(HOOK), "overrides"], capture_output=True, cwd=self.repo, env=isolated_env(), text=True).returncode, 1, "an expired reflog holds no HEAD")
|
||||
|
||||
def test_a_sibling_branch_s_override_is_not_listed(self):
|
||||
git(self.repo, "checkout", "-q", "-b", "sibling")
|
||||
git(self.repo, "commit", "-q", "--allow-empty", "-m", "sibling work")
|
||||
content = "# rule-override image-pin: the vendor tags no patch versions\nFROM vendor/tool:2\n"
|
||||
hook({"cwd": self.repo, "tool_input": {"file_path": f"{self.repo}/Dockerfile", "content": content}, "tool_name": "Write"}, self.repo)
|
||||
git(self.repo, "checkout", "-q", "chunk")
|
||||
self.assertEqual(self.listed(), "")
|
||||
git(self.repo, "merge", "-q", "--squash", "sibling")
|
||||
git(self.repo, "commit", "-q", "--allow-empty", "-m", "squashed")
|
||||
self.assertEqual(self.listed(), "", "a squash merge brings in none of the sibling's commits")
|
||||
|
||||
def test_a_blocked_call_logs_no_override(self):
|
||||
command = f"git commit -m a -m '{TRAILER}' # rule-override no-ai-attribution: quotes it"
|
||||
self.assertEqual(hook({"cwd": self.repo, "tool_input": {"command": command}, "tool_name": "Bash"}, self.repo).returncode, 2)
|
||||
self.assertEqual(self.listed(), "")
|
||||
|
||||
def test_a_commit_override_is_logged_in_the_commit_s_checkout(self):
|
||||
outside = tempfile.mkdtemp()
|
||||
self.addCleanup(subprocess.run, ["rm", "-rf", outside])
|
||||
ran = hook({"cwd": outside, "tool_input": {"command": f"git -C {self.repo} commit -m a -m b # rule-override commit-one-line: a body is needed"}, "tool_name": "Bash"}, outside)
|
||||
self.assertEqual(ran.returncode, 0)
|
||||
self.assertIn("\tcommit-one-line\ta body is needed\t", self.listed())
|
||||
|
||||
def test_an_edit_is_judged_on_the_file_it_leaves(self):
|
||||
pathlib.Path(self.repo, ".gitignore").write_text("a\nc\n")
|
||||
call = {"cwd": self.repo, "tool_input": {"file_path": f"{self.repo}/.gitignore", "new_string": "d", "old_string": "a"}, "tool_name": "Edit"}
|
||||
self.assertEqual(hook(call, self.repo).returncode, 2)
|
||||
|
||||
def test_a_commit_while_an_unranked_todo_has_changes_is_blocked(self):
|
||||
pathlib.Path(self.repo, "docs").mkdir()
|
||||
for name, content in [("README.md", README), ("docs/decisions.md", DECISIONS), ("todo.md", TODO)]:
|
||||
pathlib.Path(self.repo, name).write_text(content)
|
||||
git(self.repo, "add", "README.md", "docs", "todo.md")
|
||||
git(self.repo, "commit", "-qm", "x", "--no-verify")
|
||||
call = {"cwd": self.repo, "tool_input": {"command": "git add -A && git commit -m x"}, "tool_name": "Bash"}
|
||||
self.assertEqual(hook(call, self.repo).returncode, 0, "todo.md is unchanged")
|
||||
pathlib.Path(self.repo, "todo.md").write_text(TODO + "\n")
|
||||
ran = hook(call, self.repo)
|
||||
self.assertEqual(ran.returncode, 2)
|
||||
self.assertIn("todo.md: not ranked", ran.stderr)
|
||||
|
||||
def test_a_staged_todo_change_is_checked_and_no_clean_filter_runs(self):
|
||||
pathlib.Path(self.repo, "docs").mkdir()
|
||||
for name, content in [("README.md", README), ("docs/decisions.md", DECISIONS), ("todo.md", TODO), (".gitattributes", "todo.md filter=planted\n")]:
|
||||
pathlib.Path(self.repo, name).write_text(content)
|
||||
git(self.repo, "add", "-A")
|
||||
git(self.repo, "config", "filter.planted.clean", f"touch {self.repo}/ran; cat")
|
||||
pathlib.Path(self.repo, "ran").unlink(missing_ok=True)
|
||||
# A stat-dirty index entry, as extracting an archive leaves, is what makes `git status` re-run the filter.
|
||||
os.utime(pathlib.Path(self.repo, "todo.md"), (1, 1))
|
||||
ran = hook({"cwd": self.repo, "tool_input": {"command": "git commit -m x"}, "tool_name": "Bash"}, self.repo)
|
||||
self.assertEqual(ran.returncode, 2, ran.stderr)
|
||||
self.assertFalse(pathlib.Path(self.repo, "ran").exists())
|
||||
|
||||
def test_a_symlinked_log_is_refused(self):
|
||||
target = pathlib.Path(self.repo, "elsewhere")
|
||||
pathlib.Path(self.repo, ".git", "rule-overrides.tsv").symlink_to(target)
|
||||
content = "# rule-override image-pin: the vendor tags no patch versions\nFROM vendor/tool:2\n"
|
||||
ran = hook({"cwd": self.repo, "tool_input": {"file_path": f"{self.repo}/Dockerfile", "content": content}, "tool_name": "Write"}, self.repo)
|
||||
self.assertEqual(ran.returncode, 2)
|
||||
self.assertFalse(target.exists())
|
||||
|
||||
def test_a_malformed_override_is_named(self):
|
||||
ran = hook({"cwd": self.repo, "tool_input": {"command": f"git commit -m a -m b -m '{TRAILER}' # rule-override no-ai-attribution: quotes it # rule-override commit-oneline: x"}, "tool_name": "Bash"}, self.repo)
|
||||
self.assertIn("`rule-override commit-oneline: x` names no rule below", ran.stderr)
|
||||
|
||||
def test_a_missing_field_breaks_nothing(self):
|
||||
for given in [{"command": None}, {"content": None, "file_path": f"{self.repo}/a.md"}, {"edits": [None], "file_path": f"{self.repo}/a.md"}]:
|
||||
with self.subTest(given):
|
||||
tool = "Bash" if "command" in given else "Write" if "content" in given else "MultiEdit"
|
||||
self.assertEqual(hook({"cwd": self.repo, "tool_input": given, "tool_name": tool}, self.repo).returncode, 0)
|
||||
|
||||
def test_unreadable_input_does_not_block(self):
|
||||
for given in ["{", json.dumps({"cwd": ".", "tool_input": None, "tool_name": "Bash"})]:
|
||||
with self.subTest(given):
|
||||
self.assertEqual(subprocess.run([str(HOOK)], capture_output=True, env=isolated_env(), input=given, text=True).returncode, 1)
|
||||
|
||||
def test_help_lists_every_rule(self):
|
||||
helped = subprocess.run([str(HOOK), "--help"], capture_output=True, check=True, env=isolated_env(), text=True).stdout
|
||||
for rule in ["action-pin", "commit-one-line", "ignorefile-sorted", "image-pin", "no-ai-attribution", "todo-rank-check"]:
|
||||
self.assertIn(f" {rule}\n The rule: ", helped)
|
||||
@@ -0,0 +1,25 @@
|
||||
import hashlib
|
||||
import pathlib
|
||||
|
||||
from rule_hook.rules import Breach
|
||||
from failure import Failure
|
||||
from rule_hook.git import git
|
||||
import rank_todo
|
||||
|
||||
|
||||
def todo_breaches(directory: str) -> list[Breach]:
|
||||
top = git(directory, "rev-parse", "--show-toplevel")
|
||||
if isinstance(top, Failure) or not (pathlib.Path(top) / "todo.md").is_file():
|
||||
return []
|
||||
todo = pathlib.Path(top) / "todo.md"
|
||||
return [Breach("todo-rank-check", line, top) for line in rank_todo.check_failures(todo)] if changed(top, todo) else []
|
||||
|
||||
|
||||
def changed(top: str, todo: pathlib.Path) -> bool:
|
||||
"""Whether todo.md differs from the index or the index from HEAD: any change, staged or not, since the hook runs before a `git add` earlier in the same command."""
|
||||
# Hashed here, never by `git status`, which would run a clean filter the checkout's own config names before the call is allowed.
|
||||
staged, committed = git(top, "rev-parse", ":todo.md"), git(top, "rev-parse", "HEAD:todo.md")
|
||||
algorithm = git(top, "rev-parse", "--show-object-format")
|
||||
content = todo.read_bytes()
|
||||
worktree = hashlib.new("sha1" if isinstance(algorithm, Failure) else algorithm, b"blob %d\0" % len(content) + content).hexdigest()
|
||||
return isinstance(staged, Failure) or staged != worktree or staged != committed
|
||||
@@ -0,0 +1,68 @@
|
||||
"""A shell command's simple commands, each as its words and the directory it runs in."""
|
||||
import dataclasses
|
||||
import posixpath
|
||||
import re
|
||||
import shlex
|
||||
|
||||
HEREDOC = re.compile(r"<<-?[ \t]*([\"']?)([A-Za-z_]\w*)\1[^\n]*\n.*?^[ \t]*\2[ \t]*$", re.DOTALL | re.MULTILINE)
|
||||
ASSIGNMENT = re.compile(r"[A-Za-z_][A-Za-z0-9_]*=")
|
||||
OPERATOR = set("\n();&|<>")
|
||||
# A quoted string or an escape is taken whole, so a # inside one starts no comment; a comment starts a word.
|
||||
PIECE = re.compile(r"""'[^']*'|"(?:\\.|[^"\\])*"|\\.|(?<![^\s;&|()])#[^\n]*""", re.DOTALL)
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Simple:
|
||||
words: list[str]
|
||||
directory: str
|
||||
|
||||
|
||||
def simple_commands(command: str, cwd: str, home: str) -> list[Simple]:
|
||||
"""Each simple command, without leading variable assignments or redirect targets, in the directory `cd` left it in."""
|
||||
directory = cwd
|
||||
found = []
|
||||
for words in segments(command):
|
||||
if words[0] == "cd" and len(words) == 2:
|
||||
directory = resolved(directory, words[1], home)
|
||||
found.append(Simple(words, directory))
|
||||
return found
|
||||
|
||||
|
||||
def segments(command: str) -> list[list[str]]:
|
||||
text = uncommented(HEREDOC.sub(lambda heredoc: heredoc.group(0).split("\n", 1)[0], command))
|
||||
tokens = lexed(text)
|
||||
if tokens is None:
|
||||
# One unbalanced quote should not hide the other lines.
|
||||
tokens = [token for line in text.splitlines() for token in (lexed(line) or []) + ["\n"]]
|
||||
found: list[list[str]] = [[]]
|
||||
target = False
|
||||
for token in tokens:
|
||||
if target:
|
||||
target = False
|
||||
elif set(token) <= OPERATOR and token:
|
||||
# A redirect's target is not an operand.
|
||||
target = "<" in token or ">" in token
|
||||
found.append([])
|
||||
elif found[-1] or not ASSIGNMENT.match(token):
|
||||
found[-1].append(token)
|
||||
return [words for words in found if words]
|
||||
|
||||
|
||||
def lexed(text: str) -> list[str] | None:
|
||||
lexer = shlex.shlex(text, posix=True, punctuation_chars="();<>|&\n")
|
||||
lexer.commenters = ""
|
||||
lexer.whitespace = " \t\r"
|
||||
lexer.whitespace_split = True
|
||||
try:
|
||||
return list(lexer)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def uncommented(text: str) -> str:
|
||||
"""The text without its comments; shlex's own would also swallow the line break that ends one, joining two commands."""
|
||||
return PIECE.sub(lambda piece: "" if piece.group(0).startswith("#") else piece.group(0), text)
|
||||
|
||||
|
||||
def resolved(base: str, path: str, home: str) -> str:
|
||||
return posixpath.normpath(posixpath.join(base, home + path[1:] if path == "~" or path.startswith("~/") else path))
|
||||
Executable
+164
@@ -0,0 +1,164 @@
|
||||
#!/usr/bin/env python3
|
||||
import dataclasses
|
||||
import datetime
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
CYAN = "\033[36m"
|
||||
DIM = "\033[2m"
|
||||
GREEN = "\033[32m"
|
||||
RED = "\033[31m"
|
||||
RESET = "\033[0m"
|
||||
YELLOW = "\033[33m"
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Limit:
|
||||
percent: float
|
||||
resets_at: datetime.datetime | None
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Status:
|
||||
context_percent: float | None
|
||||
context_size: float | None
|
||||
context_used: float | None
|
||||
directory: str
|
||||
five_hour: Limit | None
|
||||
model: str
|
||||
seven_day: Limit | None
|
||||
|
||||
|
||||
def field(raw: object, *path: str) -> object:
|
||||
for key in path:
|
||||
if not isinstance(raw, dict):
|
||||
return None
|
||||
raw = raw.get(key)
|
||||
return raw
|
||||
|
||||
|
||||
def number(raw: object, *path: str) -> float | None:
|
||||
found = field(raw, *path)
|
||||
if isinstance(found, bool) or not isinstance(found, (int, float)):
|
||||
return None
|
||||
return found if isinstance(found, int) or math.isfinite(found) else None
|
||||
|
||||
|
||||
def text(raw: object, *path: str) -> str:
|
||||
found = field(raw, *path)
|
||||
return found if isinstance(found, str) else ""
|
||||
|
||||
|
||||
def instant(epoch: float | None, zone: datetime.tzinfo | None) -> datetime.datetime | None:
|
||||
if epoch is None:
|
||||
return None
|
||||
try:
|
||||
return datetime.datetime.fromtimestamp(round(epoch), datetime.timezone.utc).astimezone(zone)
|
||||
except (OSError, OverflowError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def limit(raw: dict[str, object], window: str, zone: datetime.tzinfo | None) -> Limit | None:
|
||||
percent = number(raw, "rate_limits", window, "used_percentage")
|
||||
return None if percent is None else Limit(percent, instant(number(raw, "rate_limits", window, "resets_at"), zone))
|
||||
|
||||
|
||||
# The input's fields: https://code.claude.com/docs/en/statusline
|
||||
# A field that is absent, null or of the wrong type is left out silently: many are absent in normal use (API users get no rate_limits).
|
||||
def parse(raw: dict[str, object], zone: datetime.tzinfo | None) -> Status:
|
||||
return Status(
|
||||
context_percent=number(raw, "context_window", "used_percentage"),
|
||||
context_size=number(raw, "context_window", "context_window_size"),
|
||||
context_used=number(raw, "context_window", "total_input_tokens"),
|
||||
directory=text(raw, "workspace", "current_dir") or text(raw, "cwd"),
|
||||
five_hour=limit(raw, "five_hour", zone),
|
||||
model=text(raw, "model", "display_name"),
|
||||
seven_day=limit(raw, "seven_day", zone),
|
||||
)
|
||||
|
||||
|
||||
def usage_color(percent: int) -> str:
|
||||
return RED if percent >= 80 else YELLOW if percent >= 50 else GREEN
|
||||
|
||||
|
||||
def humanize_tokens(count: int) -> str:
|
||||
if count >= 1_000_000:
|
||||
return f"{count // 1_000_000}.{count % 1_000_000 // 100_000}M"
|
||||
if count >= 1000:
|
||||
return f"{count // 1000}k"
|
||||
return str(count)
|
||||
|
||||
|
||||
def reset_suffix(at: datetime.datetime, now: datetime.datetime) -> str:
|
||||
seconds = max(0, int((at - now).total_seconds()))
|
||||
if seconds >= 86400:
|
||||
left = f"{seconds // 86400}d{seconds % 86400 // 3600}h"
|
||||
elif seconds >= 3600:
|
||||
left = f"{seconds // 3600}h{seconds % 3600 // 60}m"
|
||||
else:
|
||||
left = f"{seconds // 60}m"
|
||||
# %a stays English on every machine; setlocale would make this read process-wide state.
|
||||
clock = at.strftime("%H:%M" if at.date() == now.date() else "%a %H:%M")
|
||||
return f" {DIM}{left} left ({clock}){RESET}"
|
||||
|
||||
|
||||
def usage_segment(label: str, percent: float, suffix: str) -> str:
|
||||
rounded = round(percent)
|
||||
return f"{DIM}{label}{RESET} {usage_color(rounded)}{rounded}%{RESET}{suffix}"
|
||||
|
||||
|
||||
def limit_segment(label: str, window: Limit | None, now: datetime.datetime) -> list[str]:
|
||||
if window is None:
|
||||
return []
|
||||
return [usage_segment(label, window.percent, "" if window.resets_at is None else reset_suffix(window.resets_at, now))]
|
||||
|
||||
|
||||
def render(status: Status, branch: str, home: str, now: datetime.datetime) -> str:
|
||||
where = []
|
||||
if status.directory:
|
||||
shown = status.directory
|
||||
if home and (shown == home or shown.startswith(home + "/")):
|
||||
shown = "~" + shown[len(home):]
|
||||
where.append(f"{CYAN}{shown}{RESET}")
|
||||
if branch:
|
||||
where.append(f"{DIM}{branch}{RESET}")
|
||||
if status.model:
|
||||
where.append(f"{DIM}{status.model}{RESET}")
|
||||
|
||||
load = []
|
||||
if status.context_percent is not None:
|
||||
used, size = status.context_used, status.context_size
|
||||
tokens = "" if used is None or size is None else f" {DIM}{humanize_tokens(int(used))}/{humanize_tokens(int(size))}{RESET}"
|
||||
load.append(usage_segment("ctx", status.context_percent, tokens))
|
||||
load += limit_segment("5h", status.five_hour, now) + limit_segment("7d", status.seven_day, now)
|
||||
|
||||
return "\n".join(f"{DIM} | {RESET}".join(row) for row in (where, load) if row)
|
||||
|
||||
|
||||
def current_branch(where: str) -> str:
|
||||
if not where:
|
||||
return ""
|
||||
try:
|
||||
found = subprocess.run(["git", "-C", where, "branch", "--show-current"], errors="replace", stderr=subprocess.DEVNULL, stdout=subprocess.PIPE, text=True)
|
||||
except OSError:
|
||||
return ""
|
||||
return found.stdout.strip() if found.returncode == 0 else ""
|
||||
|
||||
|
||||
def main() -> str:
|
||||
try:
|
||||
raw = json.load(sys.stdin)
|
||||
except ValueError:
|
||||
raw = None
|
||||
if not isinstance(raw, dict):
|
||||
return f"{RED}warning: statusline.py's input is not a JSON object{RESET}"
|
||||
# Zone None: astimezone converts to the machine's own zone, daylight saving included.
|
||||
status = parse(raw, None)
|
||||
return render(status, current_branch(status.directory), os.environ.get("HOME", ""), datetime.datetime.now().astimezone())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.stdout.write(main())
|
||||
@@ -1,25 +0,0 @@
|
||||
import pathlib
|
||||
import re
|
||||
import subprocess
|
||||
import unittest
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[1]
|
||||
CITATION = re.compile(r'`?CLAUDE\.md`? → ("[^"]+"(?:,? (?:and )?"[^"]+")*)')
|
||||
HEADING = re.compile(r"^#+ (.+?)(?: \(.*\))?$", re.MULTILINE)
|
||||
LEAD = re.compile(r"^(?:- )?\*\*(.+?)(?:\*\*|[:.](?=\*\*| )| —)", re.MULTILINE)
|
||||
NAME = re.compile(r'"([^"]+)"')
|
||||
STRAY = re.compile(r'CLAUDE\.md(?!`? → ")[^\n"]{1,5}"')
|
||||
|
||||
|
||||
class Citations(unittest.TestCase):
|
||||
def test_every_citation_names_a_heading_then_headings_or_bold_leads_of_claude_md(self):
|
||||
text = (ROOT / "CLAUDE.md").read_text()
|
||||
headings = set(HEADING.findall(text))
|
||||
leads = headings | set(LEAD.findall(text))
|
||||
tracked = subprocess.run(["git", "ls-files", "-z"], capture_output=True, check=True, cwd=ROOT, text=True).stdout.split("\0")
|
||||
texts = [(path, (ROOT / path).read_text()) for path in filter(None, tracked)]
|
||||
self.assertEqual([f"{path}: {stray}" for path, text in texts for stray in STRAY.findall(text)], [], 'spell a citation `CLAUDE.md` → "Vocabulary"')
|
||||
cited = [(path, NAME.findall(run)) for path, text in texts for run in CITATION.findall(text)]
|
||||
self.assertTrue(cited)
|
||||
unresolved = [(path, name) for path, names in cited for i, name in enumerate(names) if name not in (headings if i == 0 else leads)]
|
||||
self.assertEqual([f"{path}: {name}" for path, name in unresolved], [], "the first name is a heading of CLAUDE.md, each later one a heading or a bold lead")
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user