Compare commits
661 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 447668865d | |||
| 5a56fff040 | |||
| bd64bd59c2 | |||
| dd9dda8f69 | |||
| e3566f694a | |||
| 21d507f0c5 | |||
| 504aa31bdb | |||
| 387a5ce506 | |||
| 8d2a1cf9fd | |||
| 9df08bd41e | |||
| f20d1799c3 | |||
| 1b7d5244b1 | |||
| e923534fc9 | |||
| c8d97fb516 | |||
| e92bde2bd3 | |||
| 7a4ac91597 | |||
| b68b1b60ac | |||
| 2317ed4c90 | |||
| 65a0433deb | |||
| ad6e6898c2 | |||
| 22e2c22b8f | |||
| e452b0c55e | |||
| dcbdc970a6 | |||
| 0b1289cb33 | |||
| 6f98a1855b | |||
| d70cbca594 | |||
| 6733615e1c | |||
| 92afe2ac08 | |||
| fa2024c09f | |||
| f781ac611b | |||
| aebd92de43 | |||
| bf8b642ead | |||
| f0e14f3fdf | |||
| 4764d3d522 | |||
| ef12b17d8b | |||
| 9f044044ab | |||
| a85b0a44d5 | |||
| a99a98c504 | |||
| dceff3c985 | |||
| 1a83c13eb9 | |||
| 39dd51bb44 | |||
| 66a12bd806 | |||
| 72a63c5ade | |||
| a0780ca0bd | |||
| 5732b898a6 | |||
| a225166956 | |||
| 7c42f038ac | |||
| f58fe5a9db | |||
| 28b64042ba | |||
| 061b32dd66 | |||
| 061118be0b | |||
| 28da11dd8d | |||
| a351ba8a33 | |||
| a4071f59ce | |||
| 372cfa7535 | |||
| 2f03ba1a77 | |||
| 5b615ef46e | |||
| 058ec1da4f | |||
| 038ef6e732 | |||
| a81f878f92 | |||
| aa9a4cb78b | |||
| 3b69ced357 | |||
| 545ab3ab37 | |||
| 261fb1d215 | |||
| 3f8e175229 | |||
| 6d4d37948c | |||
| 37f11f720b | |||
| 6e481939bf | |||
| 23730a991d | |||
| db904b9659 | |||
| 0b02f8d376 | |||
| 1f4a5e81ef | |||
| f6594bc048 | |||
| c5fdaf43f6 | |||
| cb48719493 | |||
| c3ae228639 | |||
| 10fb7a21bc | |||
| d1f2004e77 | |||
| 851d7d7c79 | |||
| 0782ac6721 | |||
| 7285b2bb27 | |||
| 277a52f0cb | |||
| 1d6f7328fb | |||
| a6fb79dabb | |||
| aa8b12b896 | |||
| f690eb2477 | |||
| 2ba78bb3c9 | |||
| 88d21b38a5 | |||
| 35b3c90db9 | |||
| 20c231457d | |||
| b37f34b211 | |||
| 77ef932576 | |||
| 682181bc3b | |||
| fbdb6c9f08 | |||
| 64023b5bcd | |||
| 71d5e82d3a | |||
| 6150c5289e | |||
| 8c3298f673 | |||
| 64d399f7f5 | |||
| 7042a75266 | |||
| b189e797fc | |||
| b8ab075663 | |||
| 0acb1286a0 | |||
| cf80a9d925 | |||
| 8468cc8ee0 | |||
| 6de74f0f63 | |||
| c5e458c3de | |||
| e7dc6a9956 | |||
| 1f9536d664 | |||
| bb152a1964 | |||
| 6cff688951 | |||
| e2033abbaf | |||
| c959471930 | |||
| 486c5a9fc6 | |||
| bd98bb40ee | |||
| 640b213c0b | |||
| ef47283d12 | |||
| 9e08a2b5c6 | |||
| bb6224bbb2 | |||
| a8e669d683 | |||
| c29f9e6fd1 | |||
| 0b002b0d10 | |||
| 919124eb00 | |||
| 87f41071f2 | |||
| 2fefab6b2e | |||
| 52ba0591fa | |||
| 1ba097d17c | |||
| 2e4318bfc4 | |||
| 057808ad25 | |||
| 5805bd2287 | |||
| 4008c60e76 | |||
| 79c66db183 | |||
| d08926b552 | |||
| b223adfd26 | |||
| 539a7ec8d5 | |||
| d6ec236771 | |||
| 136adb6a51 | |||
| 16b1ffc05e | |||
| cd2f487df2 | |||
| 6b23808127 | |||
| 18c284c1fe | |||
| 3e8f9deef6 | |||
| f46809693b | |||
| 4b783ac67b | |||
| e32accd08c | |||
| e419bc5cb0 | |||
| 8cdbff5fba | |||
| 028d722b94 | |||
| 31fb1a0093 | |||
| 68c44f3128 | |||
| 0f60cac9ba | |||
| 8974031c2d | |||
| 10abbaff9f | |||
| f6f2ec86b1 | |||
| c554746f8e | |||
| 8e1d166534 | |||
| 4e5902fcc5 | |||
| 591db4a33e | |||
| b9963df226 | |||
| 616a1119bc | |||
| 57c28f6571 | |||
| e7dbff791a | |||
| 7d6d5b274f | |||
| 86a4523d9f | |||
| eb17a4080d | |||
| c0b31427c0 | |||
| cf11a0f866 | |||
| b57dc461c6 | |||
| 9e4aebb3ff | |||
| b78accf55a | |||
| 26f1ef018d | |||
| 2f8760b7c6 | |||
| 46c9dbe131 | |||
| 41b8cc9a2d | |||
| 02f69a45dd | |||
| 84e6c3e343 | |||
| 703a58279a | |||
| d459c2315b | |||
| 45b2444a70 | |||
| 2f10b900b5 | |||
| 756b42934b | |||
| 55fc24401f | |||
| ec9e2098b8 | |||
| c2c9faa31f | |||
| b9e597398e | |||
| f0ece378c0 | |||
| f429e256de | |||
| 666d681562 | |||
| 20325bf352 | |||
| 190378b05f | |||
| 723189bc2d | |||
| 5f91fe6649 | |||
| 8a4c2e1b56 | |||
| 4c929e66a9 | |||
| 3efc6ca391 | |||
| 7cf6924e2e | |||
| ed2e12d99d | |||
| 1b8d65dbf6 | |||
| 3dda22672f | |||
| b79105a207 | |||
| 0e64d4b2c9 | |||
| a588075a4a | |||
| 18b52f66a1 | |||
| 628dce646f | |||
| 722f76b299 | |||
| a94e4c78b8 | |||
| d7c4873481 | |||
| a558ef09b7 | |||
| d1230a515e | |||
| 14e323ef01 | |||
| 4a4bebf87b | |||
| eb3abd12a0 | |||
| a3b2923002 | |||
| 64d4a2394d | |||
| 453a8e3b94 | |||
| 7eb2a91a13 | |||
| 10495b8852 | |||
| 2407689747 | |||
| 6f58a0e5c2 | |||
| 1dd65de56f | |||
| 33645b00e4 | |||
| 8e0c2d50f8 | |||
| b580d3991e | |||
| 250b29bc66 | |||
| 651695a695 | |||
| b7261987ad | |||
| d08a128d0f | |||
| 80270c6b17 | |||
| 1f8edb8e2e | |||
| b57704d237 | |||
| d18b064e43 | |||
| 7665087e1e | |||
| 7c3800337a | |||
| 4fbe529cfe | |||
| 10de59bc08 | |||
| 64ca83ac94 | |||
| 84779764b2 | |||
| f5f6b660f2 | |||
| 5de35893cd | |||
| dec19c5595 | |||
| a8aefd2566 | |||
| 7c7a398e42 | |||
| 185efb9bea | |||
| 50dcb55d51 | |||
| 7c97005154 | |||
| d48344aa6d | |||
| f391e52ac3 | |||
| 3ae89c3acf | |||
| 3fc6790bee | |||
| 8bee9cb765 | |||
| a261669735 | |||
| 583b85eea8 | |||
| d789f0fd12 | |||
| 3f266751a3 | |||
| e37af925e8 | |||
| 04d42a40eb | |||
| 12f5c18d46 | |||
| b20dc28f5b | |||
| 1a1da8f94d | |||
| bff8872e9b | |||
| 531c4dae25 | |||
| 747f28adf5 | |||
| dcc7149a02 | |||
| 48f9c86dd2 | |||
| 80d9e9656f | |||
| 7c0e50b52e | |||
| 456991a722 | |||
| c4cc7c11b5 | |||
| 2096fe2c7e | |||
| d7dd3dc289 | |||
| 0df7377a2b | |||
| 243cbe83b9 | |||
| 7518bc7f77 | |||
| dc79ebf828 | |||
| cdd22de313 | |||
| a81047f5f6 | |||
| 646f7a7df5 | |||
| 21d8cab43f | |||
| 70cc5c9a0a | |||
| a300dc32b7 | |||
| 1bd192ecc7 | |||
| 92f8204702 | |||
| 9a5c24aa68 | |||
| 4447aabbb3 | |||
| 6b6b82803d | |||
| 58939766d3 | |||
| 3d51ebc5df | |||
| 2296cb9119 | |||
| 13e3a71367 | |||
| e4145b8e1d | |||
| fda48ac44c | |||
| ef57520cf3 | |||
| 5a495fd58e | |||
| c7139106c7 | |||
| fcf119ffec | |||
| 2ea929a8be | |||
| e787286a48 | |||
| 8587e4f160 | |||
| 353058defd | |||
| 6bb7b28b92 | |||
| eafcefe0da | |||
| 1605d80cc5 | |||
| f091d8b698 | |||
| 390d1f1f83 | |||
| 3081d50f0f | |||
| 8e0060be08 | |||
| 9e6715e0bf | |||
| 6e050148ef | |||
| 50edcca42f | |||
| 2a961f267c | |||
| 1bfc91559a | |||
| 78077a5896 | |||
| aa279a319a | |||
| d0758a0735 | |||
| e6223f7126 | |||
| ab93b7356e | |||
| dba2e74321 | |||
| 49e86fdbb9 | |||
| cfa16c65b5 | |||
| 6703d48800 | |||
| bf6300bcd5 | |||
| da17ed5c32 | |||
| 69e1c5f3f7 | |||
| 68c2cdfa8b | |||
| 56e9049938 | |||
| bc242b2998 | |||
| ec2a16b371 | |||
| 2fbd504734 | |||
| fc13a1100e | |||
| 2911d3f4cc | |||
| 207ba120b5 | |||
| 862137b1be | |||
| 8ef6dcb7a8 | |||
| 306b040b46 | |||
| eec084a4e8 | |||
| baefcbb037 | |||
| 0202bc60f9 | |||
| e652e7aed7 | |||
| 5bc3247aec | |||
| 2bba66ac0a | |||
| 1ed305f1e2 | |||
| 3a8e4e6f75 | |||
| 07369f1164 | |||
| 1601c92f09 | |||
| ca32d0d446 | |||
| e70f61dad4 | |||
| 2d07bbff63 | |||
| 9c9f26ba57 | |||
| fc7c2301b5 | |||
| 612ba0d4e4 | |||
| bb60e9dffd | |||
| 5a9b084bfb | |||
| 489465c56f | |||
| 9a1adcef42 | |||
| 917166e186 | |||
| a1089442c4 | |||
| c8f53bbcc4 | |||
| bdc1d463cb | |||
| 5d430dbd9a | |||
| bfdb886ef7 | |||
| 9bed420f21 | |||
| 2e518e0bcc | |||
| 9a28cba0be | |||
| ef454d263e | |||
| d0a50abc8b | |||
| f36eee0ec7 | |||
| 9eb26ed727 | |||
| d41d42baa5 | |||
| c9bfc96aaf | |||
| f0d4740367 | |||
| 1a433205a6 | |||
| 80a90a803e | |||
| 0462980bd4 | |||
| 2b0133af69 | |||
| 3eb3217a49 | |||
| 5eafe960e1 | |||
| a3aad5ead1 | |||
| 4c6194255f | |||
| 5866a0497a | |||
| 8510c06b2f | |||
| 686e2dcd42 | |||
| d44024d159 | |||
| e9cc88ed27 | |||
| ab081dd33f | |||
| 83701e20aa | |||
| 6cdace6ae3 | |||
| ca5edc2ae3 | |||
| 5bf3cba602 | |||
| ef1df926c4 | |||
| 6e0fda4ded | |||
| d0f6c806a3 | |||
| 6694d54e52 | |||
| e6363d1c56 | |||
| ac2ed4095a | |||
| c07e582212 | |||
| e15f96fcd8 | |||
| 63392cea66 | |||
| eae4ee9fb1 | |||
| 6479337ab1 | |||
| d1ca16e9fc | |||
| 1f0a046dd4 | |||
| c7a02c3be7 | |||
| e3933a92ff | |||
| 28a3f9c5e9 | |||
| ee6ef24d59 | |||
| a5a8ad5522 | |||
| ac33c733c7 | |||
| e074b8b235 | |||
| ec95acab64 | |||
| 1d8dd330bb | |||
| a4f81a1024 | |||
| f6f84e534b | |||
| 2b1d3707c8 | |||
| d361312edc | |||
| f8a51728a3 | |||
| 4fa90ee01a | |||
| 78843560cf | |||
| b6a3dc43a8 | |||
| 3928d84acb | |||
| 52b0e6dbf9 | |||
| d96f4a138a | |||
| 3adf58c619 | |||
| 8df46e3a85 | |||
| 27480e586f | |||
| 308434f826 | |||
| 55a062bbdc | |||
| 051e9a08d5 | |||
| 8ffe26a33d | |||
| 9207566328 | |||
| 3f6f0456fb | |||
| fed14bf2dd | |||
| fdd48bb1cd | |||
| dbaf32fc74 | |||
| 32eb16cd20 | |||
| 023380f5a5 | |||
| e291f6ca3d | |||
| 062af261d8 | |||
| 2760c50915 | |||
| d9fb90ee03 | |||
| 1f380af695 | |||
| e7f5443688 | |||
| c4a4f40aa6 | |||
| 2bb61f385a | |||
| 84e34b8e23 | |||
| 3229045af9 | |||
| 4b2d4a1734 | |||
| 44fa8a7fe6 | |||
| 96834412c7 | |||
| 831b9c63b6 | |||
| eddc5bec95 | |||
| e1239dfd19 | |||
| 81a07fe685 | |||
| 4e1df27698 | |||
| 528eee1996 | |||
| 2890399e45 | |||
| 24173eb17f | |||
| 5b536afdf9 | |||
| fc24e9bae2 | |||
| b120faacad | |||
| 2fbbc08094 | |||
| 89bbc9de18 | |||
| 7a30b818b7 | |||
| e8898534c1 | |||
| 9e6c4fc8c2 | |||
| e71f5b9406 | |||
| dcad6fc5b7 | |||
| 602a5fac16 | |||
| 1c503e8818 | |||
| 4474182174 | |||
| b39582cb39 | |||
| fdb723094c | |||
| 815c64cbe1 | |||
| eaf2264a75 | |||
| 59344de5bc | |||
| a025534de6 | |||
| d2a196eba5 | |||
| 85cbd6b5a5 | |||
| 207cd7c3eb | |||
| c9b3c7e172 | |||
| 892cae1b46 | |||
| dcbc0bd06b | |||
| 410ae7695c | |||
| 2972f1c404 | |||
| 75c2912db4 | |||
| d60314d105 | |||
| c65207ad31 | |||
| 1fa39a6b10 | |||
| 22525c4af4 | |||
| 312d5cff44 | |||
| 712dabd664 | |||
| 10a283a5eb | |||
| 9a439a83bd | |||
| b6dd8bc20d | |||
| b9cbb06082 | |||
| a93b15ed61 | |||
| e40e57c46e | |||
| f566d1ccd5 | |||
| 33f9960c1e | |||
| 46ccea1322 | |||
| c89dd87a18 | |||
| ec86fee39f | |||
| 5ba8920dbf | |||
| 4cf3c2bd8c | |||
| 45004e1b0b | |||
| 786860683e | |||
| 0472ec0452 | |||
| 495184b9c6 | |||
| 50541c32fd | |||
| ecbb7a7cda | |||
| 8b3a5a32a3 | |||
| ee340db912 | |||
| f9615cb3b0 | |||
| 46b79e7803 | |||
| 6500754517 | |||
| dc2a37048d | |||
| 2057d8f02f | |||
| 54cb4d6948 | |||
| 86d6a2bb3f | |||
| dd2db8fb52 | |||
| 7d9fd54c80 | |||
| 7304700e7a | |||
| 16b706e16c | |||
| a6fcc6e2bc | |||
| 3eea390b1f | |||
| 6df1833eb7 | |||
| ba4a00d6b7 | |||
| 8ffb1979ea | |||
| 0022ced569 | |||
| e91221cab5 | |||
| dcc47e745c | |||
| d9d007fa7a | |||
| 3be800cb46 | |||
| 084730cbe0 | |||
| c98b3e2e21 | |||
| 49004f22a2 | |||
| 13672afc26 | |||
| de8d602d0c | |||
| 23dac2c1d1 | |||
| 5747d2792a | |||
| c3885c0d1b | |||
| df624524b7 | |||
| 53e87d1051 | |||
| 57cd5f76a4 | |||
| e57309a415 | |||
| 988f608bde | |||
| b30c91aafc | |||
| 4438ab04f3 | |||
| a9b617f9e5 | |||
| cf4072f69f | |||
| 4625b805eb | |||
| 3110e03226 | |||
| e077fffade | |||
| 95aa2b3477 | |||
| 8ab8c09c89 | |||
| ed4689872d | |||
| 40201803ae | |||
| 58252f8948 | |||
| a80bb6cc66 | |||
| 14c8e7f012 | |||
| 11b9ec313d | |||
| 9ddbee8094 | |||
| 3f8f30ab2f | |||
| e3704cf0ab | |||
| 126ac9e4fd | |||
| f634732388 | |||
| b3f6721ee9 | |||
| 354b5122ab | |||
| 1905ed5f2f | |||
| 70b5b4064e | |||
| 717f56d319 | |||
| 0f3434f2c5 | |||
| c0dce6c887 | |||
| 5d4f9d4c0b | |||
| 2c67b4f2b3 | |||
| db2b4a0f30 | |||
| 50b9daae1a | |||
| d6152efcb2 | |||
| c5fe3c76a9 | |||
| 27d8632e99 | |||
| 4209c13380 | |||
| c33c955aa2 | |||
| 79cce77762 | |||
| be855a7a03 | |||
| 125018f2aa | |||
| 24913fef1c | |||
| 80059eb684 | |||
| 81bd8e6705 | |||
| 9d68fd79f6 | |||
| c1b6380f0f | |||
| 24549589ec | |||
| 50fdd9e66d | |||
| 886c864521 | |||
| 5e736d6eaa | |||
| d2c13d42be | |||
| e2c1dd8043 | |||
| f319a96e7e | |||
| 12909f233d | |||
| 149108e8d8 | |||
| b1b798371d | |||
| 614c17c3d1 | |||
| 152972d84b | |||
| d1b0fe3a44 | |||
| 7f02856eba | |||
| 32fa9debc7 | |||
| 7ea23b15c5 | |||
| 5be5b6bd82 | |||
| fb4f8161cb | |||
| 678eac7a15 | |||
| 5c4b9746ff | |||
| 6474a43670 | |||
| fbff90d3e4 | |||
| 136422031a | |||
| b4dcfa27af | |||
| 56b5924902 | |||
| e07c20bd60 | |||
| 5c65e725fc | |||
| 66c98281a6 | |||
| d4cf6e7fe7 | |||
| f36e6bc576 | |||
| dd02671074 | |||
| b04e681a08 | |||
| 9c6578e404 | |||
| 2eef4340e1 | |||
| 661170cc4a | |||
| d1c1e769b3 | |||
| 5725baefab | |||
| 8ec835e36b | |||
| e0411fa140 | |||
| 0e718b1c2d | |||
| 9f11932aa7 | |||
| 44c8e5e73d | |||
| 98bea20feb | |||
| 7c50e52a1b | |||
| 3272387fc5 | |||
| 79bed9e819 | |||
| 5cc4346081 | |||
| 72ac52947a | |||
| a4de9ff114 | |||
| 40bb676399 | |||
| d95c1f1451 | |||
| ebc834f1d4 | |||
| 127439bb48 | |||
| e43a4923b5 | |||
| fc4d63c041 | |||
| 6d80efc05d | |||
| 7d3784c91b | |||
| b05c8dbc75 | |||
| ecba8a8ea6 | |||
| ce680b7736 | |||
| 7069fd1770 | |||
| 439a35466a | |||
| 6b1cfb05dc | |||
| e1578fd1ed | |||
| 9392769b53 | |||
| 4a3877c77f | |||
| dc621f928e | |||
| 5d326e2d9b | |||
| 40faeda4ab | |||
| e28aeab828 | |||
| 14b8a8a5a2 | |||
| 1bff4acb8d |
@@ -0,0 +1 @@
|
||||
/settings.json filter=settings
|
||||
+13
-3
@@ -4,6 +4,7 @@
|
||||
# un-ignore authored config only.
|
||||
*
|
||||
|
||||
!.gitattributes
|
||||
!.gitignore
|
||||
!AGENTS.md
|
||||
!CHANGELOG.md
|
||||
@@ -17,6 +18,10 @@
|
||||
!agents/
|
||||
!agents/*.md
|
||||
!bin/
|
||||
!bin/chunk-preflight
|
||||
!bin/chunk_pick.py
|
||||
!bin/chunk_preflight/
|
||||
!bin/chunk_preflight/*.py
|
||||
!bin/claude_code/
|
||||
!bin/claude_code/*.py
|
||||
!bin/comprehension_history.py
|
||||
@@ -47,6 +52,11 @@
|
||||
!bin/reading_cost/*.py
|
||||
!bin/repo_checks/
|
||||
!bin/repo_checks/*.py
|
||||
!bin/review-replay
|
||||
!bin/review_folder.py
|
||||
!bin/review_passes.py
|
||||
!bin/review_replay/
|
||||
!bin/review_replay/*.py
|
||||
!bin/round_titles.py
|
||||
!bin/rule-hook
|
||||
!bin/routing_figures/
|
||||
@@ -58,10 +68,8 @@
|
||||
!bin/score-outcomes
|
||||
!bin/score_outcomes/
|
||||
!bin/score_outcomes/*.py
|
||||
!bin/settings_filter.py
|
||||
!bin/shell_command.py
|
||||
!bin/stability-replay
|
||||
!bin/stability_replay/
|
||||
!bin/stability_replay/*.py
|
||||
!bin/statusline.py
|
||||
!bin/subagent-rung
|
||||
!bin/subagent_rung/
|
||||
@@ -88,4 +96,6 @@
|
||||
!workflow-bench/bench.py
|
||||
!workflow-bench/compare-prompt.md
|
||||
!workflow-bench/compare.py
|
||||
!workflow-bench/review_git.py
|
||||
!workflow-bench/run-prompt.md
|
||||
!workflow-bench/test_review_git.py
|
||||
|
||||
@@ -2,49 +2,61 @@
|
||||
|
||||
Decisions live in `docs/decisions.md`:
|
||||
|
||||
- larv-review: a project lifting itself to the comprehension floor starts 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/: an outcome is an entry of a `.outcomes.md` file in loop-claude's archive, a record is a document tools or people keep entries in, and a place is what a comprehension seat names
|
||||
- bin/: the tests rerun themselves on a `uv`-fetched Python at README Install's floor
|
||||
- bin/: the tools and their tests run on the host's Python, with no container
|
||||
- chunks: a chunk takes every unblocked item of its release that fires the same review passes, whatever its purpose, and an item above R 5 ships alone
|
||||
- comprehension floor: every dimension and the overall at 7.0 or above is the target, and blocks no merge or release
|
||||
- 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 reviewer or comprehension seat that rules the work below standard may ask to rerun once, one rung up, in the same round; the ruling that stands is an escalation trigger for the worker, never for the judge
|
||||
- review: a fix for a 🔴 or 🟡 reruns the pass that found it and each pass whose trigger names fixes like it; from round 2 a pass reviews only the answers to its last round's findings and any other pass's fix that re-entered it; a fix for a 🟢, a ❓ or a prose finding reruns none
|
||||
- review: the comprehension check records how hard a project is to read and blocks no merge: a paired ruling against the last measured commit where the architecture pass ran, and the four-seat scoring run when a release's items run out or an item names the floor
|
||||
- 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
|
||||
- larv-review: within a chunk lifting a project towards the comprehension floor, work on the project's lowest-scoring dimension comes first, and the floor doesn't block anything
|
||||
- loop-claude: a `claude` that cannot start is a failed worker run, retried
|
||||
- review: an ask no user answers leaves the PR unmerged
|
||||
- loop-claude: a judge decides each interrupt and each quoted answer from the transcript, the README's premises, `AGENTS.md`, `docs/decisions.md`, `~/.claude/CLAUDE.md`, `~/.claude/rules/` and larv-review's standards, and holds a chunk open while an answer the human typed in it is recorded nowhere; the worker's own account of which goal settles a choice decides nothing
|
||||
- loop-claude: before it opens claude on the terminal, it marks the checkout and each of its worktrees trusted in `~/.claude.json`
|
||||
- loop-claude: each project's model lives in `~/.claude/loop-claude-models.json`, which only loop-claude writes
|
||||
- loop-claude: every claude it starts bypasses permissions inside its sandbox
|
||||
- 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 it states, each README achieve goal weighed by its position, the first heaviest, held to its bar, ranked by `bin/rank_todo.py`, which ranks each blocker above the items it blocks; the table's order is the plan's only order
|
||||
- todo.md: only a session or subagent on the project's rung or above scores or reshapes the plan; one below it drafts new items and changes to filed ones for a subagent at or above that rung to apply and score, and removes finished ones
|
||||
- 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
|
||||
- loop-claude: one session per project, its id derived from the checkout's path relative to `~/code`, or to `/` outside it
|
||||
- loop-claude: the archive keeps the raw transcript, and a failed archive stops the loop
|
||||
- principles: about seven things per level, four or five where they act on each other, more where a reader finds them by name; crossing a limit asks for a grouping or a recorded reason
|
||||
- reading cost and `score-outcomes`: each waits for 10 finished chunks before it shows a median
|
||||
- reading cost: a rise is the last 5 chunks' median above the 5 before them, and files or refreshes one plan item
|
||||
- reading cost: larv-review measures each finished chunk from loop-claude's archive and appends the figure to `docs/reading-cost.md` in the next chunk's PR
|
||||
- review: `/security-review` is the security pass of record, except where the full scan runs on the same change and replaces it
|
||||
- review: a fix for a 🔴 or 🟡 reruns the pass that found it and each pass whose row in `larv-review` §3's re-entry table the fix meets; from round 2 a pass reviews only the answers to its last round's findings and any other pass's fix that re-entered it; a fix for a 🟢, a ❓ or a prose finding reruns none
|
||||
- review: a pass gets at most three rounds per chunk; instead of a fourth, the run asks the human
|
||||
- review: a pass skips only on a precedent: a decision, or a plan item crediting the pass, that the repo held before the chunk began
|
||||
- review: a project decision may opt every chunk out of the architect, the product-owner pass or the comprehension check, and a project opting out of the comprehension check voids code health
|
||||
- review: a project decision may suspend the comprehension check for the plan items it names
|
||||
- review: a reviewer or comprehension seat that rules the work below standard may ask to rerun once, one rung up, in the same round; the ruling that stands is an escalation trigger for the worker, never for the judge
|
||||
- review: an ask no user answers leaves the PR unmerged
|
||||
- review: each reviewer under `agents/` writes its full report into the chunk's review folder under `~/.local/state/larv-review/` and returns the worker its verdict and one line per finding; rule-hook refuses its Edit and MultiEdit, and any Write outside `~/.local/state/larv-review/`
|
||||
- review: stability and product-owner report only a defect, a broken requirement of the plan or the goals, a breach of a technical principle, or for stability a hard place the change touches; each architect finding names a later change the PR makes harder; prose runs only on a chunk that changes prose
|
||||
- review: the comprehension check records how hard a project is to read and blocks no merge: a paired ruling against the last measured commit where the architecture pass ran, and the four-seat scoring run, once when an item names the floor and twice on one head when a release's items run out
|
||||
- review: the premises chunk's whole review is the human's approval
|
||||
- review: the principles audit runs on every chunk that changes code, config or tests, and on no other chunk
|
||||
- review: the stability pass mutation-tests the lines a chunk changes, in place of measuring test coverage
|
||||
- routing: a chunk's worker runs on the rung its item's L picks, below the project's rung too; its reviewers run on the highest of the worker's rung, the project's and the one picked by the highest E + I among the chunk's items, unless a replay lowered their pass; the seats and the security pass always on the project's
|
||||
- routing: a review pass runs below the project's rung only on a rung that a replay of its rounds shows finding every 🔴 and 🟡 the project's rung finds, and only where the E + I steps no review up and the worker runs no higher than the project's rung, then even below the worker's; no pass has such a rung
|
||||
- routing: a worker delegates a task only where it needs just the task's conclusion, and each subagent runs on the rung its task's L picks from the project's rung, never below the project's rung when it files or scores todo.md items
|
||||
- routing: a worker hands a task one rung up on each escalation trigger, up to two rungs above the rung its item picks unless the human agrees, and opens the subagent's prompt with the trigger so the routing figures count it
|
||||
- routing: a worker whose run ends asking for a higher rung, citing an escalation trigger the judge finds in the transcript, steps one rung up as the judge interrupts or quotes an answer, or next cycle, up to two rungs above the rung its item picks
|
||||
- routing: loop-claude measures review rounds and unfinished verdicts per rung every 20 cycles, and calls for a routing change when, of two rungs with 5 or more chunks each, the lower took more of either than the one above, or when 5 or more subagents of one type had reports longer than the tool results they read
|
||||
- routing: on a model judge-replay covered, the judge runs on the rung a review would get from the highest E + I among its chunk's items, never below the project's rung
|
||||
- routing: one ladder of (model, effort) rungs, ordered by the Artificial Analysis Intelligence Index with Fable 5.1 at max on top; a task's L picks its worker's rung and its E + I its reviewers', by fixed steps counted from the cheapest rung of the project's model
|
||||
- routing: the worker changes rung only as a chunk starts, after every second unfinished verdict, or when the judge reports a taken-in item that picks a higher rung or an escalation trigger the worker cites
|
||||
- rule-hook: a PreToolUse hook enforces each rule a program can check, a `# rule-override <rule>: <reason>` marker overrides one, and larv-review's overrides pass rules on each override before merge
|
||||
- rules/: `CLAUDE.md` holds the worker's rules that no file path can scope, and each topic's rules for the worker live in a `rules/` file that Claude Code loads by its `paths:` frontmatter
|
||||
- settings.json: Claude Code runs in auto mode with the dangerous-mode prompt skipped
|
||||
- settings.json: each machine owns its model, and git's clean filter `bin/settings_filter.py` keeps it, and Claude Code's key order, out of every commit
|
||||
- tests: each test earns its keep as the technical principles' test bullet says, and the worker takes a test's expected values from its item, never from the code
|
||||
- the repo may name bender, bender-infra and ai-sandbox
|
||||
- todo.md: one table of items, scored by the formula it states, held to its bar and ranked by `bin/rank_todo.py`, which ranks each blocker above the items it blocks; each achieve goal weighs by its position, code health first and four times as heavy while the comprehension panel's overall is under 7.0 or unmeasured, then README.md's goals; the table's order is the plan's only order
|
||||
- todo.md: only a session or subagent on the project's rung or above scores or reshapes the plan; one below it drafts new items and changes to filed ones for a subagent at or above that rung to apply and score, and removes finished ones
|
||||
- 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/`
|
||||
- review: stability and product-owner report only a defect, a broken requirement of the plan or the goals, a breach of a technical principle, or for stability a hard place the change touches; each architect finding names a later change the PR makes harder; prose runs only on a chunk that changes prose
|
||||
- review: the stability pass mutation-tests the lines a chunk changes, in place of measuring test coverage
|
||||
- routing: one ladder of (model, effort) rungs, ordered by the Artificial Analysis Intelligence Index with Fable 5.1 at max on top; a task's R + C picks a rung by fixed bands, counted from the cheapest rung of the project's model, and a chunk's worker may run below that rung, launching its reviewers on that rung; the worker routes each subagent it delegates to by the R + C of the subagent's task
|
||||
- routing: a worker hands a task one rung up on each escalation trigger, up to two rungs above the rung its item picks unless the human agrees, and opens the subagent's prompt with the trigger so the routing figures count it
|
||||
- routing: a worker whose run ends asking for a higher rung, citing an escalation trigger the judge finds in the transcript, resumes one rung up next cycle, up to two rungs above the rung its item picks
|
||||
- routing: on a model judge-replay covered, the judge runs on the rung its chunk's item picks, never below the project's rung
|
||||
- routing: the stability reviewer stays on the project's rung while the worker runs below it, until `stability-replay` shows a lower rung finding every 🔴 and 🟡 the project's rung finds
|
||||
- workflow-bench/: the remote may show the bench cases' names and commit SHAs
|
||||
|
||||
## Working rules
|
||||
|
||||
- `routing-calls-raised.md` sits at the root of loop-claude's archive (`$LOOP_CLAUDE_TRANSCRIPTS`, default `~/.claude/loop-claude-transcripts`). Each of its lines is a call or a `Reset`, with a stamp. A call is new when it is stamped after the latest `Reset` and after the latest stamp that `todo.md` or `docs/decisions.md` → `routing:` cites. When there are new calls, file one `todo.md` item to settle them, or refresh the item already filed. Its detail quotes those calls with their stamps, and the routed-chunks table of `routing-figures.md` beside it, never the project names its other tables hold. A change to the ladder, its bands or the delegation rule is the human's. The chunk that settles the calls cites the latest stamp it settled in `docs/decisions.md` → `routing:`, whatever the human decided, so they are not filed again. Once a chunk that changes the ladder, its bands or the delegation rule has merged, append `- <UTC time> Reset` to `routing-calls-raised.md`: the figures then count only chunks finished after it, and its calls may be raised again.
|
||||
- When `~/.claude/settings.json` has uncommitted changes, commit them on a branch of their own and merge them through a PR: Claude Code writes that file from any session. Read their diff first. 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`.
|
||||
- `routing-calls-raised.md` sits at the root of loop-claude's archive (`$LOOP_CLAUDE_TRANSCRIPTS`, default `~/.claude/loop-claude-transcripts`). Each of its lines is a call or a `Reset`, with a stamp. A call is new when it is stamped after the latest `Reset` and after the latest stamp that `todo.md` or `docs/decisions.md` → `routing:` cites. When there are new calls, file one `todo.md` item to settle them, or refresh the item already filed. Its detail quotes those calls with their stamps, and the routed-chunks table of `routing-figures.md` beside it, never the project names its other tables hold. A change to the ladder, its steps or the delegation rule is the human's. The chunk that settles the calls cites the latest stamp it settled in `docs/decisions.md` → `routing:`, whatever the human decided, so they are not filed again. Once a chunk that changes the ladder, its steps or the delegation rule has merged, append `- <UTC time> Reset` to `routing-calls-raised.md`: the figures then count only chunks finished after it, and its calls may be raised again.
|
||||
- When `~/.claude/settings.json` has uncommitted changes, commit them on a branch of their own and merge them through a PR: Claude Code writes that file from any session. Read their diff first: `git diff HEAD -- settings.json`, which shows staged changes too. An empty diff means only the model or the key order changed: `git add settings.json` takes the file off `git status`, with nothing to commit. When the diff holds a credential, such as a token in `env` or `mcpServers`, ask the human to move it out of the file, and commit only once it is gone. A token in `env` moves to the shell profile; a server in `mcpServers` moves to `~/.claude.json` with `claude mcp add --scope user`.
|
||||
|
||||
## Scoring run
|
||||
|
||||
|
||||
+50
-2
@@ -2,10 +2,58 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
- larv-review's skill now says a commit answering the external auto-reviewer takes no `Answer <pass> round` title, and that `larv-review round-count` doesn't list the auto-reviewer. A worker who followed the skill used to get a "not a pass" warning.
|
||||
- rule-hook now blocks a larv-review round commit titled past round 3, such as `Answer stability round 4: …`, unless a `round-cap` override quotes the human's yes.
|
||||
- loop-claude's first prompt for a chunk that no plan item routed now also names the rung on which the worker launches its reviews for an item it takes in, as the prompt after a step-up or an unfinished verdict already did.
|
||||
- `loop-claude --help` now describes routing in two short paragraphs for the person running the loop. The rules it used to repeat are now stated once, in the code that enforces them.
|
||||
- loop-claude now archives the route on each `Worker:` line as a JSON record, such as `{"model": "claude-opus-5-5", "effort": "high", "item": 3, "likelihood": 4, "escape_and_impact": 5, "escalated_at": 12}`, and reads it back field by field. The line used to be a sentence, such as `claude-opus-5-5 at high effort, routed by item 3's L of 4 and E + I of 5`, which loop-claude parsed back word for word: rewording the sentence in the code would have made every archived line unreadable, and a rerun would have routed the open chunk afresh. A rerun and the routing figures still read the sentences archived since loop-claude routed on L. A rerun that finds a `Worker:` line it can't read now says so on stderr. The judge's reply now names the levels the worker took in `highest_likelihood_taken_in` and `highest_escape_and_impact_taken_in`, in place of `bundled` and `bundled_escape_and_impact`.
|
||||
- A chunk now takes every unblocked item of its release that fires the same review passes, whatever its purpose: one PR title no longer has to state what the items achieve together. An item with R above 5 ships alone. `chunk-preflight` says so for such an item, and never lists one as an item that may join another.
|
||||
- A branch whose name is not UTF-8 now shows no branch in the status line, in place of a name with replacement characters.
|
||||
- A new technical principle, "About seven things per level", sets soft limits on what a reader takes in at once: the parameters and branches of a function, the methods of a class, the files and folders in a folder, the sections of a document and the components of a system. Aim for four or five of the things that act on each other, such as parameters. Things found by name, such as files named by locale, may run far past seven. Crossing a limit asks you to group the things or record why they stay. The systems-architect reviewer now reads its limits from this principle. It rates a unit that crosses a limit with no recorded reason a 🟡, where it used to be a 🔴, and no longer asks for the limits as merge-gate rules.
|
||||
|
||||
- The comprehension panel's base worktree and a build probe's output now go in a folder under the chunk's review folder in `~/.local/state/larv-review/`. Both used to go in a session scratchpad, which loop-claude's headless sessions don't have.
|
||||
- rule-hook now reads `git > out commit -m x` as one git commit, as the shell runs it. A redirect used to split a command in two, so such a commit escaped `commit-one-line`, `round-title-counts` and `todo-rank-check`.
|
||||
- `larv-review needs-scoring-run` now calls a scoring run for the release `chunk-preflight` names as next, not for the earliest release in the plan. It also counts a change as unreleased the way `chunk-preflight` does: an entry under `CHANGELOG.md` → `## Unreleased`, or, where there is no such section, a commit after the newest `v*` tag (any commit when there is none). Before, a chunk that moved the next release's last items to a later release without shipping them called a scoring run, while `chunk-preflight` called that release unplanned.
|
||||
- README → Install now says that every machine taking this checkout must be a sandbox with no direct access to a production environment, since `settings.json` runs Claude Code in auto mode with the dangerous-mode prompt skipped. Before, it asked for a sandbox only for `loop-claude`.
|
||||
|
||||
## 0.3.0
|
||||
|
||||
- A task scored L 1 now routes its worker, or a delegated subagent such as a search, one rung below the project's rung, as L 2 does; it used to go two rungs below. On an Opus 5.5 project that is Sonnet 5.5 at high, not Haiku 5.5 at max: chunks started on Haiku 5.5 took more review rounds and unfinished verdicts.
|
||||
- loop-claude's worker now starts with `ScheduleWakeup` disallowed. A worker that scheduled a wakeup kept `claude -p` running after its turn ended, so loop-claude neither ran the judge nor asked you, and the chunk stalled until someone killed the worker.
|
||||
- Every project's audience now includes the contributor, the person who reads the code to change it. A README doesn't list them; only its `**Void:** code health` line drops them. larv-review's comprehension check now measures how hard the project is for them to read.
|
||||
- `score-outcomes` now also measures projects that merge by rebase: each run of commits that share one commit time counts as a chunk. Add `docs/score-anchors.md` to those projects too. A chunk that was pushed or fast-forwarded may hold only part of its pull request, so the medians and rank correlations leave it out.
|
||||
- `settings.json` no longer carries a model: each machine keeps the one you pick with `/model`. Git's clean filter `bin/settings_filter.py` drops `"model"` and sorts the keys, so neither a pick nor Claude Code's key order can reach a commit. Update now starts with `git add settings.json`: without it, Update's `git checkout -f` drops the machine's model. On upgrade, on each machine:
|
||||
1. Turn the filter on in `~/.claude`: `git config filter.settings.clean bin/settings_filter.py`.
|
||||
2. Pick a model with `/model`. Until you do, Claude Code runs its default model; this repo set `opus` before.
|
||||
- larv-review's "Re-entry" is now one table of which passes a fix reruns, and the pass table's triggers say only when a pass first runs. The rule is unchanged; a fix for a 🟢, a ❓ or a prose finding still reruns no pass.
|
||||
|
||||
## 0.2.0
|
||||
|
||||
- Every project now shares one achieve goal, code health: the code is easy to understand and change safely. `CLAUDE.md` → "Shared goal" states it, with its signal and counter-signal. `rank_todo.py` ranks it first among a project's achieve goals. A project's overall is the overall mean of the newest scoring run in `docs/comprehension-history.md`, averaged with every other run on its commit. While that overall is under 7.0, or no run has measured the project, code health weighs four times as much as it does at 7.0 or above. An item's Moves cell names it as in `code health by 6`. A README voids it with `**Void:** code health, since <reason>.` under `## Goals`, and `rank_todo.py` then refuses an item that names it. `larv-review record-scoring` re-ranks `todo.md` after it appends a run, and exits 1 where `rank_todo.py` would, keeping the run. Expect items that make code easier to read to rank higher in every project. On upgrade:
|
||||
1. Move every machine to this release before any of them ranks a plan another machine shares: an older `rank_todo.py` scores it without code health and rejects a `code health` cell.
|
||||
2. Void code health in each project that opts out of the comprehension check, or `rank_todo.py` refuses its plan.
|
||||
3. Run `rank_todo.py` in each project that keeps code health. It re-scores every item, so until then `rank_todo.py --check` fails, and rule-hook holds the project's next `todo.md` commit.
|
||||
4. In each project whose README restates code health as a goal of its own, file an item to drop that goal and point the Moves cells citing it at `code health`. Dropping it renumbers the goals after it, so the same item repoints every Moves cell and decision citing them; `rank_todo.py` cannot tell a cell left pointing at the wrong goal.
|
||||
- `stability-replay <model>` is now `review-replay <pass> <model>`, and replays any pass an agent under `agents/` reviews, such as `review-replay prose claude-opus-5-5`. It now tries every rung below the project's, down to the ladder's lowest. Its runs on the prose and stability passes of Opus 5.5 projects found no rung below the project's that finds every 🔴 and 🟡 the project's rung finds: Sonnet 5.5 at high missed 12 of 27 prose findings and 11 of 20 stability findings. So every pass stays where it runs. A rung a future run finds lowers only its pass, once `REPLAYED` in `bin/model_routing/ladder.py` names it, and only where the chunk's E + I steps no review up and the worker runs no higher than the project's rung; there it may run below the worker's rung.
|
||||
- `chunk-preflight` names the release it finds finished and ready to cut, or to be planned first, wherever todo.md has named that release since the last cut.
|
||||
- Each reviewer under `agents/` now writes its full report to a file that larv-review names in the reviewer's prompt, in a folder per chunk under `~/.local/state/larv-review/`. It returns only its verdict and one line per finding, so a review takes less of the worker's context. The worker reads a finding's full entry before it fixes or answers a 🔴 or 🟡. Each reviewer now holds Write. `rule-hook` refuses a reviewer's Edit and MultiEdit, and any Write outside `~/.local/state/larv-review/`; no override waives this rule. Each chunk's folder stays after the merge, so `review-replay` can replay a round that reads an earlier round's report. It replays on a copy of the folder.
|
||||
- `loop-claude` asks an interrupt's question on its own terminal and resumes the worker headless with your one-line answer, so the loop no longer waits for you to leave a claude session. Type `/talk` instead to open the worker's session in claude, as every interrupt did before, to read the diff or discuss first. A release ready to cut opens that session at once. Pressing Enter on an empty answer stops the loop, exit 2. Keys typed before the question shows are dropped, and a pasted answer keeps only its first line; type `/talk` for a longer one. The judge counts that answer as yours, like one typed in claude: the chunk stays open until the answer is recorded, where a later chunk could need it.
|
||||
- `todo.md` may mark a renamed release in a `## Renamed` section, one line per rename, such as `- 0.2.1 renamed to 0.3.0`. `chunk-preflight` and `loop-claude` then skip that release when they pick the next one, and larv-review's scoring-run trigger calls no run for it. Without the mark, a release named since the last tag whose items all moved to other releases reads as finished: `chunk-preflight` says it is ready to cut and the loop stops for you, and the trigger calls a scoring run. `rank_todo.py` fails on a `## Renamed` line of another shape, and on an item filed under a release it marks. Before you move a machine to this release, add the line to the `todo.md` of every project that renamed a release since its last tag, or its loop stops for that release's cut.
|
||||
- When a worker's run ends with a question and a request for a higher rung, `loop-claude` now steps the worker one rung up as the judge interrupts, or as it answers the question with a quote from `README.md` or another file it may quote. The judge must quote a passage showing that the escalation trigger the run cites fired. Before, the step was lost for an answered question, and the worker carried on from the answer on its old rung. The step has the same limits as the step on an unfinished verdict. An escalation trigger that fired before the worker's last step-up doesn't step it again, so one trigger buys one step. A trigger that fires after the step steps the worker again, in the same cycle or a later one. A chunk left open across the upgrade to this release starts with no step-up on record, so a trigger that already stepped its worker may step it once more. The archive's interrupt and quoted-answer outcomes now name the worker's rung.
|
||||
- A scoring run due because a release's items ran out costs four more seats: it is done twice on one head. `larv-review agreement` compares how often Mid A and the inherited architect vote alike in paired rulings with how often their overall scores move the same way between the two runs. After 10 such pairs it gives a verdict, and on `Assumption fails:` larv-review asks you whether to keep the paired ruling.
|
||||
- `workflow-bench/bench.py` gives each run a fixed list of allowed tools. Before, it skipped every permission check. A run may launch agents, run `/security-review`, edit its clone (not the clone's `.git/` or `.claude/`) and its report, and read its clone and the copy of `~/.claude` it benches. For git it gets one command, `workflow-bench/review_git.py`, and no bare `git`. The wrapper runs `log`, `diff`, `show`, `status`, `ls-files`, `add` and `commit -m` on the run's clone, whatever the working directory. It allows only the options it lists for each, and refuses an argument that names a path outside the clone. git runs with no global or system config, hook, pager or editor. A run loads no settings or MCP servers from `~/.claude` or from the case's clone, so their hooks and extra directories do not apply to it. Every other call is denied. Expect a benched review that needs another git command, or to run a project's code or tests, to say in its report that it could not.
|
||||
- Every goal in `README.md` → Goals is marked `**Maintain:**`, a state to hold, or `**Achieve:**`, a direction to pursue. Each achieve goal has a signal, a counter-signal and a one-line reason under it. A change that breaks a maintain goal is redesigned or dropped, whatever it scores: `rules/todo-items.md` says so, and larv-review's goal alignment step no longer merges such a PR. `rules/goals-and-audience.md` states the form for every project's README. Expect larv-review to stop a PR on a maintain goal where it asked you before.
|
||||
- Reshape every project's `todo.md` to the new shape below: until it is reshaped, that is the project's only work, as it is while README.md lacks Goals and Audience, and `rank_todo.py` says so. First move every machine to this release: an older release rejects the new formula, so it fails on every reshaped `todo.md`. Then mark the README's goals `**Maintain:**` or `**Achieve:**`, and set a bar on the new scale below the score of every item to keep, since the old bar would drop most items. Until then, an old-shape `todo.md` still ranks by its own formula and weights.
|
||||
- `todo.md` ranks items by value per cost: this setup's own plan uses `Score = 100 * V / (2**S + 8)`, where 8 is a chunk's fixed cost, about one size-3 change, and `rank_todo.py --help` shows it. A Moves column replaces A, G and Goals, naming each achieve goal an item moves and how far, such as `1.1 by 8, 1.2 by 5`. V sums each named goal's weight times its move. `rank_todo.py` weighs each achieve goal by its position in README.md, the first heaviest, so the goal weights table goes. An item names the most specific goal it moves, never a goal beside its own sub-goal. `rules/todo-items.md` and `rank_todo.py --help` show the new shape.
|
||||
- Reshape every project's `todo.md` to the new shape below: until it is reshaped, that is the project's only work, as it is while README.md lacks Goals and Audience, and `rank_todo.py` says so. First move every machine to this release: an older release rejects the new formula, so it fails on every reshaped `todo.md`. Then mark the README's goals `**Maintain:**` or `**Achieve:**`, score each item's L, E and I, and set a bar on the new scale below the score of every item to keep, since the old bar would drop most items. Until then, an old-shape `todo.md` still ranks by its own formula and weights.
|
||||
- `todo.md` ranks items by value per cost: this setup's own plan uses `Score = 100 * V / (2**S + 8)`, where 8 is a chunk's fixed cost, about one size-3 change, and `rank_todo.py --help` shows it. A Moves column replaces A, G and Goals, naming each achieve goal an item moves and how far, such as `1.1 by 8, 1.2 by 5`. V sums each named goal's weight times its move. `rank_todo.py` weighs each achieve goal 0.97 times the one above it in README.md, so a goal far down the list still counts almost as much as the first and the goal weights table goes. The weights sum to 1: 5 achieve goals weigh 0.212 down to 0.188, 15 weigh 0.082 down to 0.053. An item names the most specific goal it moves, never a goal beside its own sub-goal. `rules/todo-items.md` and `rank_todo.py --help` show the new shape.
|
||||
- L, E and I replace C, and set R. L is the chance the change holds a defect, from 1 to 4; E the chance a defect escapes tests and review, from 1 to 3; I the damage it would do, from 1 to 5, counting every project and session that runs the change. `rules/todo-items.md` defines each level in words, and `rank_todo.py` writes R as L + E + I − 2, at least 7 when I is 5 and at least 5 when I is 4. The table's score columns are `| L | E | I | R | S |`. `score-outcomes` takes `L E I S`, and reports how well L, E and I each order finished chunks by review rounds and 🔴 findings.
|
||||
- `loop-claude` routes a chunk's worker on its item's L, from two rungs below the project's rung at L 1 to one above it at L 4. It routes the reviewers on the highest E + I among the chunk's items, counting each item the worker takes in: one rung above the project's for each point past 4, never below the worker's rung. It runs the judge of an Opus 5.5 project on the rung that highest E + I picks, never below the project's, and keeps it there when the worker steps up. The comprehension seats and the security pass stay on the project's rung. rule-hook holds each reviewer launch to the reviewers' rung, which it works out from the E + I `loop-claude` hands the worker in `LOOP_CLAUDE_ESCAPE_AND_IMPACT`. A delegated task's subagent takes the rung its L picks: `subagent-rung` takes L in place of R + C. Until a project reshapes its `todo.md`, every chunk there runs on the project's rung. Expect reviews of items whose defects would escape far or break much to cost more, and escalation from an item of L 4 to reach Fable 5.1 only with your yes.
|
||||
- An item that restores a maintain goal the project breaks today is exempt as `defect`, and its Moves may name that maintain goal, weighed as the heaviest achieve goal. A defect ranks by its score like any item. Only two kinds rank ahead of the rest of their release: questions first, since an answer may change other items, then security items.
|
||||
- The stability reviewer applies `principles/technical-principles.md` as written, in place of its own copies of it. Its test-data check now asks for UUID v7, where it asked for randomised UUIDs.
|
||||
- larv-review's principles audit is a pass of its own, and runs on every chunk that changes code, config or tests, not only on one with an architectural decision. A chunk of prose or planning alone skips it.
|
||||
- `rule-hook` refuses an Agent call that launches a reviewer, a comprehension seat or the security pass on a rung below the one `loop-claude` names for it, and takes no override: pass the model and effort the refusal names.
|
||||
- `score-outcomes` lists a project's score anchors: the shipped items its `docs/score-anchors.md` names for each level of L, E and I, each with what its chunk measured. `rules/todo-items.md` has a scorer compare a new item with them, and says how to choose two or three per level. Add the file to each project that merges with merge commits; elsewhere, score by the level descriptions in `rules/todo-items.md`.
|
||||
- `loop-claude` archives each judge reply it rejects in the chunk's `<sha256>.outcomes.md`, with the reason and the reply as json. Before, such a reply reached only stderr, so a run that exited 1 overnight could not say what the judge had returned. stderr now prints only the reason; the reply is in outcomes.md. If archiving fails, `loop-claude` exits 1.
|
||||
- `loop-claude` routes each chunk on `todo.md` as the default branch holds it, freshly fetched: merge a `todo.md` edit before the chunk it should route starts. Where `todo.md` holds no item for the next release, the earliest release it has named since the newest tag, no item routes the chunk, and the worker is told that release is finished and ready to cut, or, where no work has landed since the tag, to be planned first. Before routing, `loop-claude` runs the new `bin/chunk-preflight` and quotes what it prints in the worker's first prompt: the chunk's mechanical facts, which `chunk-preflight --help` lists. The preflight also makes the chunk's worktree, `<checkout>-item-<ID>` beside the checkout on the branch `item-<ID>`, or continues the one already there, and leaves an uncommitted figure in that worktree's `docs/reading-cost.md` for the chunk to commit. It stops a fetch, forge CLI or tool after 60 seconds, or after the seconds `CHUNK_PREFLIGHT_TIMEOUT` sets. The prompt also asks the worker to count the item's size again once it has read the code, and to have the item re-scored where its L would change. Expect the worker to start editing sooner.
|
||||
|
||||
## 0.1.0
|
||||
|
||||
|
||||
@@ -4,22 +4,33 @@
|
||||
|
||||
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.
|
||||
- **Until `README.md` has a `## Goals` and an `## Audience` section, writing them is the only work.** Not even planning in `todo.md`. Both are public: an outside reader judges a project by where it is heading and who it is for. Goals or an audience written anywhere else, such as `AGENTS.md` or `docs/`, do not count; the one exception is code health, which "Shared goal" below states for every project.
|
||||
- **Plan `todo.md` as one scored table, in the shape whose example `~/.claude/bin/rank_todo.py --help` shows**: every item names the release that ships it. Until `todo.md` has that shape, reshaping it is the only work, and the human approves it.
|
||||
- **When the next release has no items and no work has landed towards it, plan it as this chunk.** Move the highest-scoring items of later releases into it, and get the human's approval of that set before writing any code.
|
||||
- **When the next release has no items left and work has landed towards it, it is finished: stop.** Report what it holds and that it is ready to cut. Under `/loop`, this ends the loop. Until the human cuts it, only a security fix lands, into that release; never start a later release's items or plan a new one.
|
||||
- **Open every chunk with one line:** the last version cut, how many changes are unreleased (the entries under `CHANGELOG.md` → `## Unreleased`, or else the commits since the last tag), and the release this chunk ships into. A repo that publishes nothing says so once.
|
||||
- **Read the README's `## Goals` and `## Audience` before starting a chunk, unless your prompt quotes them.** The chunk's items set its scope. The goals choose between ways to deliver those items, and never add to them.
|
||||
- **Read the plan and the decisions only as far as the chunk needs.** Run `grep -n '^## Details' todo.md`, then read `todo.md` with the Read tool up to the line it prints, or whole when it prints none. Then read the details of only the items the chunk takes. `AGENTS.md` lists every decision's title. Read the entry under a title in `docs/decisions.md` only where the title leaves open what the chunk or the review needs.
|
||||
- **Work one chunk at a time, and 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 four things hold: one PR title states what they achieve together, without listing them; they name one release; they fire the same review passes (`larv-review` §3); and no item outside the chunk blocks one of them. The next plan item is the first that does not wait: an item waits while it is marked `question`, until the human answers, or while an item that blocks it is still in the plan. Tiny items, a few lines of change each, need neither a shared purpose nor the same passes: bundle up to ten that name one release, and that no item outside the chunk blocks, into one chunk. Split a milestone into items in `todo.md` before starting it. Fix a finding in the chunk's own change within the chunk. File a finding about anything else in `todo.md`.
|
||||
- **Read the plan and the decisions only as far as the chunk needs.** Where your prompt quotes `chunk-preflight`'s facts, they hold the next item's L, E + I, tagline and detail, and the items that may join it; read further only what they leave out. Otherwise run `grep -n '^## Details' todo.md`, then read `todo.md` with the Read tool up to the line it prints, or whole when it prints none. Then read the details of only the items the chunk takes. `AGENTS.md` lists every decision's title. Read the entry under a title in `docs/decisions.md` only where the title leaves open what the chunk or the review needs.
|
||||
- **Work one chunk at a time, and put every item that can share its review into it.** Every review has a fixed cost, so a chunk takes the next plan item plus every other item for which three things hold: they name one release; they fire the same review passes (`larv-review` §3); and no item outside the chunk blocks one of them. The items need not share a purpose. An item whose risk R, in `todo.md`, is above 5 ships alone: it joins no chunk, and none joins it. The next plan item is the first that does not wait: an item waits while it is marked `question`, until the human answers, or while an item that blocks it is still in the plan. Tiny items, a few lines of change each, need not fire the same passes: bundle up to ten that name one release, and that no item outside the chunk blocks, into one chunk. Split a milestone into items in `todo.md` before starting it. Fix a finding in the chunk's own change within the chunk. File a finding about anything else in `todo.md`.
|
||||
- **Ask, don't guess.** First check whether the goals already answer the question. If they nearly do, propose a change to the goals and show how it answers this case: an answer settles one question, a goal settles every question like it. Write every answer once, where it belongs, never only in chat: a goal in `README.md`, a working rule in `AGENTS.md`, a standing choice in a comment at the one place it governs, or in `docs/decisions.md` once made in more than one place. When an answer holds a goal and a choice, write the goal in the README, and record as a choice only what the goal leaves open.
|
||||
- **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.
|
||||
- **Implement the simplest change that solves the item, and ship it with `/larv-review`.** Whenever a test can check the change, write that test first and see it fail. Take its expected values from the item, never from the code. larv-review's reviewers hold the change to the technical principles, and a finding against one names it. Read a file under `~/.claude/principles/` only when the item changes it, a finding or a record you write names it, or you decline a finding.
|
||||
- **Remove a finished item's row and detail from `todo.md`, and revise any decision that cites it.** If the repo publishes something others consume — a package, an image, an API — reword the item for them and move it to `CHANGELOG.md` under `## Unreleased`. A changelog is for the public, never for the next agent. Otherwise delete it; git history is the record.
|
||||
- **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.
|
||||
- **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, after only the open questions, which wait for me. 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.
|
||||
|
||||
## Shared goal
|
||||
|
||||
Every project pursues the achieve goal below, ranked above every achieve goal its README states. A project whose code nobody will maintain voids it with one line under `## Goals`, before the numbered goals: `**Void:** code health, since <reason>.` So does a project that opts out of the comprehension check, since the goal then has no signal. An item's Moves cell names it as in `code health by 6`, and `rank_todo.py --help` says how much it weighs.
|
||||
|
||||
**Achieve:** Code health: the code is easy to understand and change safely.
|
||||
- Signal: the comprehension panel's overall score rises, always. Under 7.0 it is very important.
|
||||
- Counter-signal: defects keep reappearing in functionality that already shipped, or reviewers raise blockers because the implementer misunderstood the current system.
|
||||
- Why: a score that rises while changes still misread the code measures the wrong thing.
|
||||
|
||||
Fewer items shipped per release is a price this goal accepts, not a counter-signal.
|
||||
|
||||
## 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.
|
||||
@@ -31,6 +42,8 @@ Everything written — chat, commit messages, comments, docs, code — is in **E
|
||||
|
||||
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.
|
||||
|
||||
Write negations as people say them. BANNED: `stops nothing`, `changes nothing`, `reveals nothing`, `depends on no one`. GOOD: `doesn't stop anything`, `doesn't change anything`, `doesn't reveal anything`, `doesn't depend on anyone`.
|
||||
|
||||
Reviewers hold prose to the full rules, with examples: `~/.claude/skills/larv-review/standards/prose.md`.
|
||||
|
||||
## Public API specs
|
||||
@@ -52,19 +65,19 @@ The rules only reviewers apply, for quality, comments, READMEs and prose, live i
|
||||
- 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 unless a decision puts them there. Example: `docker compose run --rm app <tool> …`.
|
||||
- Tear down test containers after a run.
|
||||
- Delegate a task to a subagent only when you need just its conclusion: a search or read across many files, or work independent enough to run in parallel. Keep edits, and whatever you must check line by line, in your own thread: you would read a delegated diff again to check it. Score the task's R and C as for a `todo.md` item. `<model>` below is the project's model id, such as `claude-opus-5-5`: the one loop-claude's prompt names as the project's, or else your own. Launch the subagent with the model and effort of the first case that fits:
|
||||
- Delegate a task to a subagent only when you need just its conclusion: a search or read across many files, or work independent enough to run in parallel. Keep edits, and whatever you must check line by line, in your own thread: you would read a delegated diff again to check it. Score the task's L as for a `todo.md` item; a task that changes no file, such as a search, is L 1. `<model>` below is the project's model id, such as `claude-opus-5-5`: the one loop-claude's prompt names as the project's, or else your own. Launch the subagent with the model and effort of the first case that fits:
|
||||
1. A reviewer, a comprehension seat or the security pass: those loop-claude's prompt gives it. Given none, pass no model or effort, so it runs on your model.
|
||||
2. An escalated task, below: the rung loop-claude's prompt names for escalation, or case 3's rung where the subagent files or scores `todo.md` items and that rung is higher.
|
||||
3. A subagent that files or scores `todo.md` items: what `~/.claude/bin/subagent-rung --plan <model> <R+C>` prints, which is never below the project's rung.
|
||||
4. Any other: what `~/.claude/bin/subagent-rung <model> <R+C>` prints.
|
||||
3. A subagent that files or scores `todo.md` items: what `~/.claude/bin/subagent-rung --plan <model> <L>` prints, which is never below the project's rung.
|
||||
4. Any other: what `~/.claude/bin/subagent-rung <model> <L>` prints.
|
||||
- Escalate a task that proves too hard for your rung. Four escalation triggers say so:
|
||||
1. A re-score of the item, made on the project's rung or above, picks a rung above yours.
|
||||
1. A re-score of the item's L, made on the project's rung or above, picks a rung above yours.
|
||||
2. The same failing test or finding survives two fix attempts.
|
||||
3. A pass reports a 🔴 in round 2 or later.
|
||||
4. A review rules the work below standard: systems-architect's BLOCK, a finding against larv-review's `standards/quality.md`, or a vote `record-ruling` counts as worse, in the report that stands after any relaunch one rung up (`larv-review` §3 → "Rung up").
|
||||
|
||||
When one fires, hand the hard part, edits included, to a subagent on the rung loop-claude's prompt names, one above yours. Open the subagent's prompt with the marker loop-claude's prompt gives, then the trigger's evidence. Each later subagent on that task runs on that rung or higher, and each further escalation trigger moves the task one rung higher, up to the highest rung loop-claude's prompt names. Ask the human before going higher. Where loop-claude's prompt names no escalation, as on the ladder's top rung or off it, keep the task in your own thread.
|
||||
- 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.
|
||||
- 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. A reviewer under `~/.claude/agents/` writes only its report, under `~/.local/state/larv-review/`, and rule-hook refuses it every other Write, every Edit and every MultiEdit. One that probes a build tags the image as throwaway and removes it afterwards, writes only to a folder it makes under the chunk's review folder (`~/.claude/bin/larv-review review-folder` prints it), 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.
|
||||
|
||||
@@ -78,6 +91,7 @@ The rules only reviewers apply, for quality, comments, READMEs and prose, live i
|
||||
- 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`.
|
||||
- Branch for a `todo.md` item without a ticket: `item-<ID>`, in the worktree `<checkout>-item-<ID>` beside the checkout, as `chunk-preflight` makes them.
|
||||
- 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
|
||||
@@ -91,17 +105,22 @@ The rules only reviewers apply, for quality, comments, READMEs and prose, live i
|
||||
## Vocabulary
|
||||
|
||||
- **chunk** — the unit of work, shipped as one PR; "Working loop" says what it holds.
|
||||
- **cycle** — in `loop-claude`, worker runs and the judge's verdict on each, until the chunk closes or is left for the next cycle. In between, the human answers any interrupt, or the worker resumes with an answer the judge quoted from `README.md`, `AGENTS.md`, `docs/decisions.md`, `~/.claude/CLAUDE.md`, `~/.claude/rules/` or `~/.claude/skills/larv-review/standards/`.
|
||||
- **cycle** — in `loop-claude`, worker runs and the judge's verdict on each, until the chunk closes or is left for the next cycle. In between, the human answers any interrupt, or the worker resumes with an answer the judge quoted from `README.md` or the judge's records.
|
||||
- **gate** — the merge gate: the checks a PR passes before it merges.
|
||||
- **interrupt** — `loop-claude` handing the terminal to the human, `claude --resume`, for a decision that is theirs.
|
||||
- **interrupt** — `loop-claude` asking the human, on its terminal, for a decision that is theirs. They type a one-line answer, or `/talk` to open the worker's session with `claude --resume`; a release ready to cut opens that session at once, and a routing call opens claude in `~/.claude`.
|
||||
- **judge** — the headless claude that reads a worker's transcript each cycle and decides whether to interrupt and whether the chunk is finished.
|
||||
- **judge's records** — the files the judge reads beside the README's premises: the project's `AGENTS.md` and `docs/decisions.md`, then the human's `~/.claude/CLAUDE.md` and the `.md` files in `~/.claude/rules/` and `~/.claude/skills/larv-review/standards/`.
|
||||
- **paired ruling** — the seats vote whether the project reads better, the same or worse at the branch's head than at the base, the commit `larv-review ruling-base` prints; `larv-review --help` says how the votes make the ruling.
|
||||
- **pass** — one kind of review a chunk may take, run in rounds by its reviewers until clean; `larv-review` §3 lists them.
|
||||
- **place** — the smallest addressable unit, such as a function or a section heading, that a seat names with its `path:line` when it judges how hard the project is to read there.
|
||||
- **plan** — `todo.md`.
|
||||
- **premises** — the goals and audience under `## Goals` and `## Audience` in the project's `README.md`.
|
||||
- **premises** — the goals and audience under `## Goals` and `## Audience` in the project's `README.md`, with code health ("Shared goal") first among the goals unless the README voids it.
|
||||
- **project's rung** — the cheapest rung on loop-claude's routing ladder of the project's model, which is the model loop-claude's prompt names as the project's, or else your own.
|
||||
- **release** — a semver version the human cuts.
|
||||
- **reviewer** — a reporter of findings: an agent under `~/.claude/agents/`, `/security-review` or a forge's auto-reviewer.
|
||||
- **round cap** — the rounds one pass may take per chunk; `larv-review` §3 → "Round cap".
|
||||
- **scoring run** — each seat scores the project from 1 to 10, overall and on each dimension. `larv-review` §3 → "Comprehension check" says which seats score and when one is due.
|
||||
- **seat** — one simulated reader of the comprehension panel, launched per `~/.claude/skills/comprehension-panel/SKILL.md`.
|
||||
- **session** — a Claude Code session: one id, what `claude --resume` continues.
|
||||
- **trigger** — the condition under which a review pass runs on a change it has not seen; `larv-review` §3 lists them.
|
||||
- **worker** — the headless claude that runs the task in a cycle, in the chunk's session.
|
||||
|
||||
@@ -35,6 +35,8 @@ Me, on my own machines, which take tagged releases. Nobody else depends on it.
|
||||
|
||||
## Install
|
||||
|
||||
Take this checkout only onto a machine that is a sandbox with no direct access to a production environment, such as a dedicated VM: `settings.json` runs Claude Code in auto mode with the dangerous-mode prompt skipped.
|
||||
|
||||
Claude Code may already have created `~/.claude`, where `git clone` refuses to run, so make the repository in place:
|
||||
|
||||
```sh
|
||||
@@ -43,7 +45,7 @@ git init
|
||||
git remote add origin ssh://git@gitea.larvit.se:21022/lilleman/claude-config.git
|
||||
```
|
||||
|
||||
Then run Update's commands.
|
||||
Then run Update's commands, skipping `git add settings.json`: the new repository tracks no file yet.
|
||||
|
||||
Have Python 3.11 or newer as `python3` on `PATH`, and for Rust projects `rust-analyzer` on `PATH`, which the `rust-analyzer-lsp` plugin needs. Install every plugin `settings.json` enables:
|
||||
|
||||
@@ -54,14 +56,25 @@ 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.
|
||||
Have git store `settings.json` without `"model"`, so a model you pick with `/model` stays on this machine and never reaches a commit:
|
||||
|
||||
```sh
|
||||
git config filter.settings.clean bin/settings_filter.py
|
||||
```
|
||||
|
||||
Then pick a model with `/model`.
|
||||
|
||||
After a pick, `git status` may list `settings.json`, and a `git pull` that changes the file refuses to run. `git add settings.json` stages no change and clears both. Once it is staged, such a pull goes through and drops the model: pick it again.
|
||||
|
||||
Link `loop-claude` onto `PATH`: `ln -s ~/.claude/bin/loop-claude ~/.local/bin/loop-claude`. Every claude it starts, the interactive ones included, skips every permission prompt.
|
||||
|
||||
## 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:
|
||||
Move a machine that takes tagged releases to the latest tag. The move discards every uncommitted change to a file the latest tag tracks, such as a hook Claude Code wrote into `settings.json`. Git counts a model pick as such a change until `git add settings.json`, so stage it first. List the uncommitted changes to files the checkout tracks, and the tag it is on:
|
||||
|
||||
```sh
|
||||
cd ~/.claude
|
||||
git add settings.json
|
||||
git fetch --tags origin
|
||||
git status
|
||||
```
|
||||
@@ -72,7 +85,7 @@ To keep an uncommitted change, merge it per `AGENTS.md` → "Working rules" and
|
||||
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.
|
||||
Then, where the tag changed `settings.json`, pick the model again with `/model`, and do what `CHANGELOG.md` asks of each version since the old tag, such as a new step under Install.
|
||||
|
||||
## Release
|
||||
|
||||
@@ -82,25 +95,27 @@ Rename `## Unreleased` in `CHANGELOG.md` to the version, commit, tag that commit
|
||||
|
||||
Install puts only `loop-claude` on `PATH`; call the others by their path, such as `~/.claude/bin/metric-bench`, from the project's checkout.
|
||||
|
||||
- `chunk-preflight` finds the mechanical facts a chunk starts from and makes its worktree; `loop-claude` runs it before it routes each chunk, and `chunk-preflight --help` lists the facts.
|
||||
- `judge-replay <model>` replays loop-claude's judge on archived verdicts of the projects run on the model, and prints the lowest rung that, like each rung above it, returns them; `judge-replay --help` states the replay.
|
||||
- `larv-review <command>` holds larv-review's mechanical rules: the paired ruling's base and vote count, each pass's round count, the scoring run's trigger, and the comprehension history's format and latest places; `larv-review --help` states them.
|
||||
- `larv-review <command>` holds larv-review's mechanical rules: the chunk's review folder, the paired ruling's base and vote count, each pass's round count, the scoring run's trigger, and the comprehension history's format and latest places, and its count of how often seats agree; `larv-review --help` states them.
|
||||
- `loop-claude <task>` runs a project's next chunk cycle after cycle; `loop-claude --help` states its contract.
|
||||
- `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.
|
||||
- `score-outcomes [R S C]` lists the finished items whose guessed R, S and C sit nearest the given scores, with what their chunks measured, and each score's median outcome; `score-outcomes --help` states the measures.
|
||||
- `stability-replay <model>` replays archived stability reviews of the projects run on the model, on the code each reviewed, and prints the lowest rung below the project's that, like each rung above it, finds every 🔴 and 🟡 the project's rung finds again; `stability-replay --help` states the replay. Run it only in a sandbox, like loop-claude: each replayed reviewer has Bash and skips every permission prompt, and an archived prompt may name paths on the host.
|
||||
- `review-replay <pass> <model>` replays a review pass's archived rounds from the projects run on the model, on the code each reviewed, and prints the lowest rung below the project's that, like each rung above it, finds every 🔴 and 🟡 the project's rung finds again; `review-replay --help` states the replay. Each replayed reviewer skips every permission prompt, stability-reviewer has Bash, and an archived prompt may name paths on the host.
|
||||
- `rule-hook [overrides]` blocks a tool call that breaks a rule a program can check, unless the call overrides the rule; `settings.json` → `hooks` runs it before each Bash, Edit, MultiEdit, Write and Agent call, and `rule-hook --help` states the rules and the override.
|
||||
- `score-outcomes [L E I S]` lists the finished items whose guessed scores sit nearest the given ones, and the shipped items the project's `docs/score-anchors.md` names for each level of L, E and I, each with what its chunk measured; then the median outcome at each guessed R and S, and how well L, E and I each order the chunks by review rounds and 🔴 findings; `score-outcomes --help` states the measures.
|
||||
- `settings_filter.py` is git's clean filter for `settings.json`: it drops `"model"` and sorts the keys. `.gitattributes` sets the filter `settings` on `settings.json`, and Install's `git config` line makes this script that filter.
|
||||
- `statusline.py` renders Claude Code's status line; `settings.json` → `statusLine` runs it.
|
||||
- `subagent-rung [--plan] <model> <R+C>` prints the Agent tool's model and effort for a subagent's task, picked by its R + C from the project's model, and with `--plan` never below the project's rung; `subagent-rung --help` states the rule.
|
||||
- `subagent-rung [--plan] <model> <L>` prints the Agent tool's model and effort for a subagent's task, picked by its L from the project's model, and with `--plan` never below the project's rung; `subagent-rung --help` states the rule.
|
||||
|
||||
Test on the host, with `uv` on `PATH` to fetch mypy and the Python version Install names (`docs/decisions.md` → `bin/`): `python3 -m unittest discover -s bin -p 'test_*.py'`
|
||||
Test on the host, with `uv` on `PATH` to fetch mypy and the Python version Install names (`docs/decisions.md` → `bin/`): `python3 -m unittest discover -s bin -p 'test_*.py'`. Test the bench's git wrapper with `python3 -m unittest discover -s workflow-bench -p 'test_*.py'`.
|
||||
|
||||
To mutation-test a changed module, copy `bin/` to a scratch directory (`cp -r bin "$scratch"`): mutmut writes files beside its config. In the copy, name the module and its tests in a `setup.cfg`, as below for `score_outcomes/outcomes.py`. Leave out each test class that starts a tool's launcher through `subprocess`: a mutated module fails to load in a process mutmut did not start.
|
||||
To mutation-test a changed module, copy `bin/` to a scratch directory (`cp -r bin "$scratch"`): mutmut writes files beside its config. In the copy, name the module and its tests in a `setup.cfg`, as below for `score_outcomes/results.py`. Leave out each test class that starts a tool's launcher through `subprocess`: a mutated module fails to load in a process mutmut did not start.
|
||||
|
||||
```ini
|
||||
[mutmut]
|
||||
source_paths=score_outcomes/outcomes.py
|
||||
source_paths=score_outcomes/results.py
|
||||
also_copy=.
|
||||
pytest_add_cli_args_test_selection=score_outcomes/
|
||||
pytest_add_cli_args=-k
|
||||
@@ -109,7 +124,7 @@ pytest_add_cli_args=-k
|
||||
|
||||
Then, in the copy: `uvx --with pytest 'mutmut>=3,<4' run && uvx --with pytest 'mutmut>=3,<4' results`, and `uvx --with pytest 'mutmut>=3,<4' show <mutant>` to see a mutant's change. The config keys are mutmut 3's.
|
||||
|
||||
`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, `rule_hook` imports `rank_todo.py`'s check, `score_outcomes` imports `reading_cost`'s record path, `judge_replay` imports `loop_claude`'s judge. `judge_replay` and `stability_replay` share `rung_replay/`: the rung search, and the argument, candidate rungs and exits. It reads `loop_claude`'s retry count and models file. The other non-test modules at `bin/`'s root, `claude_code/` and `transcript_archive/` serve more than one tool; `model_routing/` holds the routing ladder, which loop-claude and `subagent-rung` read. `routing_figures/` measures loop-claude's archive for loop-claude's routing calls. `test_env.py` serves the tests, and `repo_checks/` tests the repo itself.
|
||||
`bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests; `rank_todo.py`, `settings_filter.py` and `statusline.py` are tools of one file each, tested beside them, `rule_hook` imports `rank_todo.py`'s check, `larv_review` imports `rank_todo.py`'s ranking, `score_outcomes` imports `reading_cost`'s record path, `judge_replay` imports `loop_claude`'s judge, and `loop_claude` runs `chunk-preflight` as a process of its own. `judge_replay` and `review_replay` share `rung_replay/`: the rung search, the argument reader, the candidate rungs and the exits. `rung_replay/` reads `loop_claude`'s retry count and models file. The other non-test modules at `bin/`'s root, `claude_code/` and `transcript_archive/` serve more than one tool; `model_routing/` holds the routing ladder, which loop-claude, `rule_hook`, both replay tools and `subagent-rung` read. `routing_figures/` measures loop-claude's archive for loop-claude's routing calls. `test_env.py` serves the tests, and `repo_checks/` tests the repo itself.
|
||||
|
||||
## Tracking a new file
|
||||
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
---
|
||||
name: override-reviewer
|
||||
description: "Use this agent for larv-review's overrides pass."
|
||||
tools: Read, Grep, Glob
|
||||
tools: Read, Grep, Glob, Write
|
||||
---
|
||||
|
||||
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".
|
||||
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", with code health (`~/.claude/CLAUDE.md` → "Shared goal") among the goals unless the README voids it.
|
||||
|
||||
For each override:
|
||||
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
---
|
||||
name: principles-auditor
|
||||
description: "Use this agent for larv-review's architecture pass: one yardstick checked against the whole project."
|
||||
tools: Read, Grep, Glob
|
||||
description: "Use this agent for larv-review's principles pass: one yardstick checked against the whole project."
|
||||
tools: Read, Grep, Glob, Write
|
||||
---
|
||||
|
||||
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`.
|
||||
You check one yardstick against the whole project: every principle in the file you are handed, or every goal under the project's `README.md` → `## Goals`, with code health (`~/.claude/CLAUDE.md` → "Shared goal") unless the README voids it.
|
||||
|
||||
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.
|
||||
|
||||
|
||||
@@ -1,7 +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
|
||||
tools: Read, Grep, Glob, Write
|
||||
---
|
||||
|
||||
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.
|
||||
@@ -46,7 +46,7 @@ Before anything else, **read the shared principles** at `~/.claude/principles/`.
|
||||
|
||||
## Your Output Format
|
||||
|
||||
Report only a defect a persona hits, a requirement of the plan or the README's goals that the change breaks, or a breach of a technical principle. Friction that is none of these is not a finding.
|
||||
Report only a defect a persona hits, a requirement of the plan, the README's goals or code health (`~/.claude/CLAUDE.md` → "Shared goal", unless the README voids it) that the change breaks, or a breach of a technical principle. Friction that is none of these is not a finding.
|
||||
|
||||
Verdict, severities and rounds: ~/.claude/skills/larv-review/review-findings.md. After the verdict:
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
name: prose-reviewer
|
||||
description: "Use this agent for larv-review's prose pass."
|
||||
tools: Read, Grep, Glob
|
||||
tools: Read, Grep, Glob, Write
|
||||
---
|
||||
|
||||
You read the prose as someone who did not write it: you see only what it says, never what the author meant.
|
||||
@@ -35,4 +35,4 @@ The prompt hands you these. Beyond them, read only what a finding needs checking
|
||||
|
||||
1. **What the diff touched**: every markdown line, comment and printed text, such as help or an error, that the diff adds or changes.
|
||||
2. **What the review cited**: each section the prompt names, with the code it governs.
|
||||
3. **Every prose file the repo owns**, when the prompt says the architecture pass ran. This sweep catches files that grew a paragraph per chunk, which no single diff shows.
|
||||
3. **Every prose file the repo owns**, when the prompt says the architecture pass's trigger fired. This sweep catches files that grew a paragraph per chunk, which no single diff shows.
|
||||
|
||||
@@ -2,7 +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
|
||||
tools: Bash, Read, Grep, Glob, Write
|
||||
---
|
||||
|
||||
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.
|
||||
@@ -12,7 +12,7 @@ You are an elite stability-focused code reviewer with deep expertise in defensiv
|
||||
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 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 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.
|
||||
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. Make scratch work with Bash, since Write is for your report alone. Put it 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. **Mutation-test the changed lines.** Run the project's documented mutation command, or else a widely deployed mutation tool for the language: cargo-mutants for Rust, Infection for PHP, mutmut for Python, Stryker for JavaScript and TypeScript. Limit it to the lines the change adds or modifies, through the tool's own option where it has one (cargo-mutants `--in-diff <diff file>`, Infection `--git-diff-lines`, Stryker `--mutate <file>:<lines>`); otherwise mutate only the changed files and keep only the mutants on changed lines. Run it through the project's tooling, as in step 4, on a scratch copy: the tools write files. Report its wall time and mutant count in Coverage & Verification, or why nothing was mutated. Ignore a surviving mutant that leaves behaviour unchanged, or changes only message or log text no caller or user depends on. Report one 🟡 per test to add or strengthen, naming the surviving mutants it would catch.
|
||||
6. **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.
|
||||
@@ -24,6 +24,8 @@ You are an elite stability-focused code reviewer with deep expertise in defensiv
|
||||
|
||||
For every piece of code you review, systematically evaluate these categories. For a per-PR reviewer, breaking existing callers (#1), growth that shouldn't exist (#2), built-in ambiguity (#3), data corruption (#7), and security holes (#9) carry the most weight.
|
||||
|
||||
The rules behind these checks are the principles read in First Steps, step 2; a check names only where to look.
|
||||
|
||||
### 1. Backward Compatibility, Blast Radius & Rollout
|
||||
"Breaking things" is mostly about impact on existing callers and contracts, not the new code in isolation.
|
||||
- What calls or depends on the changed code? Trace the callers.
|
||||
@@ -45,11 +47,11 @@ Before judging how well code works, judge whether it should exist. Every line is
|
||||
- Growth whose whole fix is deletion — unasked additions, dead code, speculative abstraction, an unjustified dependency — breaks KISS: a 🔴. A "could be smaller" rewrite is a 🟡.
|
||||
|
||||
### 3. Ambiguity & Implicit State
|
||||
Catch behavior that is unclear or under-specified — "building in ambiguousness." Cross-check the principles: make invalid states unrepresentable, validate/build DTOs early, explicit state machines, explicit over implicit.
|
||||
Catch behavior that is unclear or under-specified — "building in ambiguousness."
|
||||
- Is stringly-typed or loosely-typed data used where an enum/DTO would make invalid states unrepresentable?
|
||||
- Is input parsed into a strict DTO at the boundary, or passed down as raw strings to be validated deep inside?
|
||||
- Past the boundary, do types carry the proof? Re-validating at every layer what the type already guarantees is noise that buries the real invariants — deletion-worthy, not defensive.
|
||||
- Is nullability, error semantics, or units ambiguous or undocumented? (timestamps: full ISO datetime in UTC?)
|
||||
- Is nullability, error semantics, or units ambiguous or undocumented?
|
||||
- Does behavior depend on undocumented assumptions or implicit state instead of an explicit state machine?
|
||||
|
||||
### 4. Error Handling & Resilience
|
||||
@@ -82,7 +84,7 @@ Catch behavior that is unclear or under-specified — "building in ambiguousness
|
||||
### 7. Data Integrity & Persistence
|
||||
- Are multi-step writes atomic (one transaction)? Are side effects — events, jobs, mail, outbound HTTP — deferred until after commit? Dispatch-before-commit emits effects for state that may still roll back.
|
||||
- Money: integer minor units or exact decimals, never binary floats; rounding rules explicit.
|
||||
- Time: stored as full ISO datetimes in UTC; arithmetic DST-safe (adding a day ≠ adding 24 h).
|
||||
- Time: arithmetic DST-safe (adding a day ≠ adding 24 h).
|
||||
- Are consumers idempotent under at-least-once delivery (webhooks, queue retries, double-submit)? Where a duplicate would double-charge or double-send, is there an idempotency key or dedup?
|
||||
- Do DB constraints (NOT NULL, unique, FK) mirror what the code assumes, so bad data cannot arrive via another path?
|
||||
- New column on an existing table: what do existing rows contain — is null/default handled or backfilled?
|
||||
@@ -99,7 +101,7 @@ Works-on-fixtures, dies-on-volume is a stability bug.
|
||||
### 9. Security
|
||||
Every PR gets at least this sweep.
|
||||
- Injection: SQL via raw/concatenated queries, shell/command, XSS via unescaped output.
|
||||
- Does every new read and write path authorize access? (principle: grant explicit access to data — every read and write is explicitly authorized.)
|
||||
- Does every new read and write path authorize access?
|
||||
- Secrets: none hardcoded; none leaked into logs, error responses, or stack traces; PII sanitized before logging.
|
||||
- Mass assignment/over-posting on model-bound input; uploaded files and paths validated (traversal); user-supplied URLs constrained (SSRF).
|
||||
- Crypto: vetted primitives only, constant-time comparison for secrets, CSPRNG for tokens.
|
||||
@@ -116,20 +118,18 @@ Every PR gets at least this sweep.
|
||||
- **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.
|
||||
|
||||
### 11. Tests
|
||||
- Does the PR ship tests for the new behavior? (principle: most code has automated tests, and tests come first.)
|
||||
- Does the PR ship tests for the new behavior?
|
||||
- Do they exercise the risky and error paths, not just the happy path?
|
||||
- Does a mutant of a changed line survive (First Steps, step 5)? (principle: every mutant of a changed line fails a test, unless the mutant leaves behaviour unchanged.)
|
||||
- Does a mutant of a changed line survive (First Steps, step 5)?
|
||||
- Was a test deleted while the behaviour it pinned remains? Flag it; restore the test.
|
||||
- Were tests and implementation changed together in a way that could mask a regression — e.g. an assertion weakened to make a test pass? Flag it; these should be separate changes.
|
||||
- Would each test fail if the behavior regressed? Watch for assertion-free tests, tautological asserts, and mocks so broad the test exercises the mock instead of the code.
|
||||
- Tests are code too: prefer extending an existing test with an assertion over adding a near-duplicate; flag overlapping tests that pin the same behavior twice, and tests of framework behavior or trivial pass-throughs — maintenance cost without protection.
|
||||
- Test data: properly randomised UUIDs, never `aaaa-0000`-style placeholders.
|
||||
- Does each test earn its keep, as the technical principles' test bullet says? Look at where its expected values come from, what it asserts, what it mocks, what wording it pins, whether another test already pins the behaviour, and whether it sleeps or reads the wall clock.
|
||||
- Are there untestable side effects that should be refactored?
|
||||
|
||||
|
||||
## Output Format
|
||||
|
||||
Report only a defect, a requirement of the plan or the README's goals that the change breaks, a breach of a technical principle, and the places the prompt hands you. A finding that is none of these is noise, however true: leave it out.
|
||||
Report only a defect, a requirement of the plan, the README's goals or code health (`~/.claude/CLAUDE.md` → "Shared goal", unless the README voids it) that the change breaks, a breach of a technical principle, and the places the prompt hands you. A finding that is none of these is noise, however true: leave it out.
|
||||
|
||||
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, mutation — 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
|
||||
|
||||
@@ -1,7 +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
|
||||
tools: Read, Grep, Glob, WebFetch, WebSearch, Write
|
||||
---
|
||||
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.
|
||||
|
||||
@@ -30,7 +30,7 @@ You are an elite Systems Architect with decades of experience designing software
|
||||
- An external contract shaped for the consumer's task, evolvable without breaking them
|
||||
- One implementation per concept — duplication only with a stated, deliberate reason
|
||||
- Methods, files, and modules that each hold a single responsibility — overgrown ones get split
|
||||
- Units that fit in a head — the thresholds of Fits in a head, crossed only with a stated reason
|
||||
- Units that fit in a head — the fractal test of Fits in a head
|
||||
|
||||
Short-term pragmatism on these points compounds into long-term decay. Push back firmly when asked to compromise on them. Pragmatism is welcome on implementation details, not on structural choices. A change that violates one of these fundamentals is a 🔴, never softened to "the one change I'd make before merge", "acceptable for now", or "worth doing later".
|
||||
|
||||
@@ -40,15 +40,9 @@ Short-term pragmatism on these points compounds into long-term decay. Push back
|
||||
|
||||
## Fits in a head
|
||||
|
||||
Working memory holds about seven chunks (Code That Fits in Your Head). So at every altitude — system, component, class, method — the thing in view must be graspable with the details below abstracted away. This is the fractal test: zoom in anywhere and what you see still fits. A design only comprehensible by holding two levels at once has failed it, however clean each level looks in isolation.
|
||||
At every altitude — system, component, class, method — the thing in view must be graspable with the details below abstracted away. This is the fractal test: zoom in anywhere and what you see still fits. A design only comprehensible by holding two levels at once has failed it, however clean each level looks in isolation. A new developer should explain what the system does from its structure in under 30 minutes; where they cannot, find the level that fails.
|
||||
|
||||
The thresholds, each a prompt and never a verdict:
|
||||
- a new developer explains what the system does from its structure in under 30 minutes
|
||||
- a system of a handful of components; a component of a handful of modules
|
||||
- a call chain reaches persistence or response in at most ~7 hops
|
||||
- a method: cyclomatic complexity at most **7**; fits an **80×24 terminal window** (~24 lines); at most **~7 things a reader must track at once** (variables, branches, in-flight states — the chunks of working memory)
|
||||
|
||||
Crossing one demands action or a stated reason. A unit over a threshold is first a prompt to check responsibilities: if it holds several, split along the concept boundaries. If it genuinely holds one but still crosses, that is not a pass — decompose it into named steps a reader can follow one at a time, or record the concrete reason it must stay whole (a table-like switch, a generated file). "Single responsibility" answers the count of responsibilities, never the count of things a reader must hold in their head. Under the thresholds: leave it and say so. Where a merge gate exists, the method thresholds run in its static analysis as machine rules — a recorded suppression carrying its concrete reason is the stated reason this section demands (see Delivery). A core method nobody can hold in their head is a structural finding, never style: the test applies at every zoom level, method included.
|
||||
The limits per level are the technical principle "About seven things per level" in `~/.claude/principles/technical-principles.md`. A unit over one is first a prompt to check responsibilities: if it holds several, split along the concept boundaries. If it holds one, decompose it into named steps a reader can follow one at a time, or let it stay whole for a reason the principle accepts. "Single responsibility" answers the count of responsibilities, never the count of things a reader must hold in their head. A unit past a limit with no recorded reason is a 🟡. It is a 🔴 only where you name what a reader cannot hold: the failed fractal test is the defect, never the count. A core method nobody can hold in their head is a structural finding, never style.
|
||||
|
||||
## Operating Mode: Staged
|
||||
|
||||
@@ -142,7 +136,7 @@ How a change ships — merge gate, pipeline, deployment, dependencies — is a d
|
||||
|
||||
- **One enforced path to production.** The pipeline is the only way code reaches any environment. A manual deploy lane or a human-waivable gate is a bypass, and the bypass is the finding — a gate people route around launders unverified changes as verified.
|
||||
- **The merge gate is fast, deterministic, and blocks on both tests and static analysis.** It admits only quick, hermetic checks (minutes, not an hour); slow or probabilistic suites run scheduled outside it (see Testability). A slow gate breeds long-lived branches; incomplete work hides behind flags with an owner and an expiry, not behind a branch.
|
||||
- **Static analysis is its own quality dimension, not a kind of testing.** Tests sample points in the input space; types and analyzers quantify over it. Types at full strictness, warnings-as-errors, and the Fits in a head thresholds as machine rules belong in the gate from the first commit — strictness is near-impossible to retrofit, so it is skeleton, never ceremony.
|
||||
- **Static analysis is its own quality dimension, not a kind of testing.** Tests sample points in the input space; types and analyzers quantify over it. Types at full strictness and warnings-as-errors belong in the gate from the first commit — strictness is near-impossible to retrofit, so it is skeleton, never ceremony.
|
||||
- **Deployment is designed, not improvised.** Build one artifact and promote it — a per-environment build voids what the gate verified. Config comes from the environment. Rollback is a standing requirement, which forces expand–contract migrations with N-1 compatibility between running code and schema; an unrollbackable change is a defect class. A deploy completes when the post-deploy smoke confirms the surface (see Testability).
|
||||
- **Dependencies follow a strategy.** Each one earns its existence (Core Philosophy); versions are locked; updates flow small-and-often through the gate via automation. Automation presupposes the gate — on a gateless project the finding is the missing gate, not the missing bot.
|
||||
- **The horizon prices the ceremony, never the skeleton.** Gate, one-command deploy path, lockfiles, and analyzer strictness are day-one requirements at any production horizon. Environment count, progressive delivery (canary, blue-green), and provenance depth are ceremony, priced by the recorded horizon and blast radius ("Hunt the imagined requirement" cuts the unrecorded). The Stage 0 promotion event converts a spike's deferral into a finding: re-review on promotion includes this front.
|
||||
@@ -151,7 +145,7 @@ How a change ships — merge gate, pipeline, deployment, dependencies — is a d
|
||||
|
||||
You are not a per-PR reviewer. The **stability-reviewer** runs on every change for code-level safety; you run deliberately, every so often, to check the system is still aligned — right goals, right contract, right foundations, sound structure. When you do look at a specific PR, it is because the work touches architectural fundamentals or reopens foundational choices, not for routine line-level review.
|
||||
|
||||
**Verdict and severities: ~/.claude/skills/larv-review/review-findings.md.** A violation of a non-negotiable fundamental — functional-core/shell entanglement, a unit past a Fits in a head threshold without a stated reason, a method or file carrying more than one responsibility, unreasoned duplication of a core concept, or a broken/leaky external contract — is a 🔴: lead with it, and name the concrete restructuring. The most common instance: a pure transformation (a deterministic input→output computation) entangled inside an imperative-shell or orchestration method, where it could be a named, separately-testable function. The architectural defect being real, not its line count or "how much it works today," sets the severity; rate a non-fundamental finding by its eventual cost — the recorded horizon sets that cost; fundamentals stay 🔴 at every horizon (Core Philosophy: rigor follows the horizon).
|
||||
**Verdict and severities: ~/.claude/skills/larv-review/review-findings.md.** A violation of a non-negotiable fundamental — functional-core/shell entanglement, a unit failing the fractal test of Fits in a head, a method or file carrying more than one responsibility, unreasoned duplication of a core concept, or a broken/leaky external contract — is a 🔴: lead with it, and name the concrete restructuring. The most common instance: a pure transformation (a deterministic input→output computation) entangled inside an imperative-shell or orchestration method, where it could be a named, separately-testable function. The architectural defect being real, not its line count or "how much it works today," sets the severity; rate a non-fundamental finding by its eventual cost — the recorded horizon sets that cost; fundamentals stay 🔴 at every horizon (Core Philosophy: rigor follows the horizon).
|
||||
|
||||
Every finding, except a place the prompt hands you, names a concrete later change this PR makes harder, such as "a second forge needs edits in four modules"; a concern that names none is too vague to check, so leave it out.
|
||||
|
||||
@@ -169,7 +163,7 @@ Focus on architectural alignment:
|
||||
- Does it add complexity that could be avoided — including by relaxing the requirement that forces it? If a simpler design gets almost the same result, name it and the behavior delta rather than accepting the complex shape as given.
|
||||
- Does it duplicate a concept that already exists instead of reusing it? (see "One concept, one implementation".)
|
||||
- Does it build generality for a scale or future the Stage 0 record doesn't name? Same weight as unreasoned duplication (see "Hunt the imagined requirement").
|
||||
- Does it push a core unit past a Fits in a head threshold?
|
||||
- Does it push a core unit past a limit of "About seven things per level" in `~/.claude/principles/technical-principles.md`?
|
||||
- Does it match the patterns documented in the README?
|
||||
- Take the language and framework as given — only reopen foundational choices when the work itself does (see Evaluating Foundational Choices).
|
||||
|
||||
@@ -183,7 +177,7 @@ This is where unjustified duplication and accidental complexity get caught. Run
|
||||
|
||||
1. **Inventory the core concepts.** List the handful of ideas the system is really built on (e.g. "the navigation menu", "a list+filter+paginate page", "a form", "the request context"). For each, find *every* place it is implemented.
|
||||
2. **One concept, one implementation — or a stated reason.** If a concept is implemented more than once, each copy must point to a concrete reason it cannot be the shared one. No reason → collapse to one. Slight, undesigned variation between copies is the signature of copy-paste drift, not deliberate design.
|
||||
3. **Trace to the bottom — and walk the long chains.** Follow the central data structures and abstractions down to their foundation. Can you hold the core in your head? Is anything obscure, implicit, or magical on the way down? A core you cannot explain to the bottom is the defect, even when every layer looks tidy. Then pick the system's key operations and follow each call chain end-to-end (entry point → … → persistence/response). Every hop must add a decision, a transformation, or a boundary that earns its keep; a pass-through layer that only forwards is change amplification plus cognitive load with no payoff — name the collapse concretely (which layer folds into which). A chain, like a unit, must fit in a head (the hop threshold under Fits in a head).
|
||||
3. **Trace to the bottom — and walk the long chains.** Follow the central data structures and abstractions down to their foundation. Can you hold the core in your head? Is anything obscure, implicit, or magical on the way down? A core you cannot explain to the bottom is the defect, even when every layer looks tidy. Then pick the system's key operations and follow each call chain end-to-end (entry point → … → persistence/response). Every hop must add a decision, a transformation, or a boundary that earns its keep; a pass-through layer that only forwards is change amplification plus cognitive load with no payoff — name the collapse concretely (which layer folds into which). A chain, like a unit, must fit in a head (the limit on hops in "About seven things per level" in `~/.claude/principles/technical-principles.md`).
|
||||
4. **Naming and placement.** If a name, or its location in the tree, does not tell a new reader what it is and where it belongs, that is a defect — not a note. Names come from the domain glossary; the hierarchy should mirror the architecture with no translation. When a subsystem has been consolidated into its own folder/namespace, confirm *every* member lives there: a collaborator stranded in the parent (typically one the refactor didn't scope in, so it predates the move) breaks the mirror as badly as a misnamed file — a finding even when nothing imports it wrongly. Check both directions: the sibling in the parent that should have moved in, and the file inside the subfolder that actually belongs to a different layer. Ask of each remaining sibling in the parent: why is this *here* and not *there* with its peers? "It predated the move" is not a reason. Enumerate what's left in the parent namespace and justify each one, rather than only inspecting the files that changed.
|
||||
5. **A flat directory is a smell at scale.** Count the files in each source directory. One folder holding many modules with no sub-structure (rule of thumb: **more than ~15–20 source files**, or a directory a newcomer can't skim to locate a concern) hides the architecture instead of mirroring it — the larger it grows, the more it costs to navigate, and "we'll group it later" never comes. This is a structural defect, not cosmetic polish: flag it and **propose a concrete grouping by concern**, naming which files go into which folder (e.g. `http/`, `auth/`, `admin/`, `plugin-host/`, `ui/`), derived from the core concepts the inventory already surfaced; co-locate tests with their module. Push for the reorganization rather than merely noting the count. The only thing that excuses a large flat tree is the project documenting it as a deliberate, reasoned deviation (and even then, re-test the reason as the file count climbs).
|
||||
6. **Price the reasoned complexity too.** Essential-looking complexity has a requirement behind it. For each hotspot that survives the steps above, name that requirement, then sketch the design without it. When a much simpler near-equivalent exists, report the trade as a finding: the simpler shape, the exact functionality delta, and the complexity saved. A requirement nobody has priced is not a decision — offer the trade once, plainly, and let the owner accept or reject it.
|
||||
|
||||
Executable
+10
@@ -0,0 +1,10 @@
|
||||
#!/usr/bin/env python3
|
||||
import os
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
|
||||
|
||||
from chunk_preflight import main
|
||||
|
||||
sys.exit(main.main(sys.argv[1:], os.environ))
|
||||
@@ -0,0 +1,177 @@
|
||||
"""The next chunk's pick: the item the chunk takes first, weighed against the last release cut, and what the default branch holds for the pick."""
|
||||
import dataclasses
|
||||
import re
|
||||
|
||||
from git_repo import commits_since, file_at, git, newest_release_tag
|
||||
from failure import Failure
|
||||
from todo_table import Item, items, next_item, release_of, renames
|
||||
from markdown_text import sections
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class LastCut:
|
||||
"""What the default branch holds about its last release, which chunk_item weighs the plan against."""
|
||||
# The newest v* tag, None where the branch has none.
|
||||
tag: str | None | Failure
|
||||
# CHANGELOG.md's text, empty where the branch holds none.
|
||||
changelog: str | Failure
|
||||
# How many commits follow the tag, or make up the branch where it has none.
|
||||
commits: int | Failure
|
||||
# todo.md's text at the tag and at each later commit that changed it, oldest first, as named_releases reads them; empty without a tag.
|
||||
todos_since: list[str] | Failure
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Upcoming:
|
||||
"""The next release, and whether work has landed towards it, as `~/.claude/CLAUDE.md` → "Working loop" uses both."""
|
||||
# The earliest release after the last cut that todo.md has named since that cut or the plan holds; without a cut, the plan's earliest. None where there is none.
|
||||
release: tuple[int, int, int] | None
|
||||
# Whether it is the plan's earliest release. Without a cut, it always is, even where the plan holds no item.
|
||||
is_earliest: bool
|
||||
# Whether work has landed towards it: one or more changes are unreleased, as unreleased_changes counts them.
|
||||
landed: bool | Failure
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Next:
|
||||
"""The plan's earliest release is the next release."""
|
||||
# None where the plan holds no item.
|
||||
release: tuple[int, int, int] | None
|
||||
# The item the next chunk takes first, next_item's pick; None where every item waits or the plan holds none.
|
||||
item: Item | None
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Cut:
|
||||
"""The plan's earliest release is the last cut's version or earlier."""
|
||||
release: tuple[int, int, int]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class ReadyToCut:
|
||||
"""The next release holds no item, and work has landed towards it."""
|
||||
# The next release, None where todo.md has named none since the cut.
|
||||
release: tuple[int, int, int] | None
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Unplanned:
|
||||
"""The next release holds no item, and no work has landed towards it."""
|
||||
# The next release, None where todo.md has named none since the cut.
|
||||
release: tuple[int, int, int] | None
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Unknown:
|
||||
"""todo.md's texts since the cut, or the changes since it, cannot be read."""
|
||||
|
||||
|
||||
# How the plan stands to the last cut, with the item the next chunk takes first where there is one.
|
||||
Pick = Next | Cut | ReadyToCut | Unplanned | Unknown
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class DefaultPlan:
|
||||
"""What the default branch, as last fetched, holds for chunk_item."""
|
||||
# todo.md's text, empty where the branch holds none.
|
||||
todo: str | Failure
|
||||
cut: LastCut
|
||||
|
||||
|
||||
def default_plan(root: str, ref: str) -> DefaultPlan:
|
||||
"""What ref, the default branch as last fetched, holds for the pick, read in the checkout at root."""
|
||||
tag = newest_release_tag(ref, root)
|
||||
commits = tag if isinstance(tag, Failure) else commits_since(tag, ref, root)
|
||||
return DefaultPlan(file_at(ref, "todo.md", root), LastCut(tag, file_at(ref, "CHANGELOG.md", root), commits, todos_since(tag, ref, root)))
|
||||
|
||||
|
||||
def todos_since(tag: str | None | Failure, ref: str, cwd: str) -> list[str] | Failure:
|
||||
"""LastCut.todos_since, read from ref in cwd. A pull request's own commits do not count, only the merge that landed it: --first-parent."""
|
||||
if not isinstance(tag, str):
|
||||
return []
|
||||
changed = git("log", "--first-parent", "--reverse", "--format=%H", f"{tag}..{ref}", "--", "todo.md", cwd=cwd)
|
||||
if isinstance(changed, Failure):
|
||||
return changed
|
||||
texts = []
|
||||
for commit in [tag, *changed.split()]:
|
||||
text = file_at(commit, "todo.md", cwd)
|
||||
if isinstance(text, Failure):
|
||||
return text
|
||||
texts.append(text)
|
||||
return texts
|
||||
|
||||
|
||||
def chunk_item(found: list[Item], cut: LastCut) -> Pick:
|
||||
"""The pick from todo.md's items, weighed against the last cut. Routing and chunk-preflight both pick with it, so they name one item."""
|
||||
upcoming = next_release(found, cut)
|
||||
return standing(upcoming, next_item(found)) if isinstance(upcoming, Upcoming) else upcoming
|
||||
|
||||
|
||||
def next_release(found: list[Item], cut: LastCut) -> Upcoming | Cut | Unknown:
|
||||
"""The next release after cut, and whether work has landed towards it. found holds the plan's items.
|
||||
|
||||
Cut where the plan files items under the last cut's version or earlier, and Unknown where todo.md's texts since the cut cannot be read.
|
||||
"""
|
||||
earliest = min((item.release for item in found), default=None)
|
||||
cut_version = version_of(cut.tag)
|
||||
if cut_version is None:
|
||||
return Upcoming(earliest, True, landed(cut))
|
||||
if earliest is not None and earliest <= cut_version:
|
||||
return Cut(earliest)
|
||||
named = named_releases(cut.todos_since)
|
||||
if isinstance(named, Failure):
|
||||
return Unknown()
|
||||
after = {release for release in named if release > cut_version}
|
||||
if earliest is not None:
|
||||
after.add(earliest)
|
||||
release = min(after, default=None)
|
||||
return Upcoming(release, earliest is not None and earliest == release, landed(cut))
|
||||
|
||||
|
||||
def version_of(tag: str | None | Failure) -> tuple[int, int, int] | None:
|
||||
"""The version x.y.z named by tag, the newest v* tag; None where it names none."""
|
||||
tagged = re.fullmatch(r"v([0-9]+\.[0-9]+\.[0-9]+)", tag) if isinstance(tag, str) else None
|
||||
return None if tagged is None else release_of(tagged[1])
|
||||
|
||||
|
||||
def landed(cut: LastCut) -> bool | Failure:
|
||||
"""Whether work has landed since cut: one or more changes are unreleased."""
|
||||
changes = unreleased_changes(cut)
|
||||
return changes if isinstance(changes, Failure) else changes > 0
|
||||
|
||||
|
||||
def standing(upcoming: Upcoming, first: Item | None) -> Next | ReadyToCut | Unplanned | Unknown:
|
||||
"""How the plan stands to upcoming, the next release. first is next_item's pick, which the pick holds where it is Next.
|
||||
|
||||
Unknown where the next release holds no item and the unreleased changes cannot be counted.
|
||||
"""
|
||||
if upcoming.is_earliest:
|
||||
return Next(upcoming.release, first)
|
||||
if isinstance(upcoming.landed, Failure):
|
||||
return Unknown()
|
||||
return ReadyToCut(upcoming.release) if upcoming.landed else Unplanned(upcoming.release)
|
||||
|
||||
|
||||
def unreleased_changes(cut: LastCut) -> int | Failure:
|
||||
"""How many changes are unreleased, as `~/.claude/CLAUDE.md` → "Working loop" counts them: the entries under ## Unreleased, or the commits since the tag where CHANGELOG.md has no such section or cannot be read."""
|
||||
entries = unreleased_entries(cut.changelog) if isinstance(cut.changelog, str) else None
|
||||
return cut.commits if entries is None else entries
|
||||
|
||||
|
||||
def unreleased_entries(changelog: str) -> int | None:
|
||||
"""How many top-level `- ` entries CHANGELOG.md holds under ## Unreleased; None without that section."""
|
||||
found = sections(changelog).get("Unreleased")
|
||||
return None if found is None else sum(line.startswith("- ") for line in found[0].splitlines())
|
||||
|
||||
|
||||
def named_releases(todos: list[str] | Failure) -> set[tuple[int, int, int]] | Failure:
|
||||
"""Each release the todo.md texts, oldest first, file items under. A release leaves the set when a text marks it renamed, and returns when a later text files items under it again. A text whose items or marks do not parse names none, except the newest: where its marks do not parse, it returns that Failure, since the release they should have excluded would read as finished."""
|
||||
if isinstance(todos, Failure):
|
||||
return todos
|
||||
if todos and isinstance(newest := renames(todos[-1]), Failure):
|
||||
return newest
|
||||
named: set[tuple[int, int, int]] = set()
|
||||
for text in todos:
|
||||
plan, marked = items(text), renames(text)
|
||||
if isinstance(plan, list) and isinstance(marked, set):
|
||||
named = (named - marked) | {item.release for item in plan}
|
||||
return named
|
||||
@@ -0,0 +1,76 @@
|
||||
"""The pure choices the preflight's steps act on."""
|
||||
import pathlib
|
||||
import re
|
||||
|
||||
from chunk_pick import chunk_item, Cut, LastCut, ReadyToCut, Unknown, Unplanned
|
||||
from failure import Failure
|
||||
from chunk_preflight.gathered import Forge, NoItem, Plan
|
||||
from todo_table import item_details, items, NoItemsTable, version
|
||||
|
||||
# The command each forge's CLI lists pull requests with; pulls_command adds the flags that pick their rows and fields.
|
||||
PULLS_LIST: dict[Forge, tuple[str, ...]] = {"gh": ("gh", "pr", "list"), "tea": ("tea", "pulls", "list")}
|
||||
|
||||
|
||||
def planned(todo: str | Failure, cut: LastCut, default: str) -> Plan | NoItem:
|
||||
"""The plan in todo, the default branch's todo.md, with the item the next chunk takes first, chunk_pick.chunk_item's pick; else why there is none."""
|
||||
where = f"{default}'s todo.md"
|
||||
if isinstance(todo, Failure):
|
||||
return NoItem(f"{where} cannot be read: {todo.reason}.")
|
||||
found = items(todo)
|
||||
if isinstance(found, NoItemsTable):
|
||||
return NoItem(f"{where} holds no items table.")
|
||||
if isinstance(found, Failure):
|
||||
return NoItem(f"{where} cannot be read: {found.reason}.")
|
||||
pick = chunk_item(found, cut)
|
||||
if isinstance(pick, Cut):
|
||||
return NoItem(f"{where} files items under release {version(pick.release)}, which is not after the last cut, {cut.tag}; ask the human which release they belong to.")
|
||||
if isinstance(pick, Unknown):
|
||||
return NoItem(f"{where} may hold no item for the next release after the last cut, {cut.tag}: todo.md's texts since then, or the count of changes since then, cannot be read. Find the next release yourself.")
|
||||
if isinstance(pick, ReadyToCut | Unplanned):
|
||||
upcoming = f"release {version(pick.release)}, the next after the last cut, {cut.tag}" if pick.release else f"the next release after the last cut, {cut.tag}"
|
||||
if isinstance(pick, ReadyToCut):
|
||||
return NoItem(f"{where} holds no item for {upcoming}, and changes are unreleased, so that release is finished and ready to cut. The working loop stops here. If todo.md renamed that release instead, add `- <old release> renamed to <new release>` to todo.md's `## Renamed` section.")
|
||||
return NoItem(f"{where} holds no item for {upcoming}, and no change is unreleased, so that release is to be planned first.")
|
||||
first = pick.item
|
||||
if first is None:
|
||||
return NoItem(f"every item of release {version(pick.release)} in {where} waits." if pick.release is not None else f"{where}'s items table holds no item.")
|
||||
details = item_details(todo)
|
||||
detail = details.get(first.id, "") if isinstance(details, dict) else f"(todo.md's details cannot be read: {details.reason})"
|
||||
return Plan(found, first, f"{first.tagline}\n\n{detail}".strip())
|
||||
|
||||
|
||||
def worktree_on(porcelain: str, branch: str) -> pathlib.Path | None:
|
||||
"""The worktree on branch, in what `git worktree list --porcelain` printed; None where none is."""
|
||||
for block in porcelain.split("\n\n"):
|
||||
fields = dict(line.partition(" ")[::2] for line in block.splitlines())
|
||||
if fields.get("branch") == f"refs/heads/{branch}":
|
||||
return pathlib.Path(fields["worktree"])
|
||||
return None
|
||||
|
||||
|
||||
def worktree_add(branch: str, path: pathlib.Path, default: str, local: bool, pushed: bool) -> tuple[list[str], str]:
|
||||
"""The git arguments that add branch's worktree at path, and how it comes to be: on the local branch, else on a new one tracking origin's, else on a new one off default."""
|
||||
if local:
|
||||
return ["worktree", "add", "--quiet", str(path), branch], f"added on the branch {branch}, which existed already."
|
||||
if pushed:
|
||||
return ["worktree", "add", "--quiet", "--track", "-b", branch, str(path), f"origin/{branch}"], f"added on the new branch {branch}, made off origin/{branch}."
|
||||
# --no-track: tracking the default branch would point a bare `git push` at it.
|
||||
return ["worktree", "add", "--quiet", "--no-track", "-b", branch, str(path), default], f"added on the new branch {branch}, made off {default}."
|
||||
|
||||
|
||||
def forge_of(origin_url: str) -> Forge:
|
||||
return "gh" if "github.com" in origin_url else "tea"
|
||||
|
||||
|
||||
def pulls_command(forge: Forge, branch: str) -> list[str]:
|
||||
"""The command that lists open pull requests: gh only branch's, by number and URL; tea every one, by index, head and URL, for facts.open_pulls to pick branch's."""
|
||||
if forge == "gh":
|
||||
return [*PULLS_LIST["gh"], "--head", branch, "--json", "number,url", "--template", "{{range .}}{{.number}}\t{{.url}}\n{{end}}"]
|
||||
return [*PULLS_LIST["tea"], "--fields", "index,head,url", "--output", "tsv"]
|
||||
|
||||
|
||||
def named_paths(text: str, tracked: list[str]) -> list[tuple[str, int]]:
|
||||
"""Each backticked span in text, in order and once, that names a tracked file or folder, with how many of the tracked files it holds: 1 for a file."""
|
||||
spans = dict.fromkeys(span.removesuffix("/") for span in re.findall(r"`([^`\s]+)`", text))
|
||||
held = ((span, sum(path == span or path.startswith(f"{span}/") for path in tracked)) for span in spans)
|
||||
return [(span, count) for span, count in held if count]
|
||||
@@ -0,0 +1,106 @@
|
||||
"""The lines the preflight prints, stated from what it gathered."""
|
||||
from todo_table import bundle_candidates, BUNDLE_MAX_R, Item, ships_alone, version
|
||||
from failure import Failure
|
||||
from chunk_preflight.gathered import Forge, Gathered, ItemFacts, NamedPath, NoItem, Plan, Ran
|
||||
from chunk_pick import LastCut, unreleased_entries
|
||||
from chunk_preflight.choices import PULLS_LIST
|
||||
from markdown_text import quoted
|
||||
|
||||
|
||||
def render(found: Gathered) -> list[str]:
|
||||
"""One `- ` line per fact, then the item's tagline and detail, and what each tool printed."""
|
||||
note = [f"- {found.note}"] if found.note else []
|
||||
head = [*note, f"- {last_release(found.default, found.cut)}"]
|
||||
if isinstance(found.item, NoItem):
|
||||
return [*head, f"- No plan item: {found.item.why} No worktree was made."]
|
||||
return [*head, *item_lines(found.default, found.item)]
|
||||
|
||||
|
||||
def last_release(default: str, release: LastCut) -> str:
|
||||
if isinstance(release.tag, Failure):
|
||||
return f"Last version cut: cannot be read: {release.tag.reason}"
|
||||
cut = f"Last version cut: {release.tag or 'none'}."
|
||||
entries = unreleased_entries(release.changelog) if isinstance(release.changelog, str) else None
|
||||
if entries is not None:
|
||||
return f"{cut} Unreleased: {counted(entries, 'entry', 'entries')} under CHANGELOG.md → ## Unreleased."
|
||||
since = f"since {release.tag}" if release.tag else f"on {default}"
|
||||
commits = f"the commits {since} cannot be counted: {release.commits.reason}" if isinstance(release.commits, Failure) else f"{counted(release.commits, 'commit', 'commits')} {since}"
|
||||
changelog = f"CHANGELOG.md cannot be read: {release.changelog.reason}" if isinstance(release.changelog, Failure) else "no ## Unreleased in CHANGELOG.md"
|
||||
return f"{cut} Unreleased: {commits}; {changelog}."
|
||||
|
||||
|
||||
def item_lines(default: str, item: ItemFacts) -> list[str]:
|
||||
first = item.plan.first
|
||||
worktree = item.worktree.reason if isinstance(item.worktree, Failure) else f"{item.worktree.path}, {item.worktree.how}"
|
||||
return [
|
||||
f"- The earliest release in {default}'s todo.md: {version(first.release)}. Its first item that does not wait: item {first.id}, {levels(first)}.",
|
||||
f"- Worktree: {worktree}",
|
||||
f"- Open pull requests from {item.plan.branch}: {pulls_text(item.pulls, item.plan.branch)}",
|
||||
*bundled(item.plan),
|
||||
*named_lines(item.named),
|
||||
f"\nItem {first.id}'s tagline and detail:\n\n{quoted(item.plan.text)}",
|
||||
*(f"\n{printed(shown, done)}" for shown, done in item.tools),
|
||||
]
|
||||
|
||||
|
||||
def pulls_text(pulls: tuple[Forge, Ran | Failure] | None, branch: str) -> str:
|
||||
"""Each open pull request from branch, by its number and URL, or why none can be listed. No title: on a public forge anyone may open one, and its title would reach the worker's prompt."""
|
||||
if pulls is None:
|
||||
return "none, as the checkout has no origin remote."
|
||||
forge, done = pulls
|
||||
shown = " ".join(PULLS_LIST[forge])
|
||||
if isinstance(done, Failure):
|
||||
return f"cannot be listed: `{shown}` {done.reason}"
|
||||
if done.code:
|
||||
return f"cannot be listed: `{shown}` exited {done.code}: {done.stderr.strip()}"
|
||||
return ", ".join(open_pulls(done.stdout, forge, branch)) or "none."
|
||||
|
||||
|
||||
def open_pulls(stdout: str, forge: Forge, branch: str) -> list[str]:
|
||||
"""Each open pull request from branch in the rows pulls_command printed, as `#<number> <URL>`: gh prints only branch's pull requests, as number and URL; tea prints every pull request, as index, head and URL, under a header row."""
|
||||
rows = [line.split("\t") for line in stdout.splitlines()]
|
||||
if forge == "gh":
|
||||
return [f"#{row[0]} {row[1]}" for row in rows if len(row) == 2]
|
||||
return [f"#{row[0]} {row[2]}" for row in rows if len(row) == 3 and row[1] == branch]
|
||||
|
||||
|
||||
def bundled(plan: Plan) -> list[str]:
|
||||
first, candidates = plan.first, bundle_candidates(plan.items, plan.first)
|
||||
if ships_alone(first):
|
||||
return [f"- Item {first.id} has R above {BUNDLE_MAX_R}, so it ships alone."]
|
||||
if not candidates:
|
||||
return [f"- No other item of release {version(first.release)} may join item {first.id}'s chunk."]
|
||||
listed = [f" - item {item.id}, {levels(item)}, S {item.scores['S']}: {item.tagline}" for item in candidates]
|
||||
return [f'- The items of release {version(first.release)} that may join the chunk of item {first.id}, where `~/.claude/CLAUDE.md` → "Working loop" lets them share it:', *listed]
|
||||
|
||||
|
||||
def named_lines(named: list[NamedPath] | Failure) -> list[str]:
|
||||
if isinstance(named, Failure):
|
||||
return [f"- The files the item names: cannot be listed: {named.reason}"]
|
||||
if not named:
|
||||
return ["- The item names no file or folder git tracks."]
|
||||
return ["- The files and folders the item names:", *(f" - `{path.span}`: {size(path)}" for path in named)]
|
||||
|
||||
|
||||
def size(path: NamedPath) -> str:
|
||||
if path.lines is None:
|
||||
return counted(path.files, "file", "files")
|
||||
if isinstance(path.lines, Failure):
|
||||
return f"cannot be read: {path.lines.reason}"
|
||||
return counted(path.lines, "line", "lines")
|
||||
|
||||
|
||||
def printed(shown: str, done: Ran | Failure) -> str:
|
||||
"""What a tool printed and its exit code, under its command line."""
|
||||
if isinstance(done, Failure):
|
||||
return f"`{shown}` {done.reason}"
|
||||
output = "\n".join(part.strip() for part in (done.stdout, done.stderr) if part.strip())
|
||||
return f"`{shown}` exited {done.code}, printing:\n\n{quoted(output)}" if output else f"`{shown}` exited {done.code}, printing nothing."
|
||||
|
||||
|
||||
def levels(item: Item) -> str:
|
||||
return f"L {item.likelihood or 'unscored'}, E + I {item.escape_and_impact or 'unscored'}"
|
||||
|
||||
|
||||
def counted(count: int, one: str, many: str) -> str:
|
||||
return f"{count} {one if count == 1 else many}"
|
||||
@@ -0,0 +1,79 @@
|
||||
"""What the preflight gathers, which facts.render states."""
|
||||
import dataclasses
|
||||
import pathlib
|
||||
import typing
|
||||
|
||||
from failure import Failure
|
||||
from todo_table import Item
|
||||
from chunk_pick import LastCut
|
||||
|
||||
# The CLI that lists a forge's pull requests: gh for a github.com origin, tea for any other.
|
||||
Forge = typing.Literal["gh", "tea"]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Ran:
|
||||
"""A command that ran to its end: its exit code and what it printed."""
|
||||
code: int
|
||||
stdout: str
|
||||
stderr: str
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Plan:
|
||||
"""The default branch's todo.md items, and `first`: the item the next chunk takes first."""
|
||||
items: list[Item]
|
||||
first: Item
|
||||
# first's tagline and detail.
|
||||
text: str
|
||||
|
||||
@property
|
||||
def branch(self) -> str:
|
||||
"""The branch first's worktree is on."""
|
||||
return f"item-{self.first.id}"
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class NoItem:
|
||||
"""Why the plan names no item for the next chunk, as a sentence the worker reads."""
|
||||
why: str
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Worktree:
|
||||
path: pathlib.Path
|
||||
# How it came to be, as the worker reads it.
|
||||
how: str
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class NamedPath:
|
||||
"""A tracked file or folder the item names, with how many tracked files it holds."""
|
||||
span: str
|
||||
files: int
|
||||
# A file's lines, or why they cannot be read; None for a folder.
|
||||
lines: int | Failure | None
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class ItemFacts:
|
||||
"""What the preflight found or made for the plan's first item."""
|
||||
plan: Plan
|
||||
worktree: Worktree | Failure
|
||||
# The forge whose CLI listed the open pull requests, and how it ran; None without an origin remote.
|
||||
pulls: tuple[Forge, Ran | Failure] | None
|
||||
named: list[NamedPath] | Failure
|
||||
# Each tool run in the worktree, by its command line, and how it ran; none without a worktree.
|
||||
tools: list[tuple[str, Ran | Failure]]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Gathered:
|
||||
"""Everything the preflight read and ran, for facts.render to state."""
|
||||
# The default branch's ref, such as origin/main.
|
||||
default: str
|
||||
# Why origin reads as last fetched; None after a fetch.
|
||||
note: str | None
|
||||
cut: LastCut
|
||||
# What was found or made for the plan's first item; else why the plan names none.
|
||||
item: ItemFacts | NoItem
|
||||
@@ -0,0 +1,167 @@
|
||||
"""Find the mechanical facts a chunk starts from, and make its worktree, so its worker starts from them.
|
||||
|
||||
usage: chunk-preflight
|
||||
|
||||
Run it inside a project checkout. loop-claude runs it at the checkout root before each chunk's
|
||||
first worker, before it routes the chunk, and quotes what it prints in the worker's prompt. It
|
||||
fetches origin, when the checkout has that remote, and takes origin's default branch, or else the
|
||||
local main or master. It leaves the checkout as it is, and reads todo.md as the default branch
|
||||
holds it, the plan loop-claude routes on. It prints:
|
||||
|
||||
- the newest v* tag on the default branch, and how many entries the default branch's CHANGELOG.md
|
||||
holds under ## Unreleased, or else how many commits followed the tag;
|
||||
- the next release and its first item that does not wait, the item loop-claude routes on, with
|
||||
its L and E + I. An item waits while it is marked question, or while an item still in todo.md
|
||||
blocks it. Where the newest tag names a version x.y.z, the next release is the earliest after
|
||||
x.y.z that todo.md has named at that tag or since, less a release its ## Renamed section marks
|
||||
renamed. Otherwise it is todo.md's earliest release.
|
||||
Where the next release holds no item, it says so, naming it where todo.md named it since the tag:
|
||||
finished and ready to cut where changes are unreleased (the ## Unreleased entries, or else the
|
||||
commits since the tag), and else to be planned first.
|
||||
Where todo.md's earliest release is x.y.z or earlier, it says todo.md files items under a release
|
||||
already cut;
|
||||
- the item's worktree: a sibling of the checkout named <checkout>-item-<ID>, on the branch
|
||||
item-<ID>. It continues a worktree already on that branch; else it adds one on the local branch,
|
||||
else on a new branch tracking origin's, else on a new branch off the default branch;
|
||||
- the open pull requests whose head is the item's branch, each by its number and URL, as gh lists
|
||||
them on a github.com origin, and else as tea does. No title reaches the output;
|
||||
- the items of that release that a chunk taking the item may take too: those that are not
|
||||
questions, that have R 5 or less, and that no item outside the chunk blocks; none where the
|
||||
item's own R is above 5;
|
||||
- each file or folder git tracks that the item's tagline or detail names in backticks, with a
|
||||
file's lines or a folder's files, and the item's tagline and detail;
|
||||
- what `rank_todo.py --check todo.md`, `larv-review needs-scoring-run <ID>`, `reading-cost` and
|
||||
`larv-review places` print in the worktree, each with its exit code. reading-cost appends to the
|
||||
worktree's docs/reading-cost.md, for the chunk to commit.
|
||||
|
||||
A fact it cannot find it says it cannot, and why, and goes on. A fetch, forge CLI or tool still
|
||||
running after {timeout} seconds, or after the seconds CHUNK_PREFLIGHT_TIMEOUT sets, is stopped; a
|
||||
stopped fetch reads origin as last fetched. With no item, it makes no worktree and runs none of
|
||||
those four tools.
|
||||
|
||||
Exit 1, saying why, on any argument, on a CHUNK_PREFLIGHT_TIMEOUT that is no number of seconds
|
||||
above 0, or when git cannot start or finds no checkout or no default branch.
|
||||
"""
|
||||
import pathlib
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import typing
|
||||
|
||||
from git_repo import commit_exists, default_branch, file_at, git, top
|
||||
from chunk_pick import default_plan
|
||||
from failure import Failure
|
||||
from chunk_preflight.gathered import Forge, Gathered, ItemFacts, NamedPath, NoItem, Plan, Ran, Worktree
|
||||
from chunk_preflight.choices import forge_of, named_paths, planned, pulls_command, worktree_add, worktree_on
|
||||
from chunk_preflight.facts import render
|
||||
|
||||
BIN = pathlib.Path(__file__).resolve().parents[1]
|
||||
# Each tool run in the item's worktree, {item} standing for the item's ID.
|
||||
TOOLS = (("rank_todo.py", "--check", "todo.md"), ("larv-review", "needs-scoring-run", "{item}"), ("reading-cost",), ("larv-review", "places"))
|
||||
# Seconds before a fetch, forge CLI or tool is stopped, so a hung one cannot keep the rest from printing; TIMEOUT_SETTING overrides it.
|
||||
TIMEOUT = 60
|
||||
TIMEOUT_SETTING = "CHUNK_PREFLIGHT_TIMEOUT"
|
||||
|
||||
|
||||
def main(argv: list[str], env: typing.Mapping[str, str]) -> int:
|
||||
if argv in (["-h"], ["--help"]):
|
||||
print(__doc__.strip().format(timeout=TIMEOUT))
|
||||
return 0
|
||||
if argv:
|
||||
print(f"unknown arguments {' '.join(argv)}; usage: chunk-preflight", file=sys.stderr)
|
||||
return 1
|
||||
printed = run(env.get(TIMEOUT_SETTING))
|
||||
if isinstance(printed, Failure):
|
||||
print(printed.reason, file=sys.stderr)
|
||||
return 1
|
||||
print("\n".join(printed))
|
||||
return 0
|
||||
|
||||
|
||||
def run(setting: str | None) -> list[str] | Failure:
|
||||
"""The preflight's lines, given what TIMEOUT_SETTING holds; a Failure where that is no number of seconds, or git finds no checkout or no default branch."""
|
||||
timeout = seconds(setting)
|
||||
if isinstance(timeout, Failure):
|
||||
return timeout
|
||||
root = top()
|
||||
return root if isinstance(root, Failure) else preflight(pathlib.Path(root), timeout)
|
||||
|
||||
|
||||
def seconds(setting: str | None) -> float | Failure:
|
||||
"""The timeout setting as seconds, TIMEOUT where unset; a Failure where it is no number above 0."""
|
||||
if setting is None:
|
||||
return TIMEOUT
|
||||
if re.fullmatch(r"[0-9]+(\.[0-9]+)?", setting) and float(setting) > 0:
|
||||
return float(setting)
|
||||
return Failure(f"{TIMEOUT_SETTING}={setting!r} is no number of seconds above 0")
|
||||
|
||||
|
||||
def preflight(root: pathlib.Path, timeout: float) -> list[str] | Failure:
|
||||
"""Gathers the facts step by step, each step taking what the ones before it found, and renders them; a Failure where the checkout has no default branch."""
|
||||
default = default_branch(stale_ok=True, timeout=timeout)
|
||||
if isinstance(default, Failure):
|
||||
return default
|
||||
ref, note = default
|
||||
held = default_plan(str(root), ref)
|
||||
plan = planned(held.todo, held.cut, ref)
|
||||
item = plan if isinstance(plan, NoItem) else item_facts(root, ref, plan, timeout)
|
||||
return render(Gathered(ref, note, held.cut, item))
|
||||
|
||||
|
||||
def item_facts(root: pathlib.Path, default: str, plan: Plan, timeout: float) -> ItemFacts:
|
||||
worktree = item_worktree(root, plan.branch, default)
|
||||
path = worktree.path if isinstance(worktree, Worktree) else None
|
||||
return ItemFacts(plan, worktree, pull_listing(root, plan.branch, timeout), named_files(plan.text, path or root), tools_run(plan.first.id, path, timeout) if path else [])
|
||||
|
||||
|
||||
def item_worktree(root: pathlib.Path, branch: str, default: str) -> Worktree | Failure:
|
||||
"""The worktree on branch, made where none is; a Failure where git cannot make it, or its path holds something else."""
|
||||
listing = git("worktree", "list", "--porcelain")
|
||||
if isinstance(listing, Failure):
|
||||
return listing
|
||||
if (path := worktree_on(listing, branch)) is not None:
|
||||
return Worktree(path, f"continued, on the branch {branch}.")
|
||||
path = root.parent / f"{root.name}-{branch}"
|
||||
if path.exists():
|
||||
return Failure(f"none made, since {path} exists and holds no worktree on the branch {branch}")
|
||||
args, how = worktree_add(branch, path, default, commit_exists(f"refs/heads/{branch}"), commit_exists(f"refs/remotes/origin/{branch}"))
|
||||
added = git(*args)
|
||||
return Failure(f"none made: {added.reason}") if isinstance(added, Failure) else Worktree(path, how)
|
||||
|
||||
|
||||
def pull_listing(root: pathlib.Path, branch: str, timeout: float) -> tuple[Forge, Ran | Failure] | None:
|
||||
url = git("remote", "get-url", "origin")
|
||||
if isinstance(url, Failure):
|
||||
return None
|
||||
forge = forge_of(url)
|
||||
return forge, ran(pulls_command(forge, branch), root, timeout)
|
||||
|
||||
|
||||
def named_files(text: str, base: pathlib.Path) -> list[NamedPath] | Failure:
|
||||
tracked = git("-C", str(base), "ls-files")
|
||||
if isinstance(tracked, Failure):
|
||||
return tracked
|
||||
return [NamedPath(span, files, line_count(base / span)) for span, files in named_paths(text, tracked.splitlines())]
|
||||
|
||||
|
||||
def line_count(path: pathlib.Path) -> int | Failure | None:
|
||||
"""A file's lines, or why they cannot be read; None for a folder."""
|
||||
if not path.is_file():
|
||||
return None
|
||||
try:
|
||||
return len(path.read_text(encoding="utf-8").splitlines())
|
||||
except (OSError, UnicodeDecodeError) as failure:
|
||||
return Failure(str(failure))
|
||||
|
||||
|
||||
def tools_run(item_id: int, worktree: pathlib.Path, timeout: float) -> list[tuple[str, Ran | Failure]]:
|
||||
commands = [[part.format(item=item_id) for part in tool] for tool in TOOLS]
|
||||
return [(" ".join(command), ran([sys.executable, str(BIN / command[0]), *command[1:]], worktree, timeout)) for command in commands]
|
||||
|
||||
|
||||
def ran(command: list[str], cwd: pathlib.Path, timeout: float) -> Ran | Failure:
|
||||
try:
|
||||
done = subprocess.run(command, capture_output=True, cwd=cwd, encoding="utf-8", errors="replace", stdin=subprocess.DEVNULL, timeout=timeout)
|
||||
except (OSError, subprocess.TimeoutExpired) as failure:
|
||||
return Failure(f"could not finish: {failure}")
|
||||
return Ran(done.returncode, done.stdout, done.stderr)
|
||||
@@ -0,0 +1,516 @@
|
||||
import os
|
||||
import pathlib
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from failure import Failure
|
||||
from chunk_preflight.choices import forge_of, named_paths, planned, worktree_add
|
||||
from chunk_preflight.gathered import Gathered, ItemFacts, NamedPath, NoItem, Ran, Worktree
|
||||
from test_env import isolated_env
|
||||
from chunk_pick import LastCut
|
||||
from chunk_preflight.main import line_count, ran, seconds, TIMEOUT
|
||||
from chunk_preflight.facts import open_pulls, render
|
||||
|
||||
BIN = pathlib.Path(__file__).resolve().parents[1]
|
||||
README = "# Project\n\n## Goals\n\n**Void:** code health, since the plan's scores weigh goal 1 alone.\n\n1. **Achieve:** Work.\n\n## Audience\n\nMe.\n"
|
||||
# Item 3 is the next release's first item that does not wait; 7 waits only on 3, 5 is a question, 8 waits on 5, 9 is in a later release.
|
||||
TODO = """# todo
|
||||
|
||||
## Scoring
|
||||
|
||||
`Score = 100 * V / (2**S + 8)`
|
||||
|
||||
`Bar = 0.1`
|
||||
|
||||
`Next ID = 10`
|
||||
|
||||
## Items
|
||||
|
||||
| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |
|
||||
|---|---|---|---|---|---|---|---|---|---|---|---|
|
||||
| 5 | 0.2.0 | | question | **Ask first.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 90.0 |
|
||||
| 3 | 0.2.0 | | | **Do the next thing.** | 2 | 2 | 3 | 5 | 3 | 1 by 9 | 56.2 |
|
||||
| 7 | 0.2.0 | 3 | | **Do the thing after.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 | 10.0 |
|
||||
| 8 | 0.2.0 | 5 | | **Do the answered thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 | 10.0 |
|
||||
| 9 | 0.3.0 | | | **Do a later thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 90.0 |
|
||||
|
||||
## Details
|
||||
|
||||
### 3. Do the next thing.
|
||||
|
||||
Change `src/app.py`'s `run` and the files under `src`, not `gone.py`.
|
||||
"""
|
||||
# The plan once item 3 has shipped: item 7 no longer waits, and its detail names the files.
|
||||
SHIPPED = TODO.replace("| 3 | 0.2.0 | | | **Do the next thing.** | 2 | 2 | 3 | 5 | 3 | 1 by 9 | 56.2 |\n", "").replace("| 7 | 0.2.0 | 3 |", "| 7 | 0.2.0 | |").replace("### 3. Do the next thing.", "### 7. Do the thing after.")
|
||||
# The plan once release 0.2.0 has shipped all its items: only release 0.3.0's item 9 is left.
|
||||
LATER = TODO[:TODO.index("| 5 |")] + "| 9 | 0.3.0 | | | **Do a later thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 90.0 |\n"
|
||||
# An items table that holds no row.
|
||||
EMPTY = TODO[:TODO.index("| 5 |")]
|
||||
CHANGELOG = "# Changelog\n\n## Unreleased\n\n- One.\n - A nested line.\n- Two.\n\n## 0.1.0\n\n- Old.\n"
|
||||
# What the preflight reads of the last release: tag v0.1.0, two entries under ## Unreleased, and 4 commits since the tag.
|
||||
CUT = LastCut("v0.1.0", CHANGELOG, 4, [])
|
||||
# Two open pull requests, as `tea pulls list --fields index,head,url --output tsv` prints them; anything else exits 1.
|
||||
FAKE_TEA = "#!/bin/sh\n[ \"$*\" = 'pulls list --fields index,head,url --output tsv' ] || exit 1\nprintf 'index\\thead\\turl\\n12\\titem-7\\thttps://forge/pulls/12\\n13\\tother\\thttps://forge/pulls/13\\n'\n"
|
||||
# Item 3's open pull request, as `gh pr list` prints it through the preflight's template; any other arguments exit 1.
|
||||
FAKE_GH = """#!PYTHON
|
||||
import sys
|
||||
if sys.argv[1:] != ["pr", "list", "--head", "item-3", "--json", "number,url", "--template", "{{range .}}{{.number}}\\t{{.url}}\\n{{end}}"]:
|
||||
sys.exit(1)
|
||||
print("12\\thttps://github.com/o/r/pull/12")
|
||||
""".replace("PYTHON", sys.executable)
|
||||
|
||||
|
||||
class Repo:
|
||||
"""An origin with a tagged release, a clone of it at <temp>/proj, and a fake tea and gh on PATH."""
|
||||
|
||||
def __init__(self, test, todo=TODO, origin="origin.git", changelog=CHANGELOG):
|
||||
temp = tempfile.TemporaryDirectory()
|
||||
test.addCleanup(temp.cleanup)
|
||||
self.temp = pathlib.Path(os.path.realpath(temp.name))
|
||||
self.origin = self.temp / origin
|
||||
self.root = self.temp / "proj"
|
||||
self.fake = self.temp / "fake-bin"
|
||||
self.fake.mkdir()
|
||||
for name, script in (("gh", FAKE_GH), ("tea", FAKE_TEA)):
|
||||
(self.fake / name).write_text(script)
|
||||
(self.fake / name).chmod(0o755)
|
||||
(self.fake / "git").symlink_to(shutil.which("git"))
|
||||
self.env = {**isolated_env(), "GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_NOSYSTEM": "1", "HOME": str(self.temp / "home"), "PATH": str(self.fake), "LOOP_CLAUDE_TRANSCRIPTS": str(self.temp / "archive")}
|
||||
self.git(self.temp, "init", "--quiet", "--bare", "--initial-branch=main", str(self.origin))
|
||||
self.git(self.temp, "clone", "--quiet", str(self.origin), str(self.root))
|
||||
self.write(self.root, "README.md", README)
|
||||
self.write(self.root, "src/app.py", "def run():\n\treturn 1\n\n")
|
||||
self.commit(self.root, "start")
|
||||
self.git(self.root, "tag", "v0.1.0")
|
||||
self.write(self.root, "CHANGELOG.md", changelog)
|
||||
if todo:
|
||||
self.write(self.root, "todo.md", todo)
|
||||
self.commit(self.root, "plan")
|
||||
self.git(self.root, "push", "--quiet", "origin", "main", "v0.1.0")
|
||||
|
||||
def git(self, cwd, *args):
|
||||
return subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@example.com", *args], capture_output=True, check=True, cwd=cwd, env=self.env, text=True).stdout
|
||||
|
||||
def write(self, root, path, text):
|
||||
(root / path).parent.mkdir(parents=True, exist_ok=True)
|
||||
(root / path).write_text(text)
|
||||
|
||||
def commit(self, root, title):
|
||||
self.git(root, "add", "-A")
|
||||
self.git(root, "commit", "--quiet", "-m", title)
|
||||
|
||||
def push_from_elsewhere(self, path, text):
|
||||
"""Pushes a change to path from another clone, leaving the checkout behind origin."""
|
||||
other = self.temp / "other"
|
||||
self.git(self.temp, "clone", "--quiet", str(self.origin), str(other))
|
||||
self.write(other, path, text)
|
||||
self.commit(other, "elsewhere")
|
||||
self.git(other, "push", "--quiet", "origin", "main")
|
||||
|
||||
def stub_git(self, arm):
|
||||
"""Puts a git on PATH that runs arm, a shell case arm, on its arguments, and the real git on any others."""
|
||||
stub = self.fake / "git"
|
||||
stub.unlink()
|
||||
stub.write_text(f'#!/bin/sh\ncase "$*" in\n{arm}\nesac\nexec {shutil.which("git")} "$@"\n')
|
||||
stub.chmod(0o755)
|
||||
|
||||
def preflight(self, **env):
|
||||
return subprocess.run([sys.executable, str(BIN / "chunk-preflight")], capture_output=True, cwd=self.root, env={**self.env, **env}, text=True, timeout=120)
|
||||
|
||||
|
||||
class ChunkPreflightTool(unittest.TestCase):
|
||||
def test_reads_the_fetched_default_branchs_plan_and_makes_the_items_worktree_off_it_leaving_the_checkout_as_it_was(self):
|
||||
repo = Repo(self)
|
||||
repo.push_from_elsewhere("todo.md", SHIPPED)
|
||||
# Claude Code rewrites tracked files, such as settings.json, so a checkout behind origin often holds changes.
|
||||
repo.write(repo.root, "todo.md", TODO + "\nA change of the checkout's own.\n")
|
||||
head = repo.git(repo.root, "rev-parse", "HEAD")
|
||||
done = repo.preflight()
|
||||
self.assertEqual(done.returncode, 0, done.stderr)
|
||||
self.assertEqual(repo.git(repo.root, "rev-parse", "HEAD"), head)
|
||||
worktree = repo.temp / "proj-item-7"
|
||||
self.assertEqual(repo.git(worktree, "rev-parse", "--abbrev-ref", "HEAD").strip(), "item-7")
|
||||
self.assertEqual(repo.git(worktree, "rev-parse", "HEAD"), repo.git(repo.root, "rev-parse", "origin/main"))
|
||||
for fact in (
|
||||
"item 7, L 1, E + I 2",
|
||||
str(worktree),
|
||||
"item-7, made off origin/main",
|
||||
"#12 https://forge/pulls/12",
|
||||
"`src/app.py`: 3 lines",
|
||||
"`src`: 1 file",
|
||||
"`rank_todo.py --check todo.md` exited 0",
|
||||
"`larv-review needs-scoring-run 7` exited 0",
|
||||
"`reading-cost` exited 0",
|
||||
"`larv-review places` exited 0",
|
||||
f"{worktree}/docs/reading-cost.md",
|
||||
):
|
||||
with self.subTest(fact=fact):
|
||||
self.assertIn(fact, done.stdout)
|
||||
self.assertNotIn("#13", done.stdout)
|
||||
self.assertNotIn("`gone.py`:", done.stdout)
|
||||
|
||||
def test_names_no_item_and_makes_no_worktree_where_the_release_after_the_last_cut_has_emptied(self):
|
||||
for changelog, fact in ((CHANGELOG, "finished and ready to cut"), ("# Changelog\n\n## Unreleased\n\n## 0.1.0\n\n- Old.\n", "planned first")):
|
||||
with self.subTest(fact=fact):
|
||||
repo = Repo(self, changelog=changelog)
|
||||
repo.write(repo.root, "todo.md", LATER)
|
||||
repo.commit(repo.root, "ship 0.2.0")
|
||||
repo.git(repo.root, "push", "--quiet", "origin", "main")
|
||||
done = repo.preflight()
|
||||
self.assertEqual(done.returncode, 0, done.stderr)
|
||||
self.assertIn(fact, done.stdout)
|
||||
self.assertNotIn("item 9", done.stdout)
|
||||
self.assertFalse((repo.temp / "proj-item-9").exists())
|
||||
|
||||
def test_takes_the_next_item_where_the_plan_marks_the_release_after_the_last_cut_renamed_and_calls_it_finished_where_it_does_not(self):
|
||||
for mark, fact, absent in (("\n## Renamed\n\n- 0.2.0 renamed to 0.3.0\n", "item 3", "finished"), ("", "finished and ready to cut", "item 3")):
|
||||
with self.subTest(mark=mark):
|
||||
repo = Repo(self)
|
||||
repo.write(repo.root, "todo.md", TODO.replace("| 0.3.0 |", "| 0.4.0 |").replace("| 0.2.0 |", "| 0.3.0 |") + mark)
|
||||
repo.commit(repo.root, "move 0.2.0's items to 0.3.0")
|
||||
repo.git(repo.root, "push", "--quiet", "origin", "main")
|
||||
done = repo.preflight()
|
||||
self.assertEqual(done.returncode, 0, done.stderr)
|
||||
self.assertIn(fact, done.stdout)
|
||||
self.assertNotIn(absent, done.stdout)
|
||||
|
||||
def test_weighs_todo_md_at_the_last_cut_and_on_the_default_branch_after_it_alone(self):
|
||||
"""Each case's plans: before the tag, at it, on a side branch merged after it, and after it, each committed in turn where given."""
|
||||
cases = (
|
||||
("a release named only before the cut", TODO, LATER, None, None, "item 9"),
|
||||
("a release named at the cut", None, TODO, None, LATER, "finished and ready to cut"),
|
||||
("a release named only on a side branch", None, LATER, TODO, None, "item 9"),
|
||||
)
|
||||
for name, before, at, side, after, fact in cases:
|
||||
with self.subTest(name):
|
||||
repo = Repo(self, todo="")
|
||||
for todo, title in ((before, "before"), (at, "at")):
|
||||
if todo is not None:
|
||||
repo.write(repo.root, "todo.md", todo)
|
||||
repo.commit(repo.root, title)
|
||||
repo.git(repo.root, "tag", "--force", "v0.1.0")
|
||||
if side is not None:
|
||||
repo.git(repo.root, "switch", "--quiet", "-c", "side")
|
||||
# The branch ends on a plan main never held, so the merge changes todo.md.
|
||||
for todo in (side, LATER + "| 10 | 0.3.0 | | | **Do another later thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 90.0 |\n"):
|
||||
repo.write(repo.root, "todo.md", todo)
|
||||
repo.commit(repo.root, "side")
|
||||
repo.git(repo.root, "switch", "--quiet", "main")
|
||||
repo.git(repo.root, "merge", "--quiet", "--no-ff", "-m", "merge side", "side")
|
||||
if after is not None:
|
||||
repo.write(repo.root, "todo.md", after)
|
||||
repo.commit(repo.root, "after")
|
||||
repo.git(repo.root, "push", "--quiet", "--force", "origin", "main", "v0.1.0")
|
||||
done = repo.preflight()
|
||||
self.assertEqual(done.returncode, 0, done.stderr)
|
||||
self.assertIn(fact, done.stdout)
|
||||
|
||||
def test_continues_the_items_worktree_and_else_its_pushed_branch(self):
|
||||
repo = Repo(self)
|
||||
repo.preflight()
|
||||
worktree = repo.temp / "proj-item-3"
|
||||
continued = repo.preflight().stdout
|
||||
self.assertIn(str(worktree), continued)
|
||||
self.assertIn("continued", continued)
|
||||
(worktree / "work.txt").write_text("work\n")
|
||||
repo.git(worktree, "add", "work.txt")
|
||||
repo.git(worktree, "commit", "--quiet", "-m", "work")
|
||||
repo.git(worktree, "push", "--quiet", "origin", "item-3")
|
||||
repo.git(repo.root, "worktree", "remove", "--force", str(worktree))
|
||||
repo.git(repo.root, "branch", "--quiet", "-D", "item-3")
|
||||
pushed = repo.preflight().stdout
|
||||
self.assertIn(str(worktree), pushed)
|
||||
self.assertIn("made off origin/item-3", pushed)
|
||||
self.assertTrue((worktree / "work.txt").exists())
|
||||
|
||||
def test_makes_no_worktree_where_its_path_holds_something_else_and_runs_no_tool(self):
|
||||
repo = Repo(self)
|
||||
(repo.temp / "proj-item-3").mkdir()
|
||||
done = repo.preflight()
|
||||
self.assertIn(f"none made, since {repo.temp / 'proj-item-3'} exists", done.stdout)
|
||||
self.assertNotIn("`reading-cost`", done.stdout)
|
||||
|
||||
def test_makes_no_worktree_and_runs_no_tool_where_git_cannot_add_it(self):
|
||||
repo = Repo(self)
|
||||
repo.temp.chmod(0o555)
|
||||
self.addCleanup(repo.temp.chmod, 0o755)
|
||||
done = repo.preflight()
|
||||
self.assertEqual(done.returncode, 0, done.stderr)
|
||||
self.assertIn("Worktree: none made: git worktree add", done.stdout)
|
||||
self.assertNotIn("`reading-cost`", done.stdout)
|
||||
self.assertFalse((repo.temp / "proj-item-3").exists())
|
||||
|
||||
def test_makes_no_worktree_and_runs_no_tool_where_git_cannot_list_the_worktrees(self):
|
||||
repo = Repo(self)
|
||||
repo.stub_git('"worktree list --porcelain") echo "listing broke" >&2; exit 1;;')
|
||||
done = repo.preflight()
|
||||
self.assertEqual(done.returncode, 0, done.stderr)
|
||||
self.assertIn("listing broke", done.stdout)
|
||||
self.assertNotIn("`reading-cost`", done.stdout)
|
||||
self.assertFalse((repo.temp / "proj-item-3").exists())
|
||||
|
||||
def test_reads_origin_as_last_fetched_where_the_fetch_stalls_and_still_states_the_other_facts(self):
|
||||
repo = Repo(self)
|
||||
repo.stub_git(f'"fetch --quiet origin") exec {shutil.which("sleep")} 10;;')
|
||||
done = repo.preflight(CHUNK_PREFLIGHT_TIMEOUT="1")
|
||||
self.assertEqual(done.returncode, 0, done.stderr)
|
||||
self.assertIn("as last fetched", done.stdout)
|
||||
self.assertIn("item 3, L 2, E + I 5", done.stdout)
|
||||
self.assertIn("`reading-cost` exited 0", done.stdout)
|
||||
|
||||
def test_lists_the_open_pull_requests_with_gh_on_a_github_origin(self):
|
||||
repo = Repo(self, origin="github.com/o/r.git")
|
||||
self.assertIn("#12 https://github.com/o/r/pull/12", repo.preflight().stdout)
|
||||
|
||||
def test_without_a_plan_states_the_release_facts_and_makes_no_worktree(self):
|
||||
repo = Repo(self, todo="")
|
||||
done = repo.preflight()
|
||||
self.assertEqual(done.returncode, 0, done.stderr)
|
||||
self.assertIn("v0.1.0", done.stdout)
|
||||
self.assertIn("no items table", done.stdout)
|
||||
self.assertFalse((repo.temp / "proj-item-3").exists())
|
||||
|
||||
def test_states_its_timeout_in_its_help(self):
|
||||
done = subprocess.run([sys.executable, str(BIN / "chunk-preflight"), "--help"], capture_output=True, env=isolated_env(), text=True)
|
||||
self.assertEqual(done.returncode, 0, done.stderr)
|
||||
self.assertIn(f"after {TIMEOUT} seconds", done.stdout)
|
||||
|
||||
def test_exits_1_on_a_timeout_setting_that_is_no_number_of_seconds(self):
|
||||
done = Repo(self).preflight(CHUNK_PREFLIGHT_TIMEOUT="soon")
|
||||
self.assertEqual(done.returncode, 1)
|
||||
self.assertIn("CHUNK_PREFLIGHT_TIMEOUT", done.stderr)
|
||||
self.assertEqual(done.stdout, "")
|
||||
|
||||
def test_exits_1_without_a_default_branch(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
env = {**isolated_env(), "GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_NOSYSTEM": "1"}
|
||||
subprocess.run(["git", "init", "--quiet", "--initial-branch=trunk", temp], check=True, env=env)
|
||||
done = subprocess.run([sys.executable, str(BIN / "chunk-preflight")], capture_output=True, cwd=temp, env=env, text=True)
|
||||
self.assertEqual(done.returncode, 1)
|
||||
self.assertIn("main or master", done.stderr)
|
||||
self.assertEqual(done.stdout, "")
|
||||
|
||||
def test_exits_1_outside_a_checkout(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
done = subprocess.run([sys.executable, str(BIN / "chunk-preflight")], capture_output=True, cwd=temp, env={**isolated_env(), "GIT_CONFIG_NOSYSTEM": "1"}, text=True)
|
||||
self.assertEqual(done.returncode, 1)
|
||||
self.assertIn("git rev-parse --show-toplevel", done.stderr)
|
||||
|
||||
|
||||
def item_facts(todo=TODO, **fields):
|
||||
"""The facts of todo's next item, its worktree made, with fields given replacing the rest."""
|
||||
return ItemFacts(**{"plan": planned(todo, CUT, "origin/main"), "worktree": Worktree(pathlib.Path("/c/proj-item-3"), "added on the new branch item-3, made off origin/main."), "pulls": None, "named": [], "tools": [], **fields})
|
||||
|
||||
|
||||
def rendered(item, release=CUT, note=None):
|
||||
return "\n".join(render(Gathered("origin/main", note, release, item)))
|
||||
|
||||
|
||||
class Render(unittest.TestCase):
|
||||
def test_states_the_earliest_releases_first_item_its_levels_and_detail_and_each_item_that_may_join_its_chunk(self):
|
||||
said = rendered(item_facts())
|
||||
self.assertIn("origin/main's todo.md: 0.2.0", said)
|
||||
self.assertIn("item 3, L 2, E + I 5", said)
|
||||
self.assertIn("> Change `src/app.py`'s `run` and the files under `src`, not `gone.py`.", said)
|
||||
self.assertIn("item 7, L 1, E + I 2, S 1: **Do the thing after.**", said)
|
||||
self.assertNotIn("item 8,", said)
|
||||
|
||||
def test_states_the_items_worktree_or_why_none_was_made(self):
|
||||
self.assertIn("/c/proj-item-3", rendered(item_facts()))
|
||||
self.assertIn("none made: path taken", rendered(item_facts(worktree=Failure("none made: path taken"))))
|
||||
|
||||
def test_states_that_no_other_item_may_join_the_chunk(self):
|
||||
said = rendered(item_facts(TODO.replace("| 7 | 0.2.0 | 3 |", "| 7 | 0.2.0 | 5 |")))
|
||||
self.assertIn("No other item", said)
|
||||
self.assertNotIn("item 7,", said)
|
||||
|
||||
def test_states_that_an_item_above_r_5_ships_alone(self):
|
||||
said = rendered(item_facts(TODO.replace("| 2 | 2 | 3 | 5 | 3 |", "| 3 | 2 | 3 | 6 | 3 |")))
|
||||
self.assertIn("Item 3 has R above 5, so it ships alone.", said)
|
||||
self.assertNotIn("item 7,", said)
|
||||
|
||||
def test_states_an_unscored_level_as_unscored(self):
|
||||
unscored = TODO.replace("| L | E | I | R | S |", "| R | S |").replace("|---|---|---|---|---|---|---|---|---|---|---|---|", "|---|---|---|---|---|---|---|---|---|").replace("| 2 | 2 | 3 | 5 | 3 |", "| 5 | 3 |").replace("| 1 | 1 | 1 | 1 | 1 |", "| 1 | 1 |")
|
||||
self.assertIn("item 3, L unscored, E + I unscored", rendered(item_facts(unscored)))
|
||||
|
||||
def test_states_the_unreleased_entries_and_else_the_commits_since_the_last_cut(self):
|
||||
self.assertIn("v0.1.0. Unreleased: 2 entries", rendered(NoItem("x.")))
|
||||
self.assertIn("1 entry", rendered(NoItem("x."), LastCut("v0.1.0", "## Unreleased\n\n- One.\n", 4, [])))
|
||||
without = rendered(NoItem("x."), LastCut("v0.1.0", "# Changelog\n", 4, []))
|
||||
self.assertIn("4 commits since v0.1.0", without)
|
||||
self.assertIn("no ## Unreleased", without)
|
||||
untagged = rendered(NoItem("x."), LastCut(None, "", 1, []))
|
||||
self.assertIn("cut: none", untagged)
|
||||
self.assertIn("1 commit on origin/main", untagged)
|
||||
|
||||
def test_states_why_the_changelog_and_the_commits_since_the_last_cut_cannot_be_read(self):
|
||||
said = rendered(NoItem("x."), LastCut("v0.1.0", Failure("changelog unreadable"), Failure("count unreadable"), []))
|
||||
self.assertIn("changelog unreadable", said)
|
||||
self.assertIn("cannot be counted: count unreadable", said)
|
||||
self.assertNotIn("no ## Unreleased", said)
|
||||
|
||||
def test_states_why_origin_reads_as_last_fetched_and_nothing_after_a_fetch(self):
|
||||
self.assertIn("- reading origin as last fetched: fetch stalled", rendered(NoItem("x."), note="reading origin as last fetched: fetch stalled"))
|
||||
fetched = rendered(NoItem("x."))
|
||||
self.assertNotIn("last fetched", fetched)
|
||||
self.assertNotIn("None", fetched)
|
||||
|
||||
def test_states_why_there_is_no_plan_item(self):
|
||||
said = rendered(NoItem("every item waits."))
|
||||
self.assertIn("every item waits.", said)
|
||||
self.assertNotIn("Worktree", said)
|
||||
|
||||
def test_states_the_open_pull_requests_from_the_items_branch_or_why_none_are_listed(self):
|
||||
cases = (
|
||||
(("tea", Ran(0, "index\thead\turl\n12\titem-3\thttps://forge/pulls/12\n", "")), ("#12 https://forge/pulls/12",)),
|
||||
(("gh", Ran(0, "12\thttps://github.com/o/r/pull/12\n14\thttps://github.com/o/r/pull/14\n", "")), ("#12 https://github.com/o/r/pull/12, #14 https://github.com/o/r/pull/14",)),
|
||||
(("gh", Ran(0, "", "")), ("item-3: none.",)),
|
||||
(None, ("item-3: none", "no origin remote")),
|
||||
(("tea", Ran(1, "", "no login\n")), ("`tea pulls list`", "exited 1", "no login")),
|
||||
(("gh", Ran(1, "", "not logged in\n")), ("`gh pr list`", "exited 1", "not logged in")),
|
||||
(("gh", Failure("could not finish: timed out")), ("`gh pr list`", "could not finish: timed out")),
|
||||
)
|
||||
for pulls, facts in cases:
|
||||
with self.subTest(pulls=pulls):
|
||||
said = rendered(item_facts(pulls=pulls))
|
||||
for fact in facts:
|
||||
self.assertIn(fact, said)
|
||||
|
||||
def test_states_each_named_files_lines_and_each_named_folders_files(self):
|
||||
said = rendered(item_facts(named=[NamedPath("src/app.py", 1, 3), NamedPath("src", 2, None), NamedPath("bad.py", 1, Failure("not UTF-8")), NamedPath("one.py", 1, 1), NamedPath("docs", 1, None)]))
|
||||
self.assertIn("`src/app.py`: 3 lines", said)
|
||||
self.assertIn("`src`: 2 files", said)
|
||||
self.assertIn("`bad.py`: cannot be read: not UTF-8", said)
|
||||
self.assertIn("`one.py`: 1 line\n", said)
|
||||
self.assertIn("`docs`: 1 file\n", said)
|
||||
|
||||
def test_states_that_the_item_names_no_tracked_file_or_why_they_cannot_be_listed(self):
|
||||
self.assertIn("no file", rendered(item_facts(named=[])))
|
||||
self.assertIn("ls-files broke", rendered(item_facts(named=Failure("ls-files broke"))))
|
||||
|
||||
def test_states_what_each_tool_printed_and_its_exit_code(self):
|
||||
said = rendered(item_facts(tools=[("rank_todo.py --check todo.md", Ran(0, "ranked\n", "")), ("reading-cost", Ran(1, "", "")), ("larv-review needs-scoring-run 3", Ran(1, "out\n", "err\n")), ("larv-review places", Failure("could not finish: timed out"))]))
|
||||
self.assertIn("`rank_todo.py --check todo.md` exited 0", said)
|
||||
self.assertIn("> ranked", said)
|
||||
self.assertIn("`reading-cost` exited 1, printing nothing", said)
|
||||
self.assertIn("> out\n> err", said)
|
||||
self.assertIn("`larv-review places` could not finish: timed out", said)
|
||||
|
||||
|
||||
class OpenPulls(unittest.TestCase):
|
||||
def test_lists_gh_rows_as_they_come_and_only_teas_rows_from_the_branch(self):
|
||||
self.assertEqual(open_pulls("12\thttps://github.com/o/r/pull/12\n14\thttps://github.com/o/r/pull/14\n", "gh", "item-3"), ["#12 https://github.com/o/r/pull/12", "#14 https://github.com/o/r/pull/14"])
|
||||
self.assertEqual(open_pulls("index\thead\turl\n12\titem-3\thttps://forge/pulls/12\n13\tother\thttps://forge/pulls/13\n", "tea", "item-3"), ["#12 https://forge/pulls/12"])
|
||||
|
||||
|
||||
class Plans(unittest.TestCase):
|
||||
def test_picks_the_earliest_releases_first_item_that_does_not_wait_or_says_why_there_is_none(self):
|
||||
self.assertEqual(planned(TODO, CUT, "origin/main").first.id, 3)
|
||||
waits = planned(TODO.replace("| 3 | 0.2.0 | | |", "| 3 | 0.2.0 | | question |"), CUT, "origin/main")
|
||||
self.assertIn("waits", waits.why)
|
||||
self.assertIn("0.2.0", waits.why)
|
||||
self.assertIn("Permission denied", planned(Failure("Permission denied"), CUT, "origin/main").why)
|
||||
self.assertIn("L 'x'", planned(TODO.replace("| 2 | 2 | 3 | 5 |", "| x | 2 | 3 | 5 |"), CUT, "origin/main").why)
|
||||
self.assertIn("details cannot be read", planned(TODO + "```\n", CUT, "origin/main").text)
|
||||
|
||||
def test_tells_a_plan_with_no_items_table_from_one_whose_table_holds_no_item(self):
|
||||
without = planned("", CUT, "origin/main").why
|
||||
self.assertIn("origin/main", without)
|
||||
self.assertIn("no items table", without)
|
||||
self.assertNotIn("cannot be read", without)
|
||||
empty = planned(EMPTY, LastCut(None, "", 4, []), "origin/main").why
|
||||
self.assertIn("holds no item", empty)
|
||||
self.assertNotIn("no items table", empty)
|
||||
|
||||
def test_finds_the_release_after_the_last_cut_finished_or_to_be_planned_where_the_plan_holds_no_item_for_it(self):
|
||||
named = "release 0.2.0, the next after the last cut, v0.1.0"
|
||||
unnamed = "the next release after the last cut, v0.1.0"
|
||||
cases = (
|
||||
(LATER, 4, [TODO], "finished and ready to cut", named),
|
||||
(LATER, 0, [TODO], "planned first", named),
|
||||
(EMPTY, 4, [TODO], "finished and ready to cut", named),
|
||||
(EMPTY, 0, [TODO], "planned first", named),
|
||||
(EMPTY, 4, [EMPTY], "finished and ready to cut", unnamed),
|
||||
(LATER, Failure("count unreadable"), [TODO], "cannot be read", unnamed),
|
||||
)
|
||||
for todo, commits, todos, fact, release in cases:
|
||||
with self.subTest(todo=todo, commits=commits, todos=todos):
|
||||
why = planned(todo, LastCut("v0.1.0", "", commits, todos), "origin/main").why
|
||||
self.assertIn(fact, why)
|
||||
self.assertIn(release, why)
|
||||
|
||||
def test_says_what_todo_md_named_since_the_last_cut_cannot_be_read(self):
|
||||
self.assertIn("cannot be read", planned(LATER, LastCut("v0.1.0", "", 4, Failure("log unreadable")), "origin/main").why)
|
||||
|
||||
def test_takes_the_earliest_release_where_no_earlier_one_was_named_since_the_last_cut(self):
|
||||
self.assertEqual(planned(LATER, LastCut("v0.1.0", "", 4, [LATER]), "origin/main").first.id, 9)
|
||||
|
||||
def test_says_the_plan_files_items_under_a_release_already_cut(self):
|
||||
why = planned(TODO, LastCut("v0.2.0", "", 4, []), "origin/main").why
|
||||
self.assertIn("release 0.2.0", why)
|
||||
self.assertIn("v0.2.0", why)
|
||||
self.assertIn("not after", why)
|
||||
|
||||
def test_takes_an_item_without_a_detail_as_its_tagline_alone(self):
|
||||
self.assertEqual(planned(TODO[:TODO.index("## Details")], CUT, "origin/main").text, "**Do the next thing.**")
|
||||
|
||||
|
||||
class Gathering(unittest.TestCase):
|
||||
def test_names_each_tracked_file_or_folder_a_backticked_span_names_once_with_its_files(self):
|
||||
cases = (
|
||||
("`src/` and `src`", ["src/app.py", "srcfoo/x.py"], [("src", 1)]),
|
||||
("`src/`", ["src/app.py", "src/b.py"], [("src", 2)]),
|
||||
("`src/app.py`, `gone.py` and `run`", ["src/app.py"], [("src/app.py", 1)]),
|
||||
)
|
||||
for text, tracked, named in cases:
|
||||
with self.subTest(text=text):
|
||||
self.assertEqual(named_paths(text, tracked), named)
|
||||
|
||||
def test_adds_the_worktree_on_the_local_branch_else_on_a_new_one_tracking_origins_else_on_a_new_one_off_the_default_branch(self):
|
||||
path = pathlib.Path("/c/proj-item-3")
|
||||
self.assertEqual(worktree_add("item-3", path, "origin/main", True, True)[0], ["worktree", "add", "--quiet", "/c/proj-item-3", "item-3"])
|
||||
self.assertEqual(worktree_add("item-3", path, "origin/main", False, True)[0], ["worktree", "add", "--quiet", "--track", "-b", "item-3", "/c/proj-item-3", "origin/item-3"])
|
||||
self.assertEqual(worktree_add("item-3", path, "origin/main", False, False)[0], ["worktree", "add", "--quiet", "--no-track", "-b", "item-3", "/c/proj-item-3", "origin/main"])
|
||||
|
||||
def test_lists_pull_requests_with_gh_on_a_github_origin_and_with_tea_elsewhere(self):
|
||||
self.assertEqual(forge_of("git@github.com:o/r.git"), "gh")
|
||||
self.assertEqual(forge_of("https://gitea.larvit.se/o/r.git"), "tea")
|
||||
|
||||
def test_reads_the_timeout_setting_as_seconds_above_0_and_else_takes_the_default(self):
|
||||
self.assertEqual(seconds(None), TIMEOUT)
|
||||
self.assertEqual(seconds("2.5"), 2.5)
|
||||
for setting in ("soon", "0", "-1", "1e3", ""):
|
||||
with self.subTest(setting=setting):
|
||||
self.assertIn("CHUNK_PREFLIGHT_TIMEOUT", seconds(setting).reason)
|
||||
|
||||
|
||||
class Running(unittest.TestCase):
|
||||
def test_says_why_a_command_could_not_finish(self):
|
||||
with tempfile.TemporaryDirectory() as cwd:
|
||||
cases = (([str(pathlib.Path(cwd, "missing"))], 60, "missing"), ([sys.executable, "-c", "import time; time.sleep(5)"], 0.2, "0.2"))
|
||||
for command, timeout, fact in cases:
|
||||
with self.subTest(fact=fact):
|
||||
done = ran(command, pathlib.Path(cwd), timeout)
|
||||
self.assertIsInstance(done, Failure)
|
||||
self.assertIn(fact, done.reason)
|
||||
|
||||
def test_counts_a_files_lines_says_why_they_cannot_be_read_and_counts_none_for_a_folder(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
folder = pathlib.Path(temp)
|
||||
(folder / "two.txt").write_text("a\nb\n")
|
||||
(folder / "latin.txt").write_bytes(b"caf\xe9\n")
|
||||
(folder / "locked.txt").write_text("a\n")
|
||||
(folder / "locked.txt").chmod(0)
|
||||
self.assertEqual(line_count(folder / "two.txt"), 2)
|
||||
self.assertIn("utf-8", line_count(folder / "latin.txt").reason)
|
||||
self.assertIn("locked.txt", line_count(folder / "locked.txt").reason)
|
||||
self.assertIsNone(line_count(folder))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -67,7 +67,7 @@ def human_text(entry: dict) -> str | None:
|
||||
|
||||
# {"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."""
|
||||
"""What loop-claude told the worker in a -p prompt."""
|
||||
text = content(entry)
|
||||
return text if entry.get("type") == "user" and entry.get("promptSource") == "sdk" and isinstance(text, str) else None
|
||||
|
||||
|
||||
@@ -23,7 +23,7 @@ def queued(prompt, kind):
|
||||
|
||||
|
||||
class Render(unittest.TestCase):
|
||||
def test_joins_assistant_text_tool_calls_human_turns_and_loop_prompts_and_skips_the_rest(self):
|
||||
def test_joins_assistant_text_tool_calls_human_turns_and_loop_prompts_labelling_a_typed_answer_the_humans_and_skips_the_rest(self):
|
||||
said = transcript.render([
|
||||
human("do it"),
|
||||
assistant({"type": "text", "text": "Starting."}, {"type": "tool_use", "name": "Bash", "input": {"command": "ls"}}),
|
||||
@@ -34,8 +34,17 @@ class Render(unittest.TestCase):
|
||||
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.')
|
||||
{**human("Answered: use B\nYour question: A or B?"), "promptSource": "sdk"},
|
||||
], lambda prompt: transcript.Typed(*reversed(prompt.removeprefix("Answered: ").split("\n"))) if prompt.startswith("Answered: ") else None)
|
||||
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.\n\n[loop] Your question: A or B?\n\n[human] use B')
|
||||
|
||||
|
||||
class Verbatim(unittest.TestCase):
|
||||
def test_a_quote_holds_only_word_for_word_less_emphasis_and_whitespace(self):
|
||||
self.assertTrue(transcript.verbatim("Merge **ff-only**.", "Merge ff-only.\nNever squash."))
|
||||
self.assertTrue(transcript.verbatim("Merge _ff-only_.", "Merge ff-only.\nNever squash."))
|
||||
self.assertFalse(transcript.verbatim("Merge ... squash.", "Merge ff-only.\nNever squash."))
|
||||
self.assertFalse(transcript.verbatim("", "Merge ff-only."))
|
||||
|
||||
|
||||
class FirstTimestampedLine(unittest.TestCase):
|
||||
@@ -84,12 +93,12 @@ class Parse(unittest.TestCase):
|
||||
|
||||
class ClaudeReply(unittest.TestCase):
|
||||
@staticmethod
|
||||
def claude(*outcomes):
|
||||
def claude(*results):
|
||||
def run(args, cwd, prompt):
|
||||
outcome = outcomes[0]
|
||||
if isinstance(outcome, OSError):
|
||||
raise outcome
|
||||
return subprocess.CompletedProcess(args, *outcome)
|
||||
result = results[0]
|
||||
if isinstance(result, OSError):
|
||||
raise result
|
||||
return subprocess.CompletedProcess(args, *result)
|
||||
return run
|
||||
|
||||
def test_runs_claude_headless_with_the_args_in_cwd_on_the_prompt(self):
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import json
|
||||
import typing
|
||||
|
||||
from claude_code.entries import assistant_parts, human_text, loop_text, parse_entry, part_text, tool_call
|
||||
from failure import Failure
|
||||
@@ -6,6 +7,12 @@ from failure import Failure
|
||||
JUDGED_TOOL_INPUT = 400
|
||||
|
||||
|
||||
class Typed(typing.NamedTuple):
|
||||
"""A -p prompt of loop-claude's that carries an answer the human typed: loop-claude's words, and that answer."""
|
||||
loop_words: str
|
||||
answer: str
|
||||
|
||||
|
||||
def read_transcript(path: str) -> list[dict] | Failure:
|
||||
try:
|
||||
with open(path, "rb") as handle:
|
||||
@@ -24,14 +31,16 @@ 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:
|
||||
def render(entries: list[dict], typed_answer: typing.Callable[[str], Typed | None]) -> str:
|
||||
"""The transcript as the judge reads it. typed_answer splits the answer the human typed out of a -p prompt of loop-claude's, so that answer reads as the human's, like one typed in claude."""
|
||||
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)
|
||||
typed = typed_answer(text)
|
||||
lines += ["[loop] " + text] if typed is None else ["[loop] " + typed.loop_words, "[human] " + typed.answer]
|
||||
return "\n\n".join(lines)
|
||||
|
||||
|
||||
@@ -42,3 +51,14 @@ def part_line(part: object, tool_input_chars: int) -> str:
|
||||
name, arguments = call
|
||||
return f"[tool {name}] {json.dumps(arguments, ensure_ascii=False)[:tool_input_chars]}"
|
||||
return ""
|
||||
|
||||
|
||||
def verbatim(quote: str, text: str) -> bool:
|
||||
"""Whether text holds the judge's quote word for word, once plain strips emphasis and reflows whitespace in both."""
|
||||
quoted = plain(quote)
|
||||
return quoted != "" and quoted in plain(text)
|
||||
|
||||
|
||||
def plain(text: str) -> str:
|
||||
# The judge drops markdown emphasis and reflows whitespace when it quotes.
|
||||
return " ".join(text.replace("*", "").replace("_", "").split())
|
||||
|
||||
@@ -6,7 +6,7 @@ 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.
|
||||
# A failure only warns: claude still opens, and the human answers Claude Code's trust dialog.
|
||||
def trust(config: pathlib.Path, roots: list[str]) -> None:
|
||||
try:
|
||||
with open(config, encoding="utf-8") as handle:
|
||||
@@ -31,7 +31,7 @@ def trust(config: pathlib.Path, roots: list[str]) -> None:
|
||||
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:
|
||||
if (wrong := next((path for path, settings in projects.items() if not isinstance(settings, dict)), None)) is not None:
|
||||
return Failure(f"projects[{json.dumps(wrong)}] is not an object")
|
||||
untrusted = [path for path in roots if not projects.get(path, {}).get("hasTrustDialogAccepted")]
|
||||
marked = {path: {**projects.get(path, {}), "hasTrustDialogAccepted": True} for path in untrusted}
|
||||
|
||||
@@ -9,6 +9,8 @@ from utc_stamp import utc
|
||||
ARCHITECT = "Inherited architect"
|
||||
DECIDED_BY = "decided by"
|
||||
DIMENSIONS = ("Navigation", "Locality", "Shape", "Self-sufficiency", "Overall")
|
||||
# The comprehension floor, which every dimension and the overall should reach; docs/decisions.md → "comprehension floor" says it blocks nothing.
|
||||
FLOOR = decimal.Decimal("7.0")
|
||||
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"
|
||||
@@ -79,7 +81,7 @@ class ScoringRun:
|
||||
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:`.
|
||||
# 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:`. A ruling recorded before PR #232 has a `| Seat | Vote |` table, whose one cell is the overall vote.
|
||||
#
|
||||
# ## 2026-10-09T09:47:25Z, PR #232 at 324d650, against 12d6d75
|
||||
#
|
||||
@@ -104,13 +106,61 @@ def entries(history: str) -> list[Entry]:
|
||||
|
||||
|
||||
def latest_places(history: str) -> str | None:
|
||||
"""The places seats found hard from the newest entry, by time, that is a scoring run or holds scoring seats' places: in it and each later entry, each ruled place opening with a dimension its seat's vote counted as worse, and every scoring seat's place. Each entry's places come under its heading, oldest first; with no such entry, it starts at the oldest entry. None when no place counts."""
|
||||
found = sorted(entries(history), key=lambda entry: entry.time)
|
||||
newest = max((index for index, entry in enumerate(found) if not entry.paired or entry.scored_places), default=0)
|
||||
parts = [placed(entry, worse_places(entry) + labelled_bullets(entry.body, SCORED_PLACES)) for entry in found[newest:]]
|
||||
"""The places seats found hard since the newest scored commit, under each entry's heading, oldest first; None when no place counts.
|
||||
|
||||
They start at the first of newest_scored's entries, so a rerun of one head adds to the run before it. Where no entry counts as scoring the project, they start at the oldest entry. From there, each entry gives every scoring seat's place, and each ruled place opening with a dimension its seat voted worse."""
|
||||
found = by_time(entries(history))
|
||||
newest = newest_scored(found)
|
||||
start = found.index(newest[0]) if newest else 0
|
||||
parts = [placed(entry, worse_places(entry) + labelled_bullets(entry.body, SCORED_PLACES)) for entry in found[start:]]
|
||||
return "\n".join(part for part in parts if part) or None
|
||||
|
||||
|
||||
def latest_overall(history: str) -> decimal.Decimal | Failure | None:
|
||||
"""The mean of the overall means of newest_scored's entries, since a rerun of one head measures it again; None where no entry counts as scoring the project."""
|
||||
overalls = []
|
||||
for entry in newest_scored(by_time(entries(history))):
|
||||
overall = run_overall(entry)
|
||||
if isinstance(overall, Failure):
|
||||
return overall
|
||||
overalls.append(overall)
|
||||
return sum(overalls, decimal.Decimal(0)) / len(overalls) if overalls else None
|
||||
|
||||
|
||||
def newest_scored(found: list[Entry]) -> list[Entry]:
|
||||
"""In found's order, the entries that count as scoring the project on the newest scored commit, the commit of the last such entry; empty where none counts. A commit matches by prefix, since a heading may write it at any length from 7 characters."""
|
||||
scoring = [entry for entry in found if scored(entry)]
|
||||
return [entry for entry in scoring if entry.commit.startswith(scoring[-1].commit) or scoring[-1].commit.startswith(entry.commit)] if scoring else []
|
||||
|
||||
|
||||
def run_overall(run: Entry) -> decimal.Decimal | Failure:
|
||||
"""The overall cell of the Mean row of an entry that counts as scoring the project."""
|
||||
try:
|
||||
overall = decimal.Decimal(overall_cells(run).get(MEAN, ""))
|
||||
except decimal.InvalidOperation:
|
||||
overall = None
|
||||
return overall if overall is not None and overall.is_finite() else Failure(f"{HISTORY}'s scoring run {run.heading} has no Mean row ending in its overall, which sets code health's weight")
|
||||
|
||||
|
||||
def overall_cells(entry: Entry) -> dict[str, str]:
|
||||
"""Each table row's last non-empty cell, by its first cell: a seat's overall vote in a ruling table, whether it has five votes or the older single `Vote`, or its overall score, or the Mean row's, in a scoring table."""
|
||||
return {name: cells[-1] for name, cells in table_rows(entry.body).items() if cells and cells[-1]}
|
||||
|
||||
|
||||
def scoring_runs(found: list[Entry]) -> list[Entry]:
|
||||
"""The scoring runs among the entries, oldest first. Unlike scored, it leaves out a ruling from before PR #255 that holds scoring seats' places: there overall_cells reads each voting seat's vote, not its score."""
|
||||
return [entry for entry in by_time(found) if not entry.paired]
|
||||
|
||||
|
||||
def by_time(found: list[Entry]) -> list[Entry]:
|
||||
return sorted(found, key=lambda entry: entry.time)
|
||||
|
||||
|
||||
def scored(entry: Entry) -> bool:
|
||||
"""Whether the entry counts as scoring the project: a scoring run, or a ruling from before PR #255 that holds scoring seats' places."""
|
||||
return not entry.paired or bool(entry.scored_places)
|
||||
|
||||
|
||||
def worse_places(entry: Entry) -> list[tuple[str, list[str]]]:
|
||||
"""Under each of a ruling's seat labels, the bullets that open with a dimension that seat's vote counted as worse; Overall counts as one."""
|
||||
worse = worse_votes(entry.body)
|
||||
@@ -125,13 +175,16 @@ def placed(entry: Entry, labelled: list[tuple[str, list[str]]]) -> str:
|
||||
|
||||
def worse_votes(body: str) -> dict[str, set[str]]:
|
||||
"""Each seat's dimensions, Overall included, whose vote in the ruling's table counted as worse; `same (voted worse, …)` counted as same. The votes table comes first, so a seat's row in a later scores table is not its vote."""
|
||||
found: dict[str, set[str]] = {}
|
||||
return {name: {dimension for dimension, vote in zip(DIMENSIONS, cells) if vote == "worse"} for name, cells in table_rows(body).items() if len(cells) == len(DIMENSIONS)}
|
||||
|
||||
|
||||
def table_rows(body: str) -> dict[str, list[str]]:
|
||||
"""Each table row's cells after its first, keyed by that first cell; where rows share a first cell, the first row wins. Header and Mean rows are included."""
|
||||
found: dict[str, list[str]] = {}
|
||||
for line in body.splitlines():
|
||||
if not line.startswith("| "):
|
||||
continue
|
||||
name, *votes = [cell.strip() for cell in line.strip("|").split("|")]
|
||||
if len(votes) == len(DIMENSIONS):
|
||||
found.setdefault(name, {dimension for dimension, vote in zip(DIMENSIONS, votes) if vote == "worse"})
|
||||
if line.startswith("| "):
|
||||
name, *cells = [cell.strip() for cell in line.strip("|").split("|")]
|
||||
found.setdefault(name, cells)
|
||||
return found
|
||||
|
||||
|
||||
@@ -205,6 +258,11 @@ def vote_text(dimension: str, said: str, counted: str) -> str:
|
||||
return f"same (voted {said}, naming no place)" if dimension == DIMENSIONS[-1] else f"same (voted {said}, no place naming {dimension})"
|
||||
|
||||
|
||||
def counted_vote(cell: str) -> str:
|
||||
"""The vote a ruling's table cell counted as, which is its first word, as vote_text writes it."""
|
||||
return cell.split()[0]
|
||||
|
||||
|
||||
def scoring_entry(title: str, scoring: ScoringRun) -> str:
|
||||
return entry_text(title, [], [scores_table(scoring)], scoring_labels(scoring.seats))
|
||||
|
||||
|
||||
+75
-25
@@ -1,16 +1,45 @@
|
||||
"""Run git in the current directory, and read the checkout, its default branch and its files."""
|
||||
"""Run git, in the current directory or a given one, and read the checkout, its default branch and its files.
|
||||
|
||||
Every tool in bin/ starts git through `git` here."""
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
|
||||
from failure import Failure
|
||||
|
||||
# A -c outranks the checkout's own config. Each transport gets its own line, since a config's protocol.<name>.allow outranks protocol.allow.
|
||||
GUARD_SETTINGS = [
|
||||
"core.fsmonitor=false",
|
||||
"log.showSignature=false",
|
||||
"protocol.allow=never",
|
||||
"protocol.ext.allow=never",
|
||||
"protocol.file.allow=never",
|
||||
"protocol.git.allow=never",
|
||||
"protocol.http.allow=never",
|
||||
"protocol.https.allow=never",
|
||||
"protocol.ssh.allow=never",
|
||||
]
|
||||
|
||||
def git(*args: str) -> str | Failure:
|
||||
|
||||
def git(*args: str, cwd: str | None = None, timeout: float | None = None, guarded: bool = False) -> str | Failure:
|
||||
"""What git printed, run in cwd, else in the current directory.
|
||||
|
||||
A Failure where git cannot start, exits non-zero, prints text that is not UTF-8, or still runs after timeout seconds, which stops it.
|
||||
guarded turns off the fsmonitor, the signature check, each transport GUARD_SETTINGS names and a partial clone's fetch of its missing objects. It is for a checkout whose config may name a program.
|
||||
"""
|
||||
command = " ".join(args)
|
||||
guards = [option for setting in GUARD_SETTINGS for option in ("-c", setting)] if guarded else []
|
||||
# GIT_NO_LAZY_FETCH needs git 2.44.
|
||||
env = {**os.environ, "GIT_NO_LAZY_FETCH": "1"} if guarded else None
|
||||
try:
|
||||
ran = subprocess.run(["git", *args], capture_output=True, text=True)
|
||||
ran = subprocess.run(["git", *guards, *args], capture_output=True, cwd=cwd, encoding="utf-8", env=env, timeout=timeout)
|
||||
except UnicodeDecodeError as failure:
|
||||
return Failure(f"git {command} printed text that is not UTF-8: {failure}")
|
||||
except (OSError, ValueError) as failure:
|
||||
return Failure(f"git could not start: {failure}")
|
||||
return ran.stdout if ran.returncode == 0 else Failure(f"git {' '.join(args)}: {ran.stderr.strip()}")
|
||||
return Failure(f"git {command} could not start: {failure}")
|
||||
except subprocess.TimeoutExpired:
|
||||
return Failure(f"git {command}: stopped after {timeout} s")
|
||||
return ran.stdout if ran.returncode == 0 else Failure(f"git {command}: {ran.stderr.strip()}")
|
||||
|
||||
|
||||
def top() -> str | Failure:
|
||||
@@ -18,28 +47,36 @@ def top() -> str | Failure:
|
||||
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."""
|
||||
def default_branch(stale_ok: bool, timeout: float | None = None) -> tuple[str, str | None] | Failure:
|
||||
"""The default branch's ref, as default_ref names it after a fetch where the checkout has an origin remote, and a note on why origin reads as last fetched. With stale_ok, a failed fetch reads origin as last fetched, and the note says so. A call to origin still running after timeout seconds fails."""
|
||||
remotes = git("remote")
|
||||
if isinstance(remotes, Failure):
|
||||
return remotes
|
||||
fetch = git("fetch", "--quiet", "origin", timeout=timeout) if "origin" in remotes.split() else ""
|
||||
if isinstance(fetch, Failure) and not stale_ok:
|
||||
return fetch
|
||||
ref = default_ref(timeout=timeout)
|
||||
note = f"reading origin as last fetched: {fetch.reason}" if isinstance(fetch, Failure) else None
|
||||
return ref if isinstance(ref, Failure) else (ref, note)
|
||||
|
||||
|
||||
def default_ref(cwd: str | None = None, timeout: float | None = None) -> str | Failure:
|
||||
"""The default branch's ref as last fetched, read in cwd, else in the current directory: `origin/<branch>` with that remote, else the local main or master. Asking origin, where the checkout records no default branch for it, fails after timeout seconds."""
|
||||
remotes = git("remote", cwd=cwd)
|
||||
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)
|
||||
recorded = git("symbolic-ref", "--short", "refs/remotes/origin/HEAD", cwd=cwd)
|
||||
return recorded.strip() if not isinstance(recorded, Failure) else origin_head(cwd, timeout)
|
||||
for branch in ("main", "master"):
|
||||
if not isinstance(git("rev-parse", "--quiet", "--verify", f"refs/heads/{branch}"), Failure):
|
||||
return branch, None
|
||||
if not isinstance(git("rev-parse", "--quiet", "--verify", f"refs/heads/{branch}", cwd=cwd), Failure):
|
||||
return branch
|
||||
return Failure("no origin remote, and no main or master branch to take as the default branch")
|
||||
|
||||
|
||||
def origin_head() -> str | Failure:
|
||||
def origin_head(cwd: str | None, timeout: float | None) -> 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")
|
||||
listed = git("ls-remote", "--symref", "origin", "HEAD", cwd=cwd, timeout=timeout)
|
||||
if isinstance(listed, Failure):
|
||||
return listed
|
||||
if named := re.match(r"ref: refs/heads/(\S+)\tHEAD", listed):
|
||||
@@ -47,18 +84,31 @@ def origin_head() -> str | Failure:
|
||||
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 newest_release_tag(branch: str, cwd: str | None = None) -> str | None | Failure:
|
||||
"""The newest `v*` tag merged into branch, read in cwd, else in the current directory; None when it has none."""
|
||||
# Sorts v1.0.0-rc.1 below v1.0.0.
|
||||
tags = git("-c", "versionsort.suffix=-", "tag", "--list", "v*", "--merged", branch, "--sort=-v:refname", cwd=cwd)
|
||||
return tags if isinstance(tags, Failure) else next(iter(tags.split()), None)
|
||||
|
||||
|
||||
def 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):
|
||||
def commits_since(tag: str | None, branch: str, cwd: str | None = None) -> int | Failure:
|
||||
"""How many commits branch holds after tag, or holds in all where tag is None; read in cwd, else in the current directory."""
|
||||
count = git("rev-list", "--count", f"{tag}..{branch}" if tag else branch, cwd=cwd)
|
||||
return count if isinstance(count, Failure) else int(count)
|
||||
|
||||
|
||||
def commit_exists(commit: str, cwd: str | None = None) -> bool:
|
||||
return not isinstance(git("rev-parse", "--quiet", "--verify", f"{commit}^{{commit}}", cwd=cwd), Failure)
|
||||
|
||||
|
||||
def file_at(revision: str, path: str, cwd: str | None = None) -> str | Failure:
|
||||
"""A file's text at a revision, read in cwd, else in the current directory; empty where the revision is not a commit, such as a root commit's parent, or holds no such file."""
|
||||
if not commit_exists(revision, cwd):
|
||||
return ""
|
||||
listed = git("ls-tree", "--name-only", revision, "--", path)
|
||||
listed = git("ls-tree", "--name-only", revision, "--", path, cwd=cwd)
|
||||
if isinstance(listed, Failure):
|
||||
return listed
|
||||
return git("show", f"{revision}:{path}") if listed.strip() else ""
|
||||
return git("show", f"{revision}:{path}", cwd=cwd) if listed.strip() else ""
|
||||
|
||||
|
||||
def full_history() -> Failure | None:
|
||||
|
||||
@@ -12,7 +12,7 @@ It first replays every verdict on the reference judge: the model at xhigh effort
|
||||
judge ran on before loop-claude routed it. A verdict the reference judge returns another kind on
|
||||
may rest on records or judge rules that have changed since; either way no rung is held to it. It
|
||||
then replays the rest on each candidate rung, highest first: from the model's cheapest rung down
|
||||
to the rung the lowest R + C picks. It stops at the first rung that misses one. It prints each
|
||||
to the lowest rung a worker routes to. It stops at the first rung that misses one. It prints each
|
||||
verdict the reference judge did not reproduce, each verdict a rung missed, and the lowest rung
|
||||
that, like each rung above it, missed none. A rung it names is the evidence to add the model to
|
||||
JUDGE_REPLAYED in bin/loop_claude/routing.py, which routes that model's judge, and to record the
|
||||
@@ -28,28 +28,30 @@ import typing
|
||||
|
||||
from transcript_archive.location import archive_root, transcript_of
|
||||
from transcript_archive.read import archived_outcomes
|
||||
from rung_replay.command import arguments_or_exit, down_from, failed, limited_exit, projects_on
|
||||
from judge_replay.replay import Case, case_from, Kind, report, reproduced, sample, verdict_kind
|
||||
from project_key import checkout_of
|
||||
from rung_replay.command import down_from, failed, limited_exit, project_rung_or_exit, projects_on
|
||||
from loop_claude.effects import Effects
|
||||
from failure import Failure
|
||||
from rung_replay.search import first_reply, replayed
|
||||
from loop_claude.cycle.judge import judge_once, Verdict
|
||||
from loop_claude.cycle.judge import judge_once
|
||||
from claude_code.reply import Limited
|
||||
from model_routing.ladder import lowest_worker_rung, project_rung, Rung
|
||||
from loop_claude.project.premises import read_premises
|
||||
from loop_claude.project.records import read_records
|
||||
from claude_code.transcript import read_transcript, render
|
||||
from model_routing.ladder import Rung
|
||||
from claude_code.transcript import read_transcript
|
||||
from loop_claude.stop import Stop
|
||||
from loop_claude.verdicts import Verdict
|
||||
|
||||
TOOL = "judge-replay"
|
||||
USAGE = f"{TOOL} <model>, a model on the routing ladder"
|
||||
PER_KIND = 15
|
||||
# The effort settings.json gave every judge before loop-claude routed it; the archived verdicts came from it.
|
||||
REFERENCE_EFFORT = "xhigh"
|
||||
|
||||
|
||||
def main(argv: list[str], env: typing.Mapping[str, str], home: pathlib.Path, effects: Effects) -> int:
|
||||
anchor = project_rung_or_exit(TOOL, argv, __doc__)
|
||||
anchor = arguments_or_exit(TOOL, argv, __doc__, USAGE, model_argument)
|
||||
if isinstance(anchor, int):
|
||||
return anchor
|
||||
cases = archived_cases(anchor.model, archive_root(home, env), home)
|
||||
@@ -59,13 +61,19 @@ def main(argv: list[str], env: typing.Mapping[str, str], home: pathlib.Path, eff
|
||||
return failed(TOOL, f"no archived verdicts of projects on {anchor.model} in {archive_root(home, env)}; run loop-claude on a project on that model first")
|
||||
cases = sample(cases, PER_KIND)
|
||||
reference = Rung(anchor.model, REFERENCE_EFFORT)
|
||||
replay = replayed(cases, reference, down_from(anchor), lambda found, rung: rule(found, rung, home / ".claude", effects), reproduced, "verdicts")
|
||||
# The candidates stop at the lowest rung a worker routes to: no route uses a rung below it for the judge.
|
||||
replay = replayed(cases, reference, down_from(anchor, lowest_worker_rung(anchor)), lambda found, rung: rule(found, rung, home / ".claude", effects), reproduced, "verdicts")
|
||||
if isinstance(replay, Limited):
|
||||
return limited_exit(TOOL, replay)
|
||||
print(report(anchor.model, reference, cases, replay))
|
||||
return 0
|
||||
|
||||
|
||||
def model_argument(argv: list[str]) -> Rung | None:
|
||||
"""The project's rung of the one model argv names; None for any other argv."""
|
||||
return project_rung(argv[0]) if len(argv) == 1 else None
|
||||
|
||||
|
||||
def archived_cases(model: str, root: pathlib.Path, home: pathlib.Path) -> list[Case] | Failure:
|
||||
projects = projects_on(model, home)
|
||||
if isinstance(projects, Failure):
|
||||
@@ -91,5 +99,6 @@ def rule(case: Case, rung: Rung, claude_dir: pathlib.Path, effects: Effects) ->
|
||||
return verdict_kind(Failure(records.reason))
|
||||
if isinstance(entries, Failure):
|
||||
return verdict_kind(entries)
|
||||
verdict: Verdict | Failure | Limited = first_reply(lambda: judge_once(case.root, case.task, premises, records, render(entries), rung, effects))
|
||||
# 0 for the route's mark, as before any step-up: the replay compares verdict kinds, and a mark changes only which escalation quotes count.
|
||||
verdict: Verdict | Failure | Limited = first_reply(lambda: judge_once(case.root, case.task, premises, records, entries, 0, rung, effects))
|
||||
return verdict if isinstance(verdict, Limited) else verdict_kind(verdict)
|
||||
|
||||
@@ -6,7 +6,7 @@ import typing
|
||||
|
||||
from transcript_archive.outcomes import ANSWERED, FINISHED, first_verdict, INTERRUPTED, task_of, UNFINISHED
|
||||
from failure import Failure
|
||||
from loop_claude.cycle.judge import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict
|
||||
from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict
|
||||
from rung_replay.search import Replay
|
||||
from model_routing.ladder import Rung
|
||||
|
||||
@@ -16,12 +16,12 @@ Kind = str
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Case:
|
||||
"""One archived verdict: on_record, judged at its UTC stamp."""
|
||||
"""One archived verdict: the kind the archive gives it, judged at its UTC stamp."""
|
||||
root: str
|
||||
task: str
|
||||
transcript: pathlib.Path
|
||||
at: str
|
||||
on_record: Kind
|
||||
archived_kind: Kind
|
||||
|
||||
|
||||
def case_from(root: str, outcomes: str, transcript: pathlib.Path) -> Case | None:
|
||||
@@ -40,8 +40,8 @@ def sample(cases: list[Case], per_kind: int) -> list[Case]:
|
||||
seen: collections.Counter[Kind] = collections.Counter()
|
||||
kept = []
|
||||
for found in sorted(cases, key=lambda found: (found.at, found.root, str(found.transcript)), reverse=True):
|
||||
seen[found.on_record] += 1
|
||||
if seen[found.on_record] <= per_kind:
|
||||
seen[found.archived_kind] += 1
|
||||
if seen[found.archived_kind] <= per_kind:
|
||||
kept.append(found)
|
||||
return kept[::-1]
|
||||
|
||||
@@ -63,12 +63,12 @@ def verdict_kind(verdict: Verdict | Failure) -> Kind:
|
||||
|
||||
|
||||
def reproduced(case: Case, kind: Kind) -> list[Kind]:
|
||||
"""The kind on record, where the reply returns it: a rung is held only to a verdict the reference judge reproduces."""
|
||||
return [kind] if kind == case.on_record else []
|
||||
"""The archived kind, where the reply returns it: a rung is held only to a verdict the reference judge reproduces."""
|
||||
return [kind] if kind == case.archived_kind else []
|
||||
|
||||
|
||||
def report(model: str, reference: Rung, cases: list[Case], replay: Replay[Case, Kind, Kind]) -> str:
|
||||
kinds = collections.Counter(found.on_record for found in cases)
|
||||
kinds = collections.Counter(found.archived_kind for found in cases)
|
||||
unreproduced = [(found, kind) for found, kind in zip(cases, replay.on_reference) if not reproduced(found, kind)]
|
||||
lines = [
|
||||
f"Replayed {len(cases)} verdicts of {model} projects: {', '.join(f'{count} {kind}' for kind, count in sorted(kinds.items()))}.",
|
||||
@@ -86,4 +86,4 @@ def report(model: str, reference: Rung, cases: list[Case], replay: Replay[Case,
|
||||
|
||||
|
||||
def missed_lines(missed: list[tuple[Case, Kind]]) -> list[str]:
|
||||
return [f" {found.root} {found.at}: on record {found.on_record}, replayed {kind}" for found, kind in missed]
|
||||
return [f" {found.root} {found.at}: archived {found.archived_kind}, replayed {kind}" for found, kind in missed]
|
||||
|
||||
@@ -13,7 +13,7 @@ from transcript_archive.outcomes import ANSWERED, FINISHED, INTERRUPTED, UNFINIS
|
||||
from judge_replay.replay import Case, case_from, report, reproduced, sample, verdict_kind
|
||||
from loop_claude.effects import Effects
|
||||
from failure import Failure
|
||||
from loop_claude.cycle.judge import Finished, Interrupt, QuotedAnswer, Unfinished
|
||||
from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished
|
||||
from judge_replay import main
|
||||
from rung_replay.search import Miss, Replay, Tried
|
||||
from model_routing.ladder import Rung
|
||||
@@ -25,8 +25,8 @@ MIDDLE = Rung("claude-sonnet-5-5", "high")
|
||||
REFERENCE = Rung("claude-opus-5-5", "xhigh")
|
||||
|
||||
|
||||
def case(at, on_record):
|
||||
return Case("/code/p", "Do the next chunk.", TRANSCRIPT, at, on_record)
|
||||
def case(at, archived_kind):
|
||||
return Case("/code/p", "Do the next chunk.", TRANSCRIPT, at, archived_kind)
|
||||
|
||||
|
||||
class CaseFrom(unittest.TestCase):
|
||||
@@ -37,7 +37,7 @@ class CaseFrom(unittest.TestCase):
|
||||
def test_reads_each_kind_of_verdict(self):
|
||||
for verdict in (FINISHED, UNFINISHED, INTERRUPTED, ANSWERED):
|
||||
found = case_from("/code/p", f"Task: t\n\n2026-10-14T10:00:00Z {verdict}\n\nmore\n", TRANSCRIPT)
|
||||
self.assertEqual(found.on_record, verdict)
|
||||
self.assertEqual(found.archived_kind, verdict)
|
||||
|
||||
def test_skips_a_copy_with_no_verdict(self):
|
||||
self.assertIsNone(case_from("/code/p", "Task: t\n\n2026-10-14T10:00:00Z Stepped up\n\nWorker: y\n", TRANSCRIPT))
|
||||
@@ -60,7 +60,7 @@ class VerdictKind(unittest.TestCase):
|
||||
|
||||
|
||||
class Reproduced(unittest.TestCase):
|
||||
def test_holds_a_rung_to_a_verdict_only_where_the_reference_returned_the_kind_on_record(self):
|
||||
def test_holds_a_rung_to_a_verdict_only_where_the_reference_returned_the_archived_kind(self):
|
||||
self.assertEqual(reproduced(case("2026-10-14T10:00:00Z", FINISHED), FINISHED), [FINISHED])
|
||||
self.assertEqual(reproduced(case("2026-10-14T10:00:00Z", FINISHED), INTERRUPTED), [])
|
||||
|
||||
@@ -72,10 +72,10 @@ class Report(unittest.TestCase):
|
||||
self.assertEqual(report("claude-opus-5-5", REFERENCE, cases, replay).splitlines(), [
|
||||
"Replayed 2 verdicts of claude-opus-5-5 projects: 1 Verdict: finished, 1 Verdict: interrupt.",
|
||||
"The reference judge, claude-opus-5-5 at xhigh effort, reproduced 1. It returned another kind on:",
|
||||
" /code/p 2026-10-14T10:00:00Z: on record Verdict: finished, replayed Verdict: unfinished",
|
||||
" /code/p 2026-10-14T10:00:00Z: archived Verdict: finished, replayed Verdict: unfinished",
|
||||
"claude-sonnet-5-5 at high effort missed 0.",
|
||||
"claude-haiku-5-5 at xhigh effort missed 1:",
|
||||
" /code/p 2026-10-14T10:00:01Z: on record Verdict: interrupt, replayed Verdict: finished",
|
||||
" /code/p 2026-10-14T10:00:01Z: archived Verdict: interrupt, replayed Verdict: finished",
|
||||
"Lowest rung that, like each rung above it, returns every verdict the reference judge reproduces: claude-sonnet-5-5 at high effort",
|
||||
])
|
||||
missed_all = report("claude-opus-5-5", REFERENCE, cases, Replay([FINISHED, INTERRUPTED], [Tried(MIDDLE, [Miss(cases[1], INTERRUPTED, FINISHED)])], None)).splitlines()
|
||||
@@ -114,7 +114,7 @@ class Main(unittest.TestCase):
|
||||
result = reply(Rung(args[args.index("--model") + 1], args[args.index("--effort") + 1]), "said Verdict: interrupt" in prompt.rsplit("latest last:", 1)[-1])
|
||||
return subprocess.CompletedProcess(args, 0, json.dumps(result), "")
|
||||
|
||||
effects = Effects(claude=claude, claude_on_terminal=unused, execv=unused, git=unused, input=unused, local_time=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused)
|
||||
effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, execv=unused, git=unused, input=unused, local_time=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused)
|
||||
out, err = io.StringIO(), io.StringIO()
|
||||
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
|
||||
code = main.main(argv, {}, self.home, effects)
|
||||
@@ -122,22 +122,30 @@ class Main(unittest.TestCase):
|
||||
|
||||
@staticmethod
|
||||
def verdict(interrupt, evidence):
|
||||
output = {"answer": "", "bundled": 0, "escalation": "", "evidence": evidence, "finished": not interrupt, "interrupt": interrupt, "question": "Which?" if interrupt else ""}
|
||||
output = {"answer": "", "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "evidence": evidence, "finished": not interrupt, "interrupt": interrupt, "question": "Which?" if interrupt else "", "release_ready": False}
|
||||
return {"type": "result", "structured_output": output}
|
||||
|
||||
def test_replays_the_models_projects_on_the_reference_then_from_the_projects_rung_down_and_prints_the_lowest_that_returns_all(self):
|
||||
# Haiku misses the interrupt; Sonnet and Opus return both.
|
||||
# Sonnet misses the interrupt; Opus returns both.
|
||||
def reply(rung, interrupted):
|
||||
return self.verdict(interrupted and rung.model != "claude-haiku-5-5", f"said {INTERRUPTED if interrupted else FINISHED}")
|
||||
return self.verdict(interrupted and rung.model != "claude-sonnet-5-5", f"said {INTERRUPTED if interrupted else FINISHED}")
|
||||
|
||||
code, out, err = self.run_main(["claude-opus-5-5"], reply)
|
||||
self.assertEqual(code, 0, err)
|
||||
self.assertEqual({cwd for _, _, cwd in self.calls}, {str(self.home / "code" / "proj")})
|
||||
self.assertEqual([(model, effort) for model, effort, _ in self.calls[::2]], [("claude-opus-5-5", "xhigh"), ("claude-opus-5-5", "medium"), ("claude-sonnet-5-5", "high"), ("claude-haiku-5-5", "max")])
|
||||
self.assertEqual([(model, effort) for model, effort, _ in self.calls[::2]], [("claude-opus-5-5", "xhigh"), ("claude-opus-5-5", "medium"), ("claude-sonnet-5-5", "high")])
|
||||
self.assertIn("The reference judge, claude-opus-5-5 at xhigh effort, reproduced 2.", out)
|
||||
self.assertTrue(out.endswith("returns every verdict the reference judge reproduces: claude-sonnet-5-5 at high effort\n"))
|
||||
for said in ("The task an agent was given:\nDo it.", "1. Ship.", "From ~/.claude/CLAUDE.md:\nBe kind."):
|
||||
self.assertTrue(out.endswith("returns every verdict the reference judge reproduces: claude-opus-5-5 at medium effort\n"))
|
||||
for said in ("The task the worker was given:\nDo it.", "1. Ship.", "From ~/.claude/CLAUDE.md:\nBe kind."):
|
||||
self.assertIn(said, self.prompts[0])
|
||||
# The replay shows the judge the whole transcript, with no step-up marked in it.
|
||||
self.assertNotIn("[step]", self.prompts[0])
|
||||
|
||||
def test_tries_no_rung_below_the_lowest_a_worker_routes_to_where_every_rung_returns_every_verdict(self):
|
||||
code, out, err = self.run_main(["claude-opus-5-5"], lambda rung, interrupted: self.verdict(interrupted, f"said {INTERRUPTED if interrupted else FINISHED}"))
|
||||
self.assertEqual(code, 0, err)
|
||||
self.assertEqual([(model, effort) for model, effort, _ in self.calls[::2]][-1], ("claude-sonnet-5-5", "high"))
|
||||
self.assertTrue(out.endswith("returns every verdict the reference judge reproduces: claude-sonnet-5-5 at high effort\n"), out)
|
||||
|
||||
def test_stops_at_the_projects_rung_and_names_none_when_it_misses(self):
|
||||
code, out, _ = self.run_main(["claude-opus-5-5"], lambda rung, interrupted: self.verdict(interrupted and rung == REFERENCE, f"said {INTERRUPTED if interrupted else FINISHED}"))
|
||||
@@ -158,7 +166,6 @@ class Main(unittest.TestCase):
|
||||
code, out, _ = self.run_main(["claude-opus-5-5"], reply)
|
||||
self.assertEqual(code, 0)
|
||||
self.assertEqual(sum(model == "claude-sonnet-5-5" for model, _, _ in self.calls), 6)
|
||||
self.assertNotIn("claude-haiku-5-5", {model for model, _, _ in self.calls})
|
||||
self.assertIn("claude-opus-5-5 at medium effort missed 0.", out)
|
||||
self.assertTrue(out.endswith(": claude-opus-5-5 at medium effort\n"))
|
||||
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import decimal
|
||||
|
||||
from comprehension_history import counted_vote, entries, Entry, overall_cells, scoring_runs
|
||||
from larv_review.seats import FIRST_SEATS
|
||||
|
||||
# Matches score-outcomes, which waits for 10 finished chunks before it shows a median.
|
||||
MIN_PAIRS = 10
|
||||
|
||||
|
||||
def ruling_agreement(found: list[Entry]) -> list[bool]:
|
||||
"""For each paired ruling that holds both of the first seats' overall votes, whether they counted alike."""
|
||||
first, second = FIRST_SEATS
|
||||
cells = [overall_cells(entry) for entry in found if entry.paired]
|
||||
return [counted_vote(each[first]) == counted_vote(each[second]) for each in cells if first in each and second in each]
|
||||
|
||||
|
||||
def run_agreement(found: list[Entry]) -> list[bool]:
|
||||
"""For each commit scored at least twice, whether the first two seats' overall scores moved the same way, up, down or not at all, from its first run to its second. Both runs read one tree, so the pair is the ruling those seats would make from absolute scores on code that did not change."""
|
||||
first, second = FIRST_SEATS
|
||||
runs: dict[str, list[dict[str, decimal.Decimal]]] = {}
|
||||
for entry in scoring_runs(found):
|
||||
cells = overall_cells(entry)
|
||||
if first in cells and second in cells:
|
||||
runs.setdefault(entry.commit, []).append({first: decimal.Decimal(cells[first]), second: decimal.Decimal(cells[second])})
|
||||
pairs = [(each[0], each[1]) for each in runs.values() if len(each) >= 2]
|
||||
return [direction(before[first], after[first]) == direction(before[second], after[second]) for before, after in pairs]
|
||||
|
||||
|
||||
def direction(before: decimal.Decimal, after: decimal.Decimal) -> int:
|
||||
return (after > before) - (after < before)
|
||||
|
||||
|
||||
def agreement_report(history: str) -> str:
|
||||
"""Whether the first two seats agree more often in a paired ruling than across two scoring runs on one commit, as the comprehension check's decision assumes. It opens `Unchecked:` until the history holds MIN_PAIRS pairs of runs and one paired ruling, then `Assumption holds:` or `Assumption fails:`; equal rates fail."""
|
||||
found = entries(history)
|
||||
ruled, scored = ruling_agreement(found), run_agreement(found)
|
||||
counts = f"{' and '.join(FIRST_SEATS)} voted alike overall in {sum(ruled)} of {len(ruled)} paired rulings, and their overall scores moved alike between two scoring runs on one commit in {sum(scored)} of {len(scored)} pairs."
|
||||
if len(scored) < MIN_PAIRS or not ruled:
|
||||
return f"Unchecked: {counts} A verdict needs {MIN_PAIRS} commits each scored twice and one paired ruling."
|
||||
holds = sum(ruled) / len(ruled) > sum(scored) / len(scored)
|
||||
return f"Assumption {'holds' if holds else 'fails'}: {counts}"
|
||||
@@ -1,33 +0,0 @@
|
||||
from failure import Failure
|
||||
from git_repo import file_at, full_history, git
|
||||
from comprehension_history import HISTORY, HistoryChange
|
||||
|
||||
|
||||
def history_changes(default: str) -> list[HistoryChange] | Failure:
|
||||
"""Each merged change on the default branch that touched the history, newest first; a merge commit counts as one change against its first parent."""
|
||||
if partial := full_history():
|
||||
return partial
|
||||
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,30 @@
|
||||
from failure import Failure
|
||||
from git_repo import file_at, full_history, git
|
||||
from comprehension_history import HISTORY, HistoryChange
|
||||
|
||||
|
||||
def history_changes(default: str) -> list[HistoryChange] | Failure:
|
||||
"""Each merged change on the default branch that touched the history, newest first."""
|
||||
if partial := full_history():
|
||||
return partial
|
||||
commits = git("log", "--first-parent", "--format=%H", default, "--", HISTORY)
|
||||
if isinstance(commits, Failure):
|
||||
return commits
|
||||
changes = []
|
||||
for commit in commits.split():
|
||||
change = history_change(commit)
|
||||
if isinstance(change, Failure):
|
||||
return change
|
||||
changes.append(change)
|
||||
return changes
|
||||
|
||||
|
||||
def history_change(commit: str) -> HistoryChange | Failure:
|
||||
"""The history before and after commit. A merge commit counts as one change, against its first parent."""
|
||||
before = file_at(f"{commit}^1", HISTORY)
|
||||
if isinstance(before, Failure):
|
||||
return before
|
||||
after = file_at(commit, HISTORY)
|
||||
if isinstance(after, Failure):
|
||||
return after
|
||||
return HistoryChange(commit, before, after)
|
||||
@@ -1,14 +1,16 @@
|
||||
import pathlib
|
||||
import time
|
||||
|
||||
from comprehension_history import appended, DIMENSIONS, heading, Heading, HISTORY, latest_places, recorded, ruling_entry, scoring_entry, ScoringRun, vote_text
|
||||
from larv_review.agreement import agreement_report
|
||||
from comprehension_history import appended, DIMENSIONS, FLOOR, heading, Heading, HISTORY, latest_places, recorded, ruling_entry, scoring_entry, ScoringRun, vote_text
|
||||
from git_repo import commit_exists, top
|
||||
from larv_review.ruling import counted, overall, ruling, split, votes
|
||||
from larv_review.ruling import counted, overall, ruling, split, surplus, votes
|
||||
from failure import Failure
|
||||
from larv_review.scoring import FLOOR, means, under_floor
|
||||
from larv_review.seats import FIRST_SEATS, scores, seats_file, SeatsFile
|
||||
from larv_review.scoring import means, under_floor
|
||||
from larv_review.plan import plan_reasons
|
||||
import rank_todo
|
||||
from file_writes import replace_file
|
||||
from larv_review.seats import scores, seats_file, SeatsFile
|
||||
|
||||
|
||||
def record_ruling(votes_file: pathlib.Path) -> Failure | None:
|
||||
@@ -20,8 +22,10 @@ def record_ruling(votes_file: pathlib.Path) -> Failure | None:
|
||||
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 surplus(overall_votes):
|
||||
return Failure(f"{' and '.join(FIRST_SEATS)} both count as {overall_votes[0]} overall, which settles the ruling; drop the other seats' lines")
|
||||
tally = ", ".join(f"{seat.name} {vote_text(DIMENSIONS[-1], overall(written[seat.name]), overall(counts[seat.name]))}" for seat in seats_read.seats)
|
||||
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
|
||||
@@ -46,7 +50,23 @@ def record_scoring(default: str, scores_file: pathlib.Path, ids: list[int]) -> F
|
||||
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}.")
|
||||
return append(given.read, scoring_entry(named.title, scoring))
|
||||
if unrecorded := append(given.read, scoring_entry(named.title, scoring)):
|
||||
return unrecorded
|
||||
return rerank()
|
||||
|
||||
|
||||
def rerank() -> Failure | None:
|
||||
"""Rank the checkout's todo.md again as rank_todo.py does, since the overall sets code health's weight, and fail where rank_todo.py would. The run stays recorded whatever happens, so those failures say to settle todo.md and run rank_todo.py on it, not to record the run again."""
|
||||
checkout = top()
|
||||
if isinstance(checkout, Failure):
|
||||
return checkout
|
||||
todo = pathlib.Path(checkout, "todo.md")
|
||||
ranked = rank_todo.rank_file(todo)
|
||||
if isinstance(ranked, Failure):
|
||||
return Failure(f"recorded the run, but rank_todo.py cannot rank {todo}: {ranked.reason}. Fix what that names, then run rank_todo.py on {todo}, not record-scoring again")
|
||||
if ranked.under_bar:
|
||||
return Failure(f"recorded the run and ranked {todo}, but the lines above name items now under the bar. Settle each as its line says, then run rank_todo.py on {todo}, not record-scoring again")
|
||||
return None
|
||||
|
||||
|
||||
def scored_seats(given: SeatsFile) -> ScoringRun | Failure:
|
||||
@@ -57,7 +77,7 @@ def scored_seats(given: SeatsFile) -> ScoringRun | Failure:
|
||||
|
||||
|
||||
def read_seats(path: pathlib.Path, paired: bool) -> 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 the history already holds an entry on what it reads; it runs before anything is printed."""
|
||||
"""The seats file and the heading its entry goes under. Fails when the file names a commit the checkout lacks, or 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:
|
||||
@@ -85,6 +105,14 @@ def show_places() -> Failure | None:
|
||||
return None
|
||||
|
||||
|
||||
def show_agreement() -> Failure | None:
|
||||
history = history_file()
|
||||
if isinstance(history, Failure):
|
||||
return history
|
||||
print(agreement_report(history[1]))
|
||||
return None
|
||||
|
||||
|
||||
def history_file() -> tuple[pathlib.Path, str] | Failure:
|
||||
"""The checkout's history and its text, empty when the file is missing."""
|
||||
checkout = top()
|
||||
+65
-25
@@ -1,17 +1,21 @@
|
||||
"""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 and latest places.
|
||||
"""Hold larv-review's mechanical rules: the chunk's review folder, the paired ruling's base and vote count, each pass's rounds, the scoring run's trigger, and the comprehension history's format and latest places, and its count of how often seats agree.
|
||||
|
||||
usage: larv-review ruling-base | round-count | needs-scoring-run [<item ID>...] | record-ruling <votes file> | record-scoring <scores file> [<item ID>...] | places
|
||||
usage: larv-review review-folder | ruling-base | round-count | needs-scoring-run [<item ID>...] | record-ruling <votes file> | record-scoring <scores file> [<item ID>...] | places | agreement
|
||||
|
||||
The comprehension check records how hard a project is to read, two ways, and blocks no merge. In a
|
||||
paired ruling, simulated readers, the seats, read the branch's head beside a base and vote better,
|
||||
same or worse, overall and on each dimension. In a scoring run, four seats score the project from 1
|
||||
to 10. Each seat names the places it found hard.
|
||||
|
||||
Run it inside a project checkout or one of its worktrees. Each command but record-ruling and places
|
||||
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.
|
||||
Run it inside a project checkout or one of its worktrees. Each command but review-folder,
|
||||
record-ruling, places and agreement first fetches origin, when the checkout has that remote, and
|
||||
takes origin's default branch, or else the local main or master, as the default branch. When the
|
||||
fetch fails, round-count 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.
|
||||
|
||||
review-folder makes the chunk's review folder, where each reviewer writes its report, and prints its
|
||||
path: ~/.local/state/larv-review/ followed by the worktree's path relative to ~, or to / outside it.
|
||||
It leaves ~/.local/state/larv-review readable by you alone.
|
||||
|
||||
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 paired ruling or a scoring
|
||||
@@ -25,11 +29,13 @@ 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.
|
||||
an item whose tagline names the comprehension floor. It is also due when the chunk leaves a release
|
||||
with no item in the checkout's todo.md, once the shipped items are set aside, and work has landed
|
||||
towards that release; bin/larv_review/plan.py's `work_landed` and `landed_towards` say when. A release the checkout's
|
||||
todo.md marks renamed in its ## Renamed section, as `- 0.2.1 renamed to 0.3.0`, is due none.
|
||||
|
||||
A second scoring run of one head names itself `<PR or branch> rerun at <commit>`, so record-scoring
|
||||
does not refuse it as a repeat of the first.
|
||||
|
||||
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
|
||||
@@ -64,44 +70,60 @@ prints `Ruling:` and appends the ruling.
|
||||
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. 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.
|
||||
floor of {floor}, a line opening `Floor:` naming each one. Then it ranks the checkout's todo.md as
|
||||
rank_todo.py does, since the overall sets the weight of code health, the goal every project shares,
|
||||
and exits 1 where rank_todo.py would, with the run recorded.
|
||||
|
||||
places prints the places seats found hard since the newest scoring run: that run's places, and,
|
||||
places prints the places seats found hard since the newest scored commit: the places of each scoring
|
||||
run on it, and,
|
||||
in each later ruling, each place opening with a dimension, or Overall, that its seat voted worse.
|
||||
A ruling recorded with scoring seats' places counts as a scoring run. Each entry's places come
|
||||
under its heading, oldest first. With no scoring run, it reads every ruling.
|
||||
|
||||
Each record is appended to the history, created when missing, under a heading of the current UTC
|
||||
agreement pairs the first two scoring runs recorded on one commit. In each pair, a seat's overall
|
||||
score goes up, goes down or stays the same. It checks the assumption behind the paired ruling: Mid A
|
||||
and the inherited architect vote alike overall in a paired ruling more often than their scores go the
|
||||
same way in a pair. It prints both counts. It opens `Unchecked:` until the history holds {pairs} such
|
||||
pairs and one paired ruling, then `Assumption holds:` or `Assumption fails:`, and exits 0 each time.
|
||||
|
||||
Each entry 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, 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.
|
||||
breaks the shape above, a todo.md that fails rank_todo.py after record-scoring records a run, or
|
||||
when git cannot start, finds no checkout or no default branch, cannot fetch origin for ruling-base,
|
||||
needs-scoring-run or record-scoring, or cannot read or write the history, todo.md or the review
|
||||
folder.
|
||||
"""
|
||||
import pathlib
|
||||
import re
|
||||
import sys
|
||||
import typing
|
||||
|
||||
from round_titles import CAP, PASSES, round_counts
|
||||
from git_repo import default_branch, git
|
||||
from round_titles import CAP, round_counts
|
||||
from git_repo import default_branch, git, top
|
||||
from failure import Failure
|
||||
from larv_review.scoring import FLOOR
|
||||
from larv_review.git import history_changes
|
||||
from comprehension_history import FLOOR
|
||||
from larv_review.history_changes import history_changes
|
||||
from larv_review.ruling_base import measured_commit
|
||||
from larv_review.agreement import MIN_PAIRS
|
||||
from review_passes import PASSES
|
||||
from larv_review.plan import plan_reasons
|
||||
from larv_review.record import record_ruling, record_scoring, show_places
|
||||
from larv_review.history_commands import record_ruling, record_scoring, show_agreement, show_places
|
||||
from review_folder import REPORTS, review_folder
|
||||
|
||||
USAGE = "usage: larv-review ruling-base | round-count | needs-scoring-run [<item ID>...] | record-ruling <votes file> | record-scoring <scores file> [<item ID>...] | places"
|
||||
USAGE = "usage: larv-review review-folder | ruling-base | round-count | needs-scoring-run [<item ID>...] | record-ruling <votes file> | record-scoring <scores file> [<item ID>...] | places | agreement"
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
if argv in (["-h"], ["--help"]):
|
||||
print(__doc__.strip().format(cap=CAP, floor=FLOOR))
|
||||
print(__doc__.strip().format(cap=CAP, floor=FLOOR, pairs=MIN_PAIRS))
|
||||
return 0
|
||||
command, *given = argv or [""]
|
||||
if command == "ruling-base" and not given:
|
||||
if command == "review-folder" and not given:
|
||||
done = make_review_folder()
|
||||
elif 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)
|
||||
@@ -113,6 +135,8 @@ def main(argv: list[str]) -> int:
|
||||
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 == "places" and not given:
|
||||
done = show_places()
|
||||
elif command == "agreement" and not given:
|
||||
done = show_agreement()
|
||||
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)
|
||||
@@ -139,6 +163,22 @@ def with_default_branch(command: typing.Callable[[str], Failure | None], stale_o
|
||||
return command(branch)
|
||||
|
||||
|
||||
def make_review_folder() -> Failure | None:
|
||||
worktree = top()
|
||||
if isinstance(worktree, Failure):
|
||||
return worktree
|
||||
home = pathlib.Path.home()
|
||||
folder = pathlib.Path(review_folder(str(home), worktree))
|
||||
try:
|
||||
(home / REPORTS).mkdir(parents=True, exist_ok=True)
|
||||
(home / REPORTS).chmod(0o700)
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
except OSError as failure:
|
||||
return Failure(f"could not make the review folder {folder}: {failure}")
|
||||
print(folder)
|
||||
return None
|
||||
|
||||
|
||||
def show_ruling_base(default: str) -> Failure | None:
|
||||
changes = history_changes(default)
|
||||
if isinstance(changes, Failure):
|
||||
|
||||
+46
-19
@@ -1,33 +1,54 @@
|
||||
import pathlib
|
||||
|
||||
from chunk_pick import Cut, default_plan, LastCut, next_release, Unknown
|
||||
from failure import Failure
|
||||
from git_repo import file_at, top
|
||||
from todo_table import Item, items
|
||||
from larv_review.git import landed_since_release
|
||||
from todo_table import Item, items, NoItemsTable, renames, version
|
||||
from git_repo import top
|
||||
|
||||
|
||||
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.
|
||||
def scoring_run_due(before: list[Item], after: list[Item], ships: list[int], landed: tuple[int, int, int] | None, renamed: set[tuple[int, int, int]]) -> list[str] | Failure:
|
||||
"""Why the plan calls a scoring run, empty when it does not.
|
||||
|
||||
A chunk that ships an item naming the floor is due one, so it can prove the floor met. So is a chunk that empties a release after work has landed towards it, so no release ends unmeasured. 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.
|
||||
A chunk that ships an item naming the floor is due one, so it can prove the floor met. So is a chunk that empties a release after work has landed towards it, so no release ends unmeasured. A release the chunk's plan marks renamed is due none.
|
||||
|
||||
before is the default branch's plan and after the chunk's. ships holds the IDs of the items the chunk ships. landed is the next release where work has landed towards it, else None (`landed_towards`). renamed holds the releases the chunk's plan marks renamed.
|
||||
"""
|
||||
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")
|
||||
for release in emptied(before, after, shipped, renamed):
|
||||
if work_landed(release, shipped, landed):
|
||||
# SKILL.md → "Second run" keys on this wording.
|
||||
reasons.append(f"leaves release {version(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."""
|
||||
# larv-review --help points here rather than restating the rule, so the rule is written once.
|
||||
def work_landed(release: tuple[int, int, int], shipped: list[Item], landed: tuple[int, int, int] | None) -> bool:
|
||||
"""Whether work has landed towards release, for the scoring-run trigger. It has when the chunk ships one of the release's items. It has too when release equals landed: the default branch's next release, once work has landed towards it."""
|
||||
return any(item.release == release for item in shipped) or release == landed
|
||||
|
||||
|
||||
def landed_towards(found: list[Item], cut: LastCut) -> tuple[int, int, int] | None | Failure:
|
||||
"""The next release on the default branch, once work has landed towards it: once one or more changes are unreleased, as `chunk_pick.unreleased_changes` counts them. None where there is no next release, or no change is unreleased. found is the default branch's plan."""
|
||||
upcoming = next_release(found, cut)
|
||||
if isinstance(upcoming, Unknown):
|
||||
return Failure("could not tell the next release: the default branch's todo.md history cannot be read")
|
||||
# Cut's release is the last cut's version or earlier, so no work lands towards it.
|
||||
if isinstance(upcoming, Cut):
|
||||
return None
|
||||
if isinstance(upcoming.landed, Failure):
|
||||
return Failure(f"could not tell whether work landed towards the next release: {upcoming.landed.reason}")
|
||||
return upcoming.release if upcoming.landed else None
|
||||
|
||||
|
||||
def emptied(before: list[Item], after: list[Item], shipped: list[Item], renamed: set[tuple[int, int, int]]) -> 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, unless the chunk's plan marks it renamed."""
|
||||
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)
|
||||
kept = [item for item in after if item.id not in {ship.id for ship in shipped}]
|
||||
return sorted(named - {item.release for item in kept} - renamed)
|
||||
|
||||
|
||||
def plan_reasons(default: str, ids: list[int]) -> list[str] | Failure:
|
||||
@@ -35,7 +56,8 @@ def plan_reasons(default: str, ids: list[int]) -> list[str] | Failure:
|
||||
checkout = top()
|
||||
if isinstance(checkout, Failure):
|
||||
return checkout
|
||||
before = file_at(default, "todo.md")
|
||||
held = default_plan(checkout, default)
|
||||
before = held.todo
|
||||
if isinstance(before, Failure):
|
||||
return before
|
||||
try:
|
||||
@@ -43,15 +65,20 @@ def plan_reasons(default: str, ids: list[int]) -> list[str] | Failure:
|
||||
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) or []
|
||||
planned = items(before)
|
||||
if isinstance(planned, NoItemsTable):
|
||||
planned = []
|
||||
if isinstance(planned, Failure):
|
||||
return Failure(f"{default}'s todo.md: {planned.reason}")
|
||||
chunk = items(after)
|
||||
if chunk is None:
|
||||
if isinstance(chunk, NoItemsTable):
|
||||
return Failure("the checkout's todo.md has no items table; rank_todo.py --help shows one")
|
||||
if isinstance(chunk, Failure):
|
||||
return Failure(f"the checkout's todo.md: {chunk.reason}")
|
||||
landed = landed_since_release(default)
|
||||
renamed = renames(after)
|
||||
if isinstance(renamed, Failure):
|
||||
return Failure(f"the checkout's todo.md: {renamed.reason}")
|
||||
landed = landed_towards(planned, held.cut)
|
||||
if isinstance(landed, Failure):
|
||||
return landed
|
||||
return scoring_run_due(planned, chunk, ids, landed)
|
||||
return scoring_run_due(planned, chunk, ids, landed, renamed)
|
||||
|
||||
@@ -6,7 +6,7 @@ VOTES = ("better", "same", "worse")
|
||||
|
||||
|
||||
def votes(seats: list[Seat]) -> dict[str, list[str]] | Failure:
|
||||
"""Each seat's five votes as written, in DIMENSIONS' order."""
|
||||
"""Each seat's five votes as written, in DIMENSIONS' order. Fails unless the seats come in a votes file's order and each seat's vote line and places have its shape. `counted` decides what the votes count as."""
|
||||
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'}")
|
||||
@@ -18,9 +18,6 @@ def votes(seats: list[Seat]) -> dict[str, list[str]] | Failure:
|
||||
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
|
||||
|
||||
|
||||
@@ -38,6 +35,11 @@ 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 surplus(overall: list[str]) -> bool:
|
||||
"""Whether seats beyond the first two voted, though the first two agree overall: their agreement settles the ruling by itself."""
|
||||
return len(overall) > 2 and overall[0] == overall[1]
|
||||
|
||||
|
||||
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]
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
import decimal
|
||||
|
||||
from comprehension_history import DIMENSIONS
|
||||
|
||||
FLOOR = decimal.Decimal("7.0")
|
||||
from comprehension_history import DIMENSIONS, FLOOR
|
||||
|
||||
|
||||
def means(lines: list[list[str]]) -> list[decimal.Decimal]:
|
||||
|
||||
@@ -10,16 +10,18 @@ import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from larv_review.agreement import agreement_report, ruling_agreement, run_agreement
|
||||
from comprehension_history import appended, entries, HistoryChange, latest_places, Place, recorded, ruling_entry, scoring_entry, ScoringRun, Seat
|
||||
import comprehension_history
|
||||
from larv_review.ruling import counted, ruling, split, votes
|
||||
from larv_review.ruling import counted, ruling, split, surplus, votes
|
||||
from failure import Failure
|
||||
from test_env import isolated_env
|
||||
from todo_table import Item, items
|
||||
from todo_table import Item, items, NoItemsTable
|
||||
from larv_review.plan import landed_towards, plan_reasons, scoring_run_due
|
||||
from chunk_pick import LastCut
|
||||
from larv_review.scoring import means, under_floor
|
||||
from larv_review.ruling_base import measured_commit
|
||||
from larv_review.seats import score_line, scores, seats_file
|
||||
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"
|
||||
@@ -66,9 +68,14 @@ class Seats(unittest.TestCase):
|
||||
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):
|
||||
def test_reads_the_other_two_seats_even_when_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)
|
||||
self.assertEqual(list(votes(seats)), [seat.name for seat in seats])
|
||||
|
||||
def test_flags_seats_beyond_the_first_two_when_those_agree_overall(self):
|
||||
self.assertTrue(surplus(["worse", "worse", "better", "better"]))
|
||||
self.assertFalse(surplus(["worse", "worse"]))
|
||||
self.assertFalse(surplus(["worse", "same", "better", "better"]))
|
||||
|
||||
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"), [])]
|
||||
@@ -155,6 +162,95 @@ class History(unittest.TestCase):
|
||||
fell = ruled.replace("2026-10-10T12:00:00Z", "2026-10-09T12:00:00Z") + "\n| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |\n|---|---|---|---|---|---|\n| Mid A | 7 | 6 | 7 | 7 | 7 |\n| Mean | 7 | 6 | 7 | 7 | 7 |\n\nJunior A, hardest first:\n\n- `bin/j.py:5` `s`: wide\n"
|
||||
self.assertEqual(latest_places(appended(appended("", scored), fell)), hard_since.replace("2026-10-10T12:00:00Z", "2026-10-09T12:00:00Z") + "\nJunior A, hardest first:\n\n- `bin/j.py:5` `s`: wide\n")
|
||||
|
||||
def test_names_the_places_of_every_run_on_the_newest_scored_commit(self):
|
||||
run = "## {time}, {pr} at {commit}\n\nJunior A, hardest first:\n\n- `bin/b.py:{line}` `h`: long\n"
|
||||
first, rerun, other = (run.format(time=time, pr=pr, commit=commit, line=line) for time, pr, commit, line in (("2026-10-08T12:00:00Z", "PR #1", "aaaaaaa", 1), ("2026-10-08T13:00:00Z", "PR #1 rerun", "aaaaaaa", 2), ("2026-10-09T12:00:00Z", "PR #2", "bbbbbbb", 3)))
|
||||
self.assertEqual(latest_places(appended(appended("", first), rerun)), first + "\n" + rerun)
|
||||
self.assertEqual(latest_places(appended(appended(appended("", first), rerun), other)), other)
|
||||
in_full = rerun.replace("aaaaaaa", "aaaaaaa" + "0" * 33)
|
||||
self.assertEqual(latest_places(appended(appended("", first), in_full)), first + "\n" + in_full)
|
||||
|
||||
|
||||
def scored(time: str, pr: str, commit: str, mid: str, architect: str) -> str:
|
||||
"""A scoring run's entry as the history writes it, with the two seats' overall scores."""
|
||||
run = ScoringRun([], {"Mid A": ["7", "7", "7", "7", mid], "Inherited architect": ["7", "7", "7", "7", architect]}, [decimal.Decimal("7.00")] * 5)
|
||||
return scoring_entry(f"{time}, {pr} at {commit}", run)
|
||||
|
||||
|
||||
def ruled(time: str, pr: str, mid: str, architect: str, voted: str | None = None) -> str:
|
||||
"""A paired ruling's entry as the history writes it; `voted` is what Mid A said overall when it counted as `mid`."""
|
||||
counts = {"Mid A": ["same"] * 4 + [mid], "Inherited architect": ["same"] * 4 + [architect]}
|
||||
said = {**counts, "Mid A": ["same"] * 4 + [voted or mid]}
|
||||
return ruling_entry(f"{time}, {pr} at ccccccc, against aaaaaaa", [Seat("Mid A", "", []), Seat("Inherited architect", "", [])], said, counts, "same")
|
||||
|
||||
|
||||
def pairs_of_runs(alike: int, apart: int) -> list[str]:
|
||||
"""Each pair is two runs on one commit: Mid A and the architect both up, or Mid A up and the architect not moving."""
|
||||
return [scored(f"2026-10-02T00:{index:02d}:{later}Z", "PR #1 rerun" if later else "PR #1", f"{index:07x}", "7.5" if later else "7", "7.5" if later and index < alike else "7") for index in range(alike + apart) for later in (0, 1)]
|
||||
|
||||
|
||||
class Agreement(unittest.TestCase):
|
||||
def test_counts_the_rulings_whose_two_seats_voted_alike_overall(self):
|
||||
old = "## 2026-10-08T18:37:21Z, PR #228 at 2682668, against 8c9bf09\n\nRuling: worse\n\n| Seat | Vote |\n|---|---|\n| Mid A | worse |\n| Inherited architect | worse |\n"
|
||||
history = "\n".join([ruled("2026-10-01T00:00:00Z", "PR #1", "same", "same"), ruled("2026-10-02T00:00:00Z", "PR #2", "same", "same", voted="worse"), ruled("2026-10-03T00:00:00Z", "PR #3", "worse", "better"), old])
|
||||
self.assertEqual(ruling_agreement(entries(history)), [True, True, False, True])
|
||||
|
||||
def test_compares_the_two_seats_across_the_first_two_runs_on_one_commit(self):
|
||||
both_up = [scored("2026-10-01T00:00:00Z", "PR #1", "aaaaaaa", "7", "7"), scored("2026-10-02T00:00:00Z", "PR #1 rerun", "aaaaaaa", "7.5", "7.5")]
|
||||
one_up = [scored("2026-10-03T00:00:00Z", "PR #2", "bbbbbbb", "7", "7"), scored("2026-10-04T00:00:00Z", "PR #2 rerun", "bbbbbbb", "7.5", "7")]
|
||||
self.assertEqual(run_agreement(entries("\n".join([*both_up, *one_up]))), [True, False])
|
||||
|
||||
def test_counts_opposite_moves_and_a_move_against_none_as_different(self):
|
||||
opposite = [scored("2026-10-01T00:00:00Z", "PR #1", "aaaaaaa", "7", "7"), scored("2026-10-02T00:00:00Z", "PR #1 rerun", "aaaaaaa", "7.5", "6.5")]
|
||||
down_and_none = [scored("2026-10-03T00:00:00Z", "PR #2", "bbbbbbb", "7", "7"), scored("2026-10-04T00:00:00Z", "PR #2 rerun", "bbbbbbb", "6.5", "7")]
|
||||
both_down = [scored("2026-10-05T00:00:00Z", "PR #3", "ccccccc", "7", "7"), scored("2026-10-06T00:00:00Z", "PR #3 rerun", "ccccccc", "6.5", "6.5")]
|
||||
self.assertEqual(run_agreement(entries("\n".join([*opposite, *down_and_none, *both_down]))), [False, False, True])
|
||||
|
||||
def test_leaves_out_commits_scored_once_and_runs_of_one_pr_on_different_commits(self):
|
||||
history = "\n".join([scored("2026-10-01T00:00:00Z", "PR #1", "aaaaaaa", "7", "7"), scored("2026-10-02T00:00:00Z", "PR #1", "bbbbbbb", "7.5", "7.5")])
|
||||
self.assertEqual(run_agreement(entries(history)), [])
|
||||
|
||||
def test_takes_the_two_earliest_runs_of_a_commit_whatever_order_the_file_holds_them(self):
|
||||
history = "\n".join([scored("2026-10-03T00:00:00Z", "PR #1 again", "aaaaaaa", "6", "7"), scored("2026-10-01T00:00:00Z", "PR #1", "aaaaaaa", "7", "7"), scored("2026-10-02T00:00:00Z", "PR #1 rerun", "aaaaaaa", "7.5", "7.5")])
|
||||
self.assertEqual(run_agreement(entries(history)), [True])
|
||||
|
||||
def test_skips_a_run_whose_table_lists_neither_seat(self):
|
||||
mean_only = scoring_entry("2026-10-01T12:00:00Z, PR #1 at aaaaaaa", ScoringRun([], {}, [decimal.Decimal("7.00")] * 5))
|
||||
history = "\n".join([mean_only, scored("2026-10-01T00:00:00Z", "PR #1 rerun", "aaaaaaa", "7", "7"), scored("2026-10-02T00:00:00Z", "PR #1 again", "aaaaaaa", "7.5", "7.5")])
|
||||
self.assertEqual(run_agreement(entries(history)), [True])
|
||||
|
||||
def test_skips_an_entry_listing_one_seat_or_an_empty_overall(self):
|
||||
one_seat = "## 2026-10-01T00:00:00Z, PR #1 at aaaaaaa, against bbbbbbb\n\nRuling: same\n\n| Seat | Overall |\n|---|---|\n| Mid A | same |\n"
|
||||
empty = "## 2026-10-02T00:00:00Z, PR #2 at ccccccc, against bbbbbbb\n\nRuling: same\n\n| Seat | Overall |\n|---|---|\n| Mid A | same |\n| Inherited architect | |\n"
|
||||
self.assertEqual(ruling_agreement(entries("\n".join([one_seat, empty]))), [])
|
||||
half = "## 2026-10-03T00:00:00Z, PR #3 at ddddddd\n\n| Seat | Overall |\n|---|---|\n| Mid A | 7 |\n"
|
||||
self.assertEqual(run_agreement(entries("\n".join([half, half.replace("PR #3", "PR #3 rerun").replace("T00:00:00Z", "T01:00:00Z")]))), [])
|
||||
|
||||
def test_records_a_rerun_beside_the_run_it_repeats(self):
|
||||
history = appended("", scored("2026-10-01T00:00:00Z", "PR #1", "aaaaaaa", "7", "7"))
|
||||
self.assertTrue(recorded(history, "PR #1 at aaaaaaa"))
|
||||
self.assertFalse(recorded(history, "PR #1 rerun at aaaaaaa"))
|
||||
|
||||
def test_gives_no_verdict_before_ten_pairs_of_runs_and_a_ruling(self):
|
||||
ruling = ruled("2026-10-20T00:00:00Z", "PR #2", "same", "same")
|
||||
self.assertIn("Unchecked: ", agreement_report("\n".join([*pairs_of_runs(9, 0), ruling])))
|
||||
self.assertIn("Unchecked: ", agreement_report("\n".join(pairs_of_runs(10, 0))))
|
||||
|
||||
def test_holds_when_the_seats_agree_in_a_higher_share_of_rulings_than_of_pairs_of_runs(self):
|
||||
rulings = [ruled(f"2026-10-20T00:00:0{index}Z", f"PR #{index + 2}", "same", "same") for index in range(3)]
|
||||
report = agreement_report("\n".join([*pairs_of_runs(5, 5), *rulings]))
|
||||
self.assertEqual(report.split(":")[0], "Assumption holds")
|
||||
self.assertIn("3 of 3 paired rulings", report)
|
||||
self.assertIn("5 of 10 pairs", report)
|
||||
|
||||
def test_fails_when_the_two_shares_are_equal(self):
|
||||
rulings = [ruled("2026-10-20T00:00:00Z", "PR #2", "same", "same"), ruled("2026-10-20T00:00:01Z", "PR #3", "worse", "same")]
|
||||
self.assertEqual(agreement_report("\n".join([*pairs_of_runs(5, 5), *rulings])).split(":")[0], "Assumption fails")
|
||||
|
||||
def test_fails_when_the_seats_agree_in_a_lower_share_of_rulings_than_of_pairs_of_runs(self):
|
||||
rulings = [ruled("2026-10-20T00:00:00Z", "PR #2", "same", "same"), ruled("2026-10-20T00:00:01Z", "PR #3", "same", "same"), ruled("2026-10-20T00:00:02Z", "PR #4", "worse", "same")]
|
||||
self.assertEqual(agreement_report("\n".join([*pairs_of_runs(8, 2), *rulings])).split(":")[0], "Assumption fails")
|
||||
|
||||
|
||||
class Base(unittest.TestCase):
|
||||
def test_takes_the_newest_change_adding_an_entry(self):
|
||||
@@ -170,32 +266,77 @@ class Base(unittest.TestCase):
|
||||
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 | 3 | 1 | 1 | 1 | 9.0 |")), [item(3, (0, 1, 0))])
|
||||
self.assertIsNone(items("# todo\n"))
|
||||
self.assertEqual(items("# todo\n"), NoItemsTable("todo.md holds no items table"))
|
||||
self.assertIsInstance(items("# todo\n"), Failure)
|
||||
self.assertIsInstance(items(todo("| 0 | 0.1.0 | | **Do it.** | 1 | 1 | 3 | 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)
|
||||
self.assertEqual(scoring_run_due(plan, plan, [1], (0, 1, 0), set()), ["ships item 1, which names the comprehension floor"])
|
||||
self.assertIsInstance(scoring_run_due(plan, plan, [9], (0, 1, 0), set()), 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), [])
|
||||
self.assertEqual(scoring_run_due(plan, plan, [1], None, set()), ["leaves release 0.1.0 with no plan item"])
|
||||
self.assertEqual(scoring_run_due(plan, plan + [item(3, (0, 1, 0))], [1], (0, 1, 0), set()), [])
|
||||
|
||||
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), [])
|
||||
self.assertEqual(scoring_run_due(before, after, [2], (0, 1, 0), set()), ["leaves release 0.1.0 with no plan item"])
|
||||
self.assertEqual(scoring_run_due(before, after, [], (0, 1, 0), set()), [])
|
||||
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), [])
|
||||
self.assertEqual(scoring_run_due(before, emptied, [2], None, set()), ["leaves release 0.1.0 with no plan item"])
|
||||
self.assertEqual(scoring_run_due(before, emptied, [], (0, 1, 0), set()), ["leaves release 0.1.0 with no plan item"])
|
||||
self.assertEqual(scoring_run_due(before, emptied, [], None, set()), [])
|
||||
|
||||
def test_is_not_due_when_the_chunk_marks_the_next_release_renamed(self):
|
||||
before = [item(1, (0, 2, 1)), item(2, (0, 3, 0))]
|
||||
renamed = {(0, 2, 1)}
|
||||
self.assertEqual(scoring_run_due(before, [item(1, (0, 3, 0)), item(2, (0, 4, 0))], [], (0, 2, 1), renamed), [])
|
||||
self.assertEqual(scoring_run_due(before, [item(1, (0, 3, 0)), item(2, (0, 3, 0))], [], (0, 2, 1), renamed), [])
|
||||
dropped = [item(1, (0, 2, 1)), item(3, (0, 2, 1)), item(2, (0, 3, 0))]
|
||||
self.assertEqual(scoring_run_due(dropped, [item(1, (0, 3, 0)), item(2, (0, 3, 0))], [], (0, 2, 1), renamed), [])
|
||||
|
||||
def test_is_due_when_the_chunk_defers_the_next_releases_last_items_unmarked(self):
|
||||
before = [item(1, (0, 2, 1)), item(2, (0, 3, 0))]
|
||||
self.assertEqual(scoring_run_due(before, [item(1, (0, 3, 0)), item(2, (0, 3, 0))], [], (0, 2, 1), set()), ["leaves release 0.2.1 with no plan item"])
|
||||
|
||||
def test_words_the_emptied_release_reason_as_skill_md_s_second_run_quotes_it(self):
|
||||
skill = (pathlib.Path(__file__).resolve().parents[2] / "skills" / "larv-review" / "SKILL.md").read_text()
|
||||
self.assertIn("`leaves release … with no plan item`", skill)
|
||||
reasons = scoring_run_due([item(1, (0, 1, 0))], [], [], (0, 1, 0), set())
|
||||
self.assertRegex(reasons[0], r"^leaves release [0-9.]+ with no plan item$")
|
||||
|
||||
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), [])
|
||||
self.assertEqual(scoring_run_due(before, before[:1], [], (0, 1, 0), set()), [])
|
||||
|
||||
|
||||
|
||||
class LandedTowards(unittest.TestCase):
|
||||
def test_names_the_next_release_only_where_a_change_is_unreleased(self):
|
||||
plan = [item(1, (0, 2, 0))]
|
||||
changelog = "# Changelog\n\n## Unreleased\n\n- Did a thing.\n"
|
||||
self.assertEqual(landed_towards(plan, LastCut("v0.1.0", changelog, 0, [])), (0, 2, 0))
|
||||
self.assertEqual(landed_towards(plan, LastCut("v0.1.0", "# Changelog\n\n## Unreleased\n", 3, [])), None)
|
||||
self.assertEqual(landed_towards(plan, LastCut("v0.1.0", "", 3, [])), (0, 2, 0))
|
||||
self.assertEqual(landed_towards(plan, LastCut(None, "", 0, [])), None)
|
||||
|
||||
def test_names_no_release_where_the_plan_files_items_under_the_last_cut_or_names_none_after_it(self):
|
||||
changelog = "# Changelog\n\n## Unreleased\n\n- Did a thing.\n"
|
||||
self.assertIsNone(landed_towards([item(1, (0, 1, 0))], LastCut("v0.1.0", changelog, 0, [])))
|
||||
self.assertIsNone(landed_towards([], LastCut("v0.1.0", changelog, 0, [""])))
|
||||
|
||||
def test_names_the_next_release_where_the_plan_holds_no_item_for_it(self):
|
||||
named = "| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|---|---|\n| 1 | 0.2.0 | | | **Do 1.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 | 10.0 |\n"
|
||||
changelog = "# Changelog\n\n## Unreleased\n\n- Did a thing.\n"
|
||||
self.assertEqual(landed_towards([item(2, (0, 3, 0))], LastCut("v0.1.0", changelog, 0, [f"## Items\n\n{named}"])), (0, 2, 0))
|
||||
|
||||
def test_fails_where_the_changes_or_the_next_release_cannot_be_read(self):
|
||||
plan = [item(1, (0, 2, 0))]
|
||||
self.assertIsInstance(landed_towards(plan, LastCut("v0.1.0", Failure("unreadable"), Failure("count unreadable"), [])), Failure)
|
||||
self.assertIsInstance(landed_towards([], LastCut("v0.1.0", "", 3, Failure("log unreadable"))), Failure)
|
||||
|
||||
|
||||
class LarvReviewTool(unittest.TestCase):
|
||||
@@ -264,6 +405,37 @@ class LarvReviewTool(unittest.TestCase):
|
||||
self.assertEqual(self.run_tool("needs-scoring-run").stdout, "No scoring run due.\n")
|
||||
self.assertIn("todo.md's ID column", self.run_tool("needs-scoring-run", "item-85").stderr)
|
||||
|
||||
def test_calls_a_scoring_run_for_a_deferred_release_and_none_for_one_the_checkouts_plan_marks_renamed(self):
|
||||
rows = ("| 1 | 0.2.0 | | **Do it.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |", "| 2 | 0.2.0 | | **Then this.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |", "| 3 | 0.2.0 | | **And this.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |")
|
||||
self.commit("Move 0.1.0's item to 0.2.0", {"todo.md": todo(*rows)})
|
||||
self.assertEqual(self.run_tool("needs-scoring-run").stdout, "Scoring run due: the chunk leaves release 0.1.0 with no plan item.\n")
|
||||
self.commit("Mark 0.1.0 renamed", {"todo.md": todo(*rows) + "\n## Renamed\n\n- 0.1.0 renamed to 0.2.0\n"})
|
||||
self.assertEqual(self.run_tool("needs-scoring-run").stdout, "No scoring run due.\n")
|
||||
|
||||
def test_counts_work_landed_from_the_changelogs_unreleased_entries_where_it_has_that_section(self):
|
||||
self.git("tag", "v0.0.1")
|
||||
self.commit("Commit after the tag", {"CHANGELOG.md": "# Changelog\n\n## Unreleased\n\n## 0.0.1\n"})
|
||||
self.git("push", "-q", "origin", "HEAD:main")
|
||||
rows = ("| 1 | 0.2.0 | | **Do it.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |", "| 2 | 0.2.0 | | **Then this.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |", "| 3 | 0.2.0 | | **And this.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |")
|
||||
self.commit("Move 0.1.0's item to 0.2.0 and log a change", {"todo.md": todo(*rows), "CHANGELOG.md": "# Changelog\n\n## Unreleased\n\n- The chunk's own change.\n\n## 0.0.1\n"})
|
||||
self.assertEqual(self.run_tool("needs-scoring-run").stdout, "No scoring run due.\n")
|
||||
self.git("reset", "-q", "--hard", "HEAD~1")
|
||||
self.commit("Log a change", {"CHANGELOG.md": "# Changelog\n\n## Unreleased\n\n- Did a thing.\n\n## 0.0.1\n"})
|
||||
self.git("push", "-q", "origin", "HEAD:main")
|
||||
self.commit("Move 0.1.0's item to 0.2.0", {"todo.md": todo(*rows)})
|
||||
self.assertEqual(self.run_tool("needs-scoring-run").stdout, "Scoring run due: the chunk leaves release 0.1.0 with no plan item.\n")
|
||||
|
||||
def test_refuses_where_the_default_branchs_unreleased_changes_cannot_be_read(self):
|
||||
self.addCleanup(os.chdir, os.getcwd())
|
||||
os.chdir(self.checkout)
|
||||
self.assertIsInstance(plan_reasons("no-such-ref", []), Failure)
|
||||
|
||||
def test_refuses_a_checkout_plan_whose_renamed_section_does_not_parse(self):
|
||||
self.commit("Break the mark", {"todo.md": todo("| 1 | 0.2.0 | | **Do it.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |") + "\n## Renamed\n\nsoon\n"})
|
||||
broken = self.run_tool("needs-scoring-run")
|
||||
self.assertEqual(broken.returncode, 1)
|
||||
self.assertIn("## Renamed", broken.stderr)
|
||||
|
||||
def test_reads_a_default_branch_plan_without_a_table_as_empty_and_refuses_a_checkout_without_one(self):
|
||||
self.git("switch", "-q", "-c", "reshape", "main")
|
||||
self.commit("Plan as a list", {"todo.md": "# todo\n\n- [ ] Do it.\n"})
|
||||
@@ -299,6 +471,13 @@ class LarvReviewTool(unittest.TestCase):
|
||||
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_refuses_the_other_seats_lines_once_the_first_two_agree_overall(self):
|
||||
lines = f"PR #2 at {self.start}, against {self.start}\n\n" + "\n".join(f"{seat}: {said('worse')}\n\n- Overall: `bin/a.py:3` `f`: hard\n" for seat in ("Mid A", "Inherited architect", "Maintainability senior", "Junior A"))
|
||||
ran = self.run_tool("record-ruling", self.seats_file(lines))
|
||||
self.assertEqual((ran.returncode, ran.stdout), (1, ""))
|
||||
self.assertIn("both count as worse overall, which settles the ruling; drop the other seats' lines", ran.stderr)
|
||||
self.assertFalse((self.checkout / "docs" / "comprehension-history.md").exists())
|
||||
|
||||
def test_records_a_ruling_whose_dimension_fell_and_takes_no_scores_file(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")
|
||||
@@ -319,6 +498,7 @@ class LarvReviewTool(unittest.TestCase):
|
||||
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)
|
||||
self.plan()
|
||||
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.\n", ran.stdout)
|
||||
@@ -328,6 +508,54 @@ class LarvReviewTool(unittest.TestCase):
|
||||
self.assertIn("Inherited architect, would restructure first:", text)
|
||||
self.assertEqual(entries(text)[0].scored_places, [Place("bin/a.py", "f")] * 4)
|
||||
|
||||
def plan(self, readme="# P\n\n## Goals\n\n1. **Achieve:** A.\n", bar="0.1"):
|
||||
"""Commit and push the README.md and a todo.md whose item 1, alone in release 0.1.0, moves code health, each item scored as before any scoring run."""
|
||||
header = "| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|---|---|\n"
|
||||
# Before any scoring run code health weighs four times its weight at an overall of 7.0: 4 / 1.97 against goal 1's 0.97 / 1.97.
|
||||
rows = "| 1 | 0.1.0 | | | **Read easier.** | 1 | 1 | 1 | 1 | 1 | code health by 1 | 101.5 |\n| 2 | 0.2.0 | | | **Do A.** | 1 | 1 | 1 | 1 | 1 | 1 by 3 | 73.9 |\n"
|
||||
self.commit("Plan", {"README.md": readme, "todo.md": f"# todo\n\n## Scoring\n\n`Score = 100 * V / 2**S`\n\n`Bar = {bar}`\n\n`Next ID = 3`\n\n## Items\n\n" + header + rows})
|
||||
self.git("push", "-q", "origin", "HEAD:main")
|
||||
|
||||
def record_sevens(self):
|
||||
"""Run record-scoring for item 1 on a scores file in which every seat scores 7 throughout."""
|
||||
line = "Navigation 7, Locality 7, Shape 7, Self-sufficiency 7, Overall 7"
|
||||
seats = "".join(f"\n{seat}: {line}\n" for seat in ("Junior A", "Mid A", "Maintainability senior", "Inherited architect"))
|
||||
return self.run_tool("record-scoring", self.seats_file(f"PR #2 at {self.start}\n" + seats), "1")
|
||||
|
||||
def test_reports_a_plan_it_cannot_read_yet_keeps_the_run(self):
|
||||
# This checkout has no README.md beside its todo.md.
|
||||
ran = self.record_sevens()
|
||||
self.assertEqual(ran.returncode, 1)
|
||||
self.assertIn(f"recorded the run, but rank_todo.py cannot rank {self.checkout / 'todo.md'}: {self.checkout / 'README.md'}: not found", ran.stderr)
|
||||
self.assertIn("not record-scoring again", ran.stderr)
|
||||
self.assertEqual(len(entries((self.checkout / "docs" / "comprehension-history.md").read_text())), 1)
|
||||
|
||||
def test_reports_a_plan_it_reads_but_cannot_rank_yet_keeps_the_run(self):
|
||||
self.plan(readme="# P\n\n## Goals\n\n**Void:** code health, since it is a probe.\n\n1. **Achieve:** A.\n")
|
||||
ran = self.record_sevens()
|
||||
self.assertEqual(ran.returncode, 1)
|
||||
self.assertIn(f"recorded the run, but rank_todo.py cannot rank {self.checkout / 'todo.md'}: item 1 names code health, which README.md voids", ran.stderr)
|
||||
self.assertIn("not record-scoring again", ran.stderr)
|
||||
self.assertEqual(len(entries((self.checkout / "docs" / "comprehension-history.md").read_text())), 1)
|
||||
|
||||
def test_reranks_todo_md_by_the_overall_it_records(self):
|
||||
self.plan()
|
||||
ran = self.record_sevens()
|
||||
self.assertEqual(ran.returncode, 0, ran.stderr)
|
||||
self.assertIn("| code health by 1 | 25.4 |", (self.checkout / "todo.md").read_text())
|
||||
|
||||
def test_fails_once_its_re_rank_leaves_an_item_under_the_bar_yet_keeps_the_run(self):
|
||||
self.plan(bar="30")
|
||||
ran = self.record_sevens()
|
||||
self.assertEqual(ran.returncode, 1)
|
||||
todo = self.checkout / "todo.md"
|
||||
# At an overall of 7.0 item 1 falls from 101.5 to 25.4.
|
||||
self.assertIn(f"{todo}: item 1 scores 25.4, under the bar 30; delete it, or mark it with a reason the bar does not apply\n", ran.stderr)
|
||||
self.assertIn("recorded the run", ran.stderr)
|
||||
self.assertIn("not record-scoring again", ran.stderr)
|
||||
self.assertIn("| code health by 1 | 25.4 |", todo.read_text())
|
||||
self.assertEqual(len(entries((self.checkout / "docs" / "comprehension-history.md").read_text())), 1)
|
||||
|
||||
def test_prints_the_places_seats_found_hard_since_the_newest_scoring_run(self):
|
||||
self.assertEqual(self.run_tool("places").stdout, "Seats found no places hard.\n")
|
||||
self.commit("Record a scoring run", {"docs/comprehension-history.md": appended("", SCORING + "\nJunior A, hardest first:\n\n- `bin/b.py:4` `h`: long\n")})
|
||||
@@ -337,6 +565,13 @@ class LarvReviewTool(unittest.TestCase):
|
||||
outside = subprocess.run([sys.executable, str(TOOL), "places"], capture_output=True, cwd=self.checkout.parent, env=self.env, text=True)
|
||||
self.assertEqual((outside.returncode, outside.stdout), (1, ""))
|
||||
|
||||
def test_prints_how_often_seats_agree_in_rulings_and_across_runs_on_one_commit(self):
|
||||
history = "\n".join([scored("2026-10-01T00:00:00Z", "PR #1", "aaaaaaa", "7", "7"), scored("2026-10-02T00:00:00Z", "PR #1 rerun", "aaaaaaa", "7.5", "7"), ruled("2026-10-03T00:00:00Z", "PR #2", "same", "same")])
|
||||
self.commit("Record the checks", {"docs/comprehension-history.md": appended("", history)})
|
||||
ran = self.run_tool("agreement")
|
||||
self.assertEqual((ran.returncode, ran.stdout), (0, "Unchecked: Mid A and Inherited architect voted alike overall in 1 of 1 paired rulings, and their overall scores moved alike between two scoring runs on one commit in 0 of 1 pairs. A verdict needs 10 commits each scored twice and one paired ruling.\n"), ran.stderr)
|
||||
self.assertIn("unknown arguments", self.run_tool("agreement", "x").stderr)
|
||||
|
||||
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)
|
||||
@@ -352,6 +587,34 @@ class LarvReviewTool(unittest.TestCase):
|
||||
self.git("remote", "set-head", "origin", "--delete")
|
||||
self.assertEqual(self.run_tool("needs-scoring-run", "2").stdout, "No scoring run due.\n")
|
||||
|
||||
def test_makes_and_prints_the_worktrees_review_folder_from_anywhere_in_it(self):
|
||||
reports = self.checkout.parent / ".local" / "state" / "larv-review"
|
||||
(self.checkout / "sub").mkdir()
|
||||
ran = subprocess.run([sys.executable, str(TOOL), "review-folder"], capture_output=True, cwd=self.checkout / "sub", env=self.env, text=True)
|
||||
self.assertEqual((ran.returncode, ran.stdout), (0, f"{reports}/proj\n"), ran.stderr)
|
||||
self.assertTrue((reports / "proj").is_dir())
|
||||
|
||||
def test_leaves_the_reports_folder_readable_by_the_user_alone_where_it_was_not(self):
|
||||
reports = self.checkout.parent / ".local" / "state" / "larv-review"
|
||||
reports.mkdir(parents=True, mode=0o755)
|
||||
self.assertEqual(self.run_tool("review-folder").returncode, 0)
|
||||
self.assertEqual(reports.stat().st_mode & 0o777, 0o700)
|
||||
|
||||
def test_fails_where_it_cannot_make_the_review_folder(self):
|
||||
(self.checkout.parent / ".local" / "state").mkdir(parents=True)
|
||||
(self.checkout.parent / ".local" / "state" / "larv-review").write_text("")
|
||||
ran = self.run_tool("review-folder")
|
||||
self.assertEqual(ran.returncode, 1)
|
||||
self.assertIn("could not make the review folder", ran.stderr)
|
||||
|
||||
def test_review_folder_fails_outside_a_checkout(self):
|
||||
ran = subprocess.run([sys.executable, str(TOOL), "review-folder"], capture_output=True, cwd=self.checkout.parent, env=self.env, text=True)
|
||||
self.assertEqual(ran.returncode, 1)
|
||||
self.assertNotIn("Traceback", ran.stderr)
|
||||
|
||||
def test_review_folder_takes_no_arguments(self):
|
||||
self.assertIn("unknown arguments", self.run_tool("review-folder", "x").stderr)
|
||||
|
||||
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"))
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import dataclasses
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
@@ -11,17 +12,42 @@ from claude_code.trust import trust
|
||||
from loop_claude.project.checkout import worktrees
|
||||
|
||||
ANSWER_QUESTION = "answer the question above"
|
||||
# TALK and ASK_ANSWER were picked on 2026-10-17 by a bench of three readers seated as the README's audience, as ~/.claude/CLAUDE.md → "Working loop" → "Bench a syntax with the people who write it." has it.
|
||||
TALK = "/talk"
|
||||
ASK_ANSWER = f"Answer ({TALK} opens claude, Enter stops the loop): "
|
||||
|
||||
|
||||
def interrupt(root: str, session_id: uuid.UUID, worker: Rung, path: str, question: str, paths: Paths, effects: Effects) -> Stop | None:
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Talk:
|
||||
"""The human answers in the worker's claude session, which talk opens."""
|
||||
|
||||
|
||||
def put_question(question: str, answer_here: bool, effects: Effects) -> str | Talk | Stop:
|
||||
"""Prints question for the human. Where answer_here, returns the line they type at loop-claude's terminal, stripped, or Talk where they type TALK; else Talk at once. A Stop where loop-claude is off a terminal, or they type nothing, or the input ends."""
|
||||
print(f"\n{question}", file=sys.stderr)
|
||||
if stop := needs_terminal(ANSWER_QUESTION, effects.on_terminal()):
|
||||
return stop
|
||||
# Keys typed while the worker ran wait on the terminal, and would answer a question no one has read, here or in claude's session, which reads them too. Of a pasted answer, input takes the first line; the rest wait, and the next question drops them. A longer answer goes through TALK.
|
||||
effects.discard_typed()
|
||||
if not answer_here:
|
||||
return Talk()
|
||||
try:
|
||||
answer = effects.input(ASK_ANSWER).strip()
|
||||
except EOFError:
|
||||
print(file=sys.stderr)
|
||||
return needs_human(ANSWER_QUESTION, "the input ended")
|
||||
if not answer:
|
||||
return needs_human(ANSWER_QUESTION, "nothing was typed")
|
||||
return Talk() if answer == TALK else answer
|
||||
|
||||
|
||||
def talk(root: str, session_id: uuid.UUID, worker: Rung, path: str, paths: Paths, env: dict[str, str], effects: Effects) -> Stop | None:
|
||||
"""Resumes the worker's session in claude on the terminal; the human must type something there."""
|
||||
entries = read_transcript(path)
|
||||
if isinstance(entries, Failure):
|
||||
return Stop(1, entries.reason)
|
||||
before = human_turns(entries)
|
||||
if unstarted := hand_over(worker, ["--resume", str(session_id)], root, paths, effects):
|
||||
if unstarted := hand_over(worker, ["--resume", str(session_id)], root, paths, env, effects):
|
||||
return Stop(1, f"could not start claude for the interrupt: {unstarted.reason}")
|
||||
entries = read_transcript(path)
|
||||
if isinstance(entries, Failure):
|
||||
@@ -29,11 +55,11 @@ def interrupt(root: str, session_id: uuid.UUID, worker: Rung, path: str, questio
|
||||
return None if human_turns(entries) > before else needs_human(ANSWER_QUESTION, "the interrupt ended with nothing typed")
|
||||
|
||||
|
||||
def hand_over(rung: Rung, args: list[str], root: str, paths: Paths, effects: Effects) -> Failure | None:
|
||||
"""Runs claude on the terminal in root on rung, the checkout and each of its worktrees first marked trusted; the failure is why claude could not start."""
|
||||
def hand_over(rung: Rung, args: list[str], root: str, paths: Paths, env: dict[str, str], effects: Effects) -> Failure | None:
|
||||
"""Marks the checkout and each of its worktrees trusted, then runs claude on the terminal in root, on rung, with env added to its environment; the failure is why claude could not start."""
|
||||
trust(paths.claude_json, worktrees(root, effects))
|
||||
try:
|
||||
effects.claude_on_terminal([*rung.flags(), "--permission-mode", "bypassPermissions", *args], root)
|
||||
effects.claude_on_terminal([*rung.flags(), "--permission-mode", "bypassPermissions", *args], root, env)
|
||||
except OSError as failure:
|
||||
return Failure(str(failure.strerror))
|
||||
return None
|
||||
|
||||
@@ -3,22 +3,25 @@ import json
|
||||
import re
|
||||
import typing
|
||||
|
||||
from loop_claude.cycle.prompts import ANSWER_DESTINATIONS, ANSWERS_RECORDED, either
|
||||
from loop_claude.cycle.prompts import ANSWER_DESTINATIONS, ANSWERS_RECORDED, typed_answer
|
||||
from claude_code.reply import claude_reply, Limited
|
||||
from loop_claude.effects import Effects
|
||||
from loop_claude import escalation_mark
|
||||
from failure import Failure
|
||||
from loop_claude.project.records import HUMAN_RULE_NAMES
|
||||
from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict
|
||||
from todo_table import LEVELS
|
||||
from model_routing.route import on_its_scale
|
||||
from claude_code.transcript import plain, verbatim
|
||||
from loop_claude.cycle.retry import retried
|
||||
from model_routing.ladder import Rung
|
||||
from loop_claude.stop import Stop
|
||||
from claude_code.entries import structured_output
|
||||
from todo_table import TOP_SCORE
|
||||
|
||||
# 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 = (
|
||||
INTERRUPT_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, and neither "
|
||||
"- the worker asks the human anything, seeks approval, or says a decision is the human's, and neither "
|
||||
"README.md nor the records settle the matter\n"
|
||||
"- 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 "
|
||||
@@ -28,44 +31,55 @@ JUDGE_RULES = (
|
||||
"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, "
|
||||
"between - neither rules the rejected one out - and the choice materially changes the deliverable\n\n"
|
||||
"interrupt=false otherwise. Bookkeeping the worker settled silently - what to document, wording, "
|
||||
"where a note goes - is not on its own a reason to interrupt. A run that ends asking loop-claude for a higher "
|
||||
"rung is no reason to interrupt either; one that asks the human's yes to a higher rung is. 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. A [loop] line is what loop-claude told "
|
||||
"the agent, such as an answer quoted from README.md or the records.\n\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\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 "
|
||||
"rung is no reason to interrupt either; one that asks the human's yes to a higher rung is.\n\n"
|
||||
"The human may have replied inside the transcript, on a [human] line: judge only what "
|
||||
"is still open, never a question they already answered there.\n\n"
|
||||
"Where the worker asked or flagged something itself, the question is that one, in the worker's own "
|
||||
"wording; never construct another from facts it stated."
|
||||
)
|
||||
QUOTE_RULES = (
|
||||
"Where README.md or the records answer the worker's own question and no [loop] line has "
|
||||
"quoted that answer yet, set interrupt=false and quote the passage that answers it; the worker is "
|
||||
"then given that passage in place of the human's reply. An interrupt outranks a quoted answer, and either "
|
||||
"outranks finished.\n\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 "
|
||||
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 "
|
||||
"outranks finished."
|
||||
)
|
||||
FINISHED_RULES = (
|
||||
"The chunk is the piece of work the worker is on, shipped as one pull request.\n\n"
|
||||
"finished=true when the chunk is complete: merged, or nothing remains that the worker could do on "
|
||||
f"its own. Even then, it is finished only once {ANSWERS_RECORDED}.\n\n"
|
||||
"An answer counts as recorded where README.md or the records above already hold it, the human's rules "
|
||||
"(~/.claude/CLAUDE.md, ~/.claude/rules/, ~/.claude/skills/larv-review/standards/) included. "
|
||||
f"It also counts where the transcript shows the worker writing it into {ANSWER_DESTINATIONS}, "
|
||||
"but not into one of the human's rules.\n\n"
|
||||
"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."
|
||||
)
|
||||
JUDGE_RULES = "\n\n".join((INTERRUPT_RULES, QUOTE_RULES, FINISHED_RULES))
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
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."})
|
||||
answer: str = dataclasses.field(metadata={"description": "With interrupt false, the passage of README.md or the records that answers the worker's question, quoted verbatim, without elisions. Empty otherwise."})
|
||||
# Routes the next cycle's worker. Counting the item the chunk was routed on is harmless: loop-claude never steps the worker down.
|
||||
bundled: int = dataclasses.field(metadata={"description": "The highest R + C the agent states for a todo.md item it took into this chunk; 0 when it states none."})
|
||||
# Routes the next cycle's worker one rung up: docs/decisions.md → `routing: a worker whose run ends asking for a higher rung`.
|
||||
escalation: str = dataclasses.field(metadata={"description": "Empty unless the chunk is unfinished and the agent's run ends asking loop-claude for a higher rung, citing an escalation trigger. Then: a verbatim quote, without elisions, of an earlier transcript passage showing the trigger fired after any earlier such request, such as a review round's commit title or the agent's report of the finding or failing test. Never the request itself."})
|
||||
evidence: str = dataclasses.field(metadata={"description": "A verbatim quote of the one transcript passage the verdict rests on, without elisions: what triggers the interrupt; for a quoted answer, the agent's question; else what shows the chunk finished or the work remaining."})
|
||||
highest_likelihood_taken_in: int = dataclasses.field(metadata={"description": "The highest L the worker states for a todo.md item it took into this chunk; 0 when it states none."})
|
||||
# Routes the next cycle's judge and reviewers, as highest_likelihood_taken_in routes the worker.
|
||||
highest_escape_and_impact_taken_in: int = dataclasses.field(metadata={"description": "The highest E + I the worker states for a todo.md item it took into this chunk; 0 when it states none."})
|
||||
# Routes the worker one rung up, as the judge interrupts or quotes an answer, or on the next cycle: loop_claude/escalation_mark.py.
|
||||
escalation: str = dataclasses.field(metadata={"description": "Empty unless the chunk is unfinished, interrupt is true or answer quotes a passage, and the worker's run ends asking loop-claude for a higher rung, citing an escalation trigger. Then: a verbatim quote, without elisions, of the transcript passage where the trigger fired, such as a review round's commit title or the worker's report of the finding or failing test. " + escalation_mark.QUOTE_AFTER_STEP + " Never a later mention of the trigger, and never the request itself."})
|
||||
evidence: str = dataclasses.field(metadata={"description": "A verbatim quote of the one transcript passage the verdict rests on, without elisions: what triggers the interrupt; for a quoted answer, the worker's question; else what shows the chunk finished or the work remaining."})
|
||||
finished: bool = dataclasses.field(metadata={"description": "Whether the chunk is finished."})
|
||||
interrupt: bool = dataclasses.field(metadata={"description": "Whether the human must now be interrupted."})
|
||||
question: str = dataclasses.field(metadata={"description": "With interrupt true, the single question to put to the human. With a quoted answer, the agent's question that the answer field answers. Empty otherwise."})
|
||||
question: str = dataclasses.field(metadata={"description": "With interrupt true, the single question to put to the human. With a quoted answer, the worker's question that the answer field answers. Empty otherwise."})
|
||||
# True opens claude's session at once, in place of the one-line answer (run.ask). The judge decides it, since loop-claude computes the plan's standing (chunk_pick.chunk_item) only when it routes a chunk on the ladder afresh: it would miss a release ready to cut in a resumed chunk or off the ladder. A wrong ruling costs the human one typed /talk, or answering in claude, which stops the loop if they leave it with nothing typed.
|
||||
release_ready: bool = dataclasses.field(metadata={"description": "With interrupt true, whether the question is about a release ready to cut, which only the human may publish. False otherwise."})
|
||||
|
||||
|
||||
REPLY_TYPES = typing.get_type_hints(Reply)
|
||||
JSON_TYPES = {bool: "boolean", int: "integer", str: "string"}
|
||||
HIGHEST_R_PLUS_C = 2 * TOP_SCORE
|
||||
HIGHEST_L = LEVELS["L"]
|
||||
JUDGE_SCHEMA = {
|
||||
"properties": {field.name: {**field.metadata, "type": JSON_TYPES[REPLY_TYPES[field.name]]} for field in dataclasses.fields(Reply)},
|
||||
"required": list(REPLY_TYPES),
|
||||
@@ -74,34 +88,19 @@ JUDGE_SCHEMA = {
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Interrupt:
|
||||
evidence: str
|
||||
question: str
|
||||
class Rejected(Failure):
|
||||
"""A judge reply loop-claude rejected: reason says why, reply holds the reply as json."""
|
||||
reply: 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
|
||||
# The bundled R + C the judge saw, 0 for none.
|
||||
bundled: int = 0
|
||||
# The judge's quote showing that the worker's cited escalation trigger fired; empty for none.
|
||||
escalation: str = ""
|
||||
|
||||
|
||||
Verdict = Interrupt | QuotedAnswer | Finished | Unfinished
|
||||
class Grounds(typing.NamedTuple):
|
||||
"""What run_judge checks the judge's quotes against, word for word, since stitched fragments can say what their source does not."""
|
||||
# The transcript as the judge saw it. The evidence must quote it, its fragments in order: a misquote is Rejected, which judge retries.
|
||||
shown: str
|
||||
# escalation_mark.since_step's lines. An escalation must quote both these and shown: a misquote drops the escalation, as escalation_mark.checked says.
|
||||
since_step: str
|
||||
# README.md's premises and the records. A quoted answer must quote them: a misquote puts the question to the human.
|
||||
quotable: str
|
||||
|
||||
|
||||
def verdict_from(output: object) -> Verdict | Failure:
|
||||
@@ -111,29 +110,31 @@ def verdict_from(output: object) -> Verdict | Failure:
|
||||
# type(), not isinstance(): JSON true is no integer.
|
||||
if type(output.get(name)) is not kind:
|
||||
return Failure(f"the judge's reply has no {name} of type {JSON_TYPES[kind]}")
|
||||
# An L taken in off its scale counts as none: holding the rung is safe, and three failures would stop an unattended loop.
|
||||
likelihood = output["highest_likelihood_taken_in"] if 0 <= output["highest_likelihood_taken_in"] <= HIGHEST_L else 0
|
||||
if output["interrupt"]:
|
||||
if not output["question"].strip():
|
||||
return Failure("the judge interrupted without a question")
|
||||
return Interrupt(output["evidence"], output["question"])
|
||||
return Interrupt(output["evidence"], output["question"], escalation=output["escalation"], highest_likelihood_taken_in=likelihood, release_ready=output["release_ready"])
|
||||
if output["answer"].strip():
|
||||
if not output["question"].strip():
|
||||
return Failure("the judge quoted an answer without a question")
|
||||
return QuotedAnswer(output["evidence"], output["question"], output["answer"])
|
||||
return QuotedAnswer(output["evidence"], output["question"], output["answer"], escalation=output["escalation"], highest_likelihood_taken_in=likelihood)
|
||||
if output["finished"]:
|
||||
return Finished(output["evidence"])
|
||||
if not 0 <= output["bundled"] <= HIGHEST_R_PLUS_C:
|
||||
return Failure(f"the judge's bundled R + C {output['bundled']} is not from 0 to {HIGHEST_R_PLUS_C}")
|
||||
return Unfinished(output["evidence"], output["bundled"], output["escalation"])
|
||||
escape_and_impact = output["highest_escape_and_impact_taken_in"] if on_its_scale(output["highest_escape_and_impact_taken_in"]) else 0
|
||||
return Unfinished(output["evidence"], escalation=output["escalation"], highest_likelihood_taken_in=likelihood, highest_escape_and_impact_taken_in=escape_and_impact)
|
||||
|
||||
|
||||
def judge(root: str, task: str, premises: str, records: str, rendered_transcript: str, rung: Rung, effects: Effects) -> Verdict | Stop:
|
||||
return retried("judge", lambda: judge_once(root, task, premises, records, rendered_transcript, rung, effects), effects)
|
||||
def judge(root: str, task: str, premises: str, records: str, entries: list[dict], escalated_at: int, rung: Rung, effects: Effects, keep: typing.Callable[[Rejected], Stop | None]) -> Verdict | Stop:
|
||||
return retried("judge", lambda: judge_once(root, task, premises, records, entries, escalated_at, rung, effects), effects, lambda failure: keep(failure) if isinstance(failure, Rejected) else None)
|
||||
|
||||
|
||||
def judge_once(root: str, task: str, premises: str, records: str, rendered_transcript: str, rung: Rung, effects: Effects) -> Verdict | Failure | Limited:
|
||||
"""One judge run, as judge retries it; judge-replay replays it."""
|
||||
prompt, shown = judge_prompt(task, premises, records, rendered_transcript)
|
||||
return run_judge(root, judge_args(rung), prompt, shown, f"{premises}\n\n{records}", effects)
|
||||
def judge_once(root: str, task: str, premises: str, records: str, entries: list[dict], escalated_at: int, rung: Rung, effects: Effects) -> Verdict | Failure | Limited:
|
||||
"""One judge run on the transcript's entries, as judge retries it; judge-replay replays it. escalated_at is the route's mark, as loop_claude/escalation_mark.py says."""
|
||||
prompt, grounds = judge_prompt(task, premises, records, entries, escalated_at)
|
||||
verdict = run_judge(root, judge_args(rung), prompt, grounds, effects)
|
||||
return verdict if isinstance(verdict, Failure | Limited) else escalation_mark.stamped(verdict, len(entries))
|
||||
|
||||
|
||||
def judge_args(rung: Rung) -> list[str]:
|
||||
@@ -146,40 +147,40 @@ def judge_args(rung: Rung) -> list[str]:
|
||||
]
|
||||
|
||||
|
||||
def run_judge(root: str, args: list[str], prompt: str, shown: str, quotable: str, effects: Effects) -> Verdict | Failure | Limited:
|
||||
"""One judge run, its three quotes each checked against what they quote:
|
||||
- evidence, against shown, its fragments in order: a misquote is a Failure, which judge retries;
|
||||
- a quoted answer, against quotable, word for word: a misquote puts the question to the human;
|
||||
- an escalation, against shown, word for word: a misquote drops it, so the worker's rung holds.
|
||||
A misquoted answer or escalation is no Failure, which would otherwise exit an unattended loop. Neither may be elided, since stitched fragments can say what the records or the transcript do not.
|
||||
"""
|
||||
def run_judge(root: str, args: list[str], prompt: str, grounds: Grounds, effects: Effects) -> Verdict | Failure | Limited:
|
||||
"""One judge run, each quote in its verdict checked against grounds as Grounds says."""
|
||||
reply = claude_reply(effects.claude, args, root, prompt, "the judge")
|
||||
if isinstance(reply, Failure | Limited):
|
||||
return reply
|
||||
verdict = verdict_from(structured_output(reply))
|
||||
replied = json.dumps(reply, ensure_ascii=False)
|
||||
if isinstance(verdict, Failure):
|
||||
return Failure(f"{verdict.reason}; it replied: {json.dumps(reply, ensure_ascii=False)}")
|
||||
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 ""))
|
||||
if isinstance(verdict, QuotedAnswer) and not verbatim(verdict.answer, quotable):
|
||||
return Interrupt(verdict.evidence, verdict.question)
|
||||
if isinstance(verdict, Unfinished) and verdict.escalation and not verbatim(verdict.escalation, shown):
|
||||
return dataclasses.replace(verdict, escalation="")
|
||||
return verdict
|
||||
return Rejected(verdict.reason, replied)
|
||||
if not grounded(verdict.evidence, grounds.shown):
|
||||
return Rejected(f"the judge quoted {verdict.evidence!r}, which is not in the transcript" + (f", for the question: {verdict.question}" if isinstance(verdict, Interrupt | QuotedAnswer) else ""), replied)
|
||||
return quotes_checked(verdict, grounds)
|
||||
|
||||
|
||||
def 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."""
|
||||
def quotes_checked(verdict: Verdict, grounds: Grounds) -> Verdict:
|
||||
"""The verdict with its quoted answer and its escalation checked. A quoted answer that neither README.md's premises nor the records hold goes to the human as an interrupt, which keeps the escalation the answer carried. Neither misquote is a Failure, which would otherwise exit an unattended loop."""
|
||||
if isinstance(verdict, QuotedAnswer) and not verbatim(verdict.answer, grounds.quotable):
|
||||
verdict = Interrupt(verdict.evidence, verdict.question, escalation=verdict.escalation, highest_likelihood_taken_in=verdict.highest_likelihood_taken_in)
|
||||
return escalation_mark.checked(verdict, since=grounds.since_step, shown=grounds.shown)
|
||||
|
||||
|
||||
def judge_prompt(task: str, premises: str, records: str, entries: list[dict], escalated_at: int) -> tuple[str, Grounds]:
|
||||
"""The prompt, and what the judge's quotes are checked against."""
|
||||
transcript = escalation_mark.transcript(entries, escalated_at, typed_answer)
|
||||
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"
|
||||
"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"
|
||||
f"The task the worker was given:\n{task}\n\n"
|
||||
"What the worker 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
|
||||
shown = transcript[max(0, len(transcript) - room):]
|
||||
return f"{head}{shown}\n\n{JUDGE_RULES}", Grounds(shown, escalation_mark.since_step(entries, escalated_at), f"{premises}\n\n{records}")
|
||||
|
||||
|
||||
def grounded(evidence: str, rendered_transcript: str) -> bool:
|
||||
@@ -193,13 +194,3 @@ def grounded(evidence: str, rendered_transcript: str) -> bool:
|
||||
return False
|
||||
at = found + len(fragment)
|
||||
return fragments != []
|
||||
|
||||
|
||||
def verbatim(quote: str, text: str) -> bool:
|
||||
quoted = plain(quote)
|
||||
return quoted != "" and quoted in plain(text)
|
||||
|
||||
|
||||
def plain(text: str) -> str:
|
||||
# The judge drops markdown emphasis and reflows whitespace when it quotes.
|
||||
return " ".join(text.replace("*", "").replace("_", "").split())
|
||||
|
||||
@@ -1,79 +1,195 @@
|
||||
from model_routing.ladder import climbed, highest, LADDER, Rung
|
||||
"""What loop-claude says to the worker each cycle. model_routing.review_choice chooses where the reviews run. review_launches and reruns put that choice into sentences, and escalation says where escalated subagents run; rung_sentences returns the sentences of all three. In a chunk's first prompt, routed_by places them after its routing sentences where an item routed the chunk, and fresh places them alone otherwise. rungs_held repeats them at the end of a prompt after a step-up or an unfinished verdict."""
|
||||
from model_routing.review_choice import chosen, ReviewChoice
|
||||
from model_routing.ladder import climbed, LADDER, position, Rung
|
||||
from model_routing.route import ESCALATION_MARKER, Route
|
||||
from loop_claude.routing import escalation_rungs
|
||||
from loop_claude.project.records import HUMAN_RULE_NAMES, RECORD_FILES
|
||||
from markdown_text import quoted
|
||||
|
||||
def either(names: tuple[str, ...]) -> str:
|
||||
"""The names as `a, b or c`."""
|
||||
return f"{', '.join(names[:-1])} or {names[-1]}"
|
||||
|
||||
from markdown_text import listed, quoted
|
||||
from review_passes import REVIEWERS
|
||||
from claude_code.transcript import Typed
|
||||
|
||||
# Where the judge may quote an answer from, named as the human and the worker see them; of README.md the judge sees only the premises.
|
||||
QUOTE_SOURCES = either(("README.md's Goals and Audience", *RECORD_FILES, *HUMAN_RULE_NAMES))
|
||||
QUOTE_SOURCES = listed(("README.md's Goals and Audience", *RECORD_FILES, *HUMAN_RULE_NAMES), "or")
|
||||
# Where the worker may write an answer the human typed, so it counts as recorded.
|
||||
ANSWER_DESTINATIONS = "README.md's Goals or Audience, " + ", ".join(RECORD_FILES) + ", todo.md or a comment"
|
||||
ANSWERS_RECORDED = f"every answer the human typed in it that a later chunk could need is recorded in {ANSWER_DESTINATIONS} at the one place it governs"
|
||||
# How review_launches names the reviews: "each reviewer" covers every pass with an agent that no replay lowered.
|
||||
EACH_REVIEWER = "each reviewer"
|
||||
EACH_SEAT = "each comprehension seat"
|
||||
THE_SECURITY_PASS = "the security pass's subagent"
|
||||
|
||||
|
||||
def fresh(task: str, premises: str, route: Route, anchor: Rung | None) -> str:
|
||||
escalated = f"{escalation(route, anchor)}{reruns(route, anchor)}".lstrip()
|
||||
routed = f"{routed_by(route, anchor)}\n\n" if route.item else (f"{escalated}\n\n" if escalated else "")
|
||||
return f"{task}\n\nContinue any open draft PR or worktree for the chunk before creating a new one.\n\n{routed}The chunk's todo.md items, or else the task above, set its scope. The goals below choose between ways to deliver that scope, and never widen it.\n\nFrom README.md:\n{premises}"
|
||||
AFTER_CODE_HEALTH = 'which rank after code health (~/.claude/CLAUDE.md → "Shared goal") unless README.md voids it'
|
||||
|
||||
|
||||
def routed_by(route: Route, anchor: Rung | None) -> str:
|
||||
return f"loop-claude runs you on {route.rung}, routed by item {route.item}'s R + C of {route.risk_and_complexity}. Name each todo.md item this chunk takes, with its R + C, whether or not it is item {route.item}.{off_the_projects_rung(route, anchor)}{escalation(route, anchor)}{reruns(route, anchor)}"
|
||||
def fresh(task: str, premises: str, route: Route, project: Rung | None, facts: str) -> str:
|
||||
"""A chunk's first prompt; facts is preflight_facts' or preflight_failed's text."""
|
||||
routed = f"{routed_by(route, project)} {recount(route)}" if route.item else " ".join(rung_sentences(route, project))
|
||||
opening = f"{routed}\n\n" if routed else ""
|
||||
return f"{task}\n\nContinue any open draft PR or worktree for the chunk before creating a new one.\n\n{opening}{facts}\n\nThe chunk's todo.md items, or else the task above, set its scope. The goals below, {AFTER_CODE_HEALTH}, choose between ways to deliver that scope, and never widen it.\n\nFrom README.md:\n{premises}"
|
||||
|
||||
|
||||
def off_the_projects_rung(route: Route, anchor: Rung | None) -> str:
|
||||
"""Which subagents to launch on the project's rung, anchor, and below it which on the --plan rung; empty while the worker runs on anchor, as every chunk no item routed does until it steps up."""
|
||||
if anchor is None or route.rung == anchor:
|
||||
return ""
|
||||
# Below the project's rung, the reviewers stay on it to hold quality; above it, the seats score every chunk on one rung, and the security pass spends no more than the project chose.
|
||||
below = highest(route.rung, anchor) == anchor
|
||||
launched = "each reviewer, each comprehension seat and the security pass's subagent" if below else "each comprehension seat and the security pass's subagent"
|
||||
planning = f" Launch each subagent that files or scores todo.md items on the rung `~/.claude/bin/subagent-rung --plan {anchor.model} <R+C>` prints." if below else ""
|
||||
return f" Your rung is {'below' if below else 'above'} the project's, {anchor}: launch {launched} with the Agent tool set to {anchor.agent_args()}. Run a full scan only from such a subagent, since the scan's agents run on the model that starts them.{planning}"
|
||||
def routed_by(route: Route, project: Rung | None) -> str:
|
||||
return " ".join((
|
||||
f"loop-claude runs you on {route.rung}, routed by item {route.item}'s L of {route.likelihood}.",
|
||||
f"Name each todo.md item this chunk takes, with its L and E + I, whether or not it is item {route.item}.",
|
||||
*rung_sentences(route, project),
|
||||
))
|
||||
|
||||
|
||||
def escalation(route: Route, anchor: Rung | None) -> str:
|
||||
"""The prompt's escalation sentences, the marker's among them. Empty off the ladder or on its top rung. Where escalation_rungs opens none, the worker escalates only with the human's yes.
|
||||
Else they name the rungs escalation_rungs opens to a subagent, and offer to resume the worker one rung up for the rest of the chunk, up to the highest of those rungs."""
|
||||
if anchor is None or route.rung not in LADDER[:-1]:
|
||||
return ""
|
||||
marked = f" Open the subagent's prompt with `{ESCALATION_MARKER} <n>:`, n the trigger's number."
|
||||
rungs = [f"`{rung.agent_args()}`" for rung in escalation_rungs(anchor, route)]
|
||||
def recount(route: Route) -> str:
|
||||
"""Has the worker count the routing item's size again once it knows the code, since the L that routed it was scored before anyone read that code."""
|
||||
return f"After your first read of the code, count item {route.item}'s size again: the lines, files and components you will change. Where that count would change its L, have a subagent that scores todo.md items re-score it; a re-score whose L picks a rung above yours is escalation trigger 1."
|
||||
|
||||
|
||||
def preflight_facts(printed: str) -> str:
|
||||
"""What chunk-preflight printed, for the worker to take as found."""
|
||||
return f"loop-claude ran `~/.claude/bin/chunk-preflight` at the checkout root just before this run. Take what it printed as found rather than finding it again:\n\n{printed}"
|
||||
|
||||
|
||||
def preflight_failed(reason: str) -> str:
|
||||
"""Has the worker find the facts chunk-preflight would have, its worktree among them."""
|
||||
return f"loop-claude could not run `~/.claude/bin/chunk-preflight`, so find the chunk's facts yourself. Why it could not run: {reason}"
|
||||
|
||||
|
||||
def review_launches(route: Route, project: Rung | None) -> list[str]:
|
||||
"""The sentences naming where to launch reviews, in this order; none off the ladder:
|
||||
- one for each rung, other than the worker's, that a reviewer, a seat or the security pass runs on;
|
||||
- the rung of each pass a replay lowered;
|
||||
- where the security pass runs on another rung than the worker's, that a full scan runs only from its subagent;
|
||||
- where the worker runs below the project's rung, where to launch a subagent that files or scores todo.md items;
|
||||
- the reviewers' rung each higher E + I picks.
|
||||
|
||||
For a worker on Sonnet 5.5 at high, on an Opus 5.5 project, routed by item 3 of E + I 5, they open: `Launch each reviewer with the Agent tool set to model opus, effort high, the rung item 3's E + I of 5 picks.` and `Launch each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium, the project's rung.` Where a replay lowered the prose pass to Haiku 5.5 at low, and the E + I steps no review up, a sentence follows: `Launch each prose-reviewer instead with the Agent tool set to model haiku, effort low, the rung the replay of its pass chose.`
|
||||
"""
|
||||
if project is None:
|
||||
return []
|
||||
choice = chosen(project, route)
|
||||
lowered = [f"Launch each {REVIEWERS[kind]} instead with the Agent tool set to {rung.agent_args()}, the rung the replay of its pass chose." for kind, rung in choice.lowered.items()]
|
||||
scan = ["Run a full scan only from such a subagent, since the scan's agents run on the model that starts them."] if choice.security != route.rung else []
|
||||
planning = [f"Your rung is below the project's: launch each subagent that files or scores todo.md items on the rung `~/.claude/bin/subagent-rung --plan {project.model} <L>` prints."] if position(route.rung) < position(project) else []
|
||||
return [*shared_launches(choice, route, project), *lowered, *scan, *planning, *taken_in_launches(choice)]
|
||||
|
||||
|
||||
def shared_launches(choice: ReviewChoice, route: Route, project: Rung) -> list[str]:
|
||||
"""A sentence for each rung, other than the worker's, that the reviewers no replay lowered, the seats or the security pass run on."""
|
||||
together = {EACH_REVIEWER: choice.reviewers, EACH_SEAT: choice.seat, THE_SECURITY_PASS: choice.security}
|
||||
launched: dict[Rung, list[str]] = {}
|
||||
for reviews, rung in together.items():
|
||||
if rung != route.rung:
|
||||
launched.setdefault(rung, []).append(reviews)
|
||||
return [f"Launch {listed(reviews, 'and')} with the Agent tool set to {rung.agent_args()}, {rung_named(rung, route, project)}." for rung, reviews in launched.items()]
|
||||
|
||||
|
||||
def taken_in_launches(choice: ReviewChoice) -> list[str]:
|
||||
"""The sentence naming the reviewers' rung each higher E + I picks, so the worker reviews an item it takes in on that rung in the same run, since the judge reports a taken-in item's E + I only as the cycle ends, and loop-claude routes on it from the next cycle. None where no higher E + I picks a higher rung.
|
||||
|
||||
For a worker on Opus 5.5 at medium, on an Opus 5.5 project, routed by an item of E + I 6, it reads: `Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `model opus, effort max` from 7 and `model fable, effort max` from 8.`
|
||||
"""
|
||||
if not choice.higher:
|
||||
return []
|
||||
picks = [f"`{rung.agent_args()}` from {escape_and_impact}" for rung, escape_and_impact in choice.higher.items()]
|
||||
return [f"Where an item you take into the chunk has an E + I of {min(choice.higher.values())} or more, launch {EACH_REVIEWER} with the Agent tool set to {listed(picks, 'and')}."]
|
||||
|
||||
|
||||
def rung_named(rung: Rung, route: Route, project: Rung) -> str:
|
||||
"""Why a review runs on rung: it is the project's, or the one the route's reviewed_on E + I picks, the item's or one taken in."""
|
||||
if rung == project:
|
||||
return "the project's rung"
|
||||
if route.escape_and_impact_taken_in:
|
||||
return f"the rung picked by an item of E + I {route.escape_and_impact_taken_in} taken into the chunk"
|
||||
return f"the rung item {route.item}'s E + I of {route.escape_and_impact} picks"
|
||||
|
||||
|
||||
def escalation(route: Route, project: Rung | None) -> list[str]:
|
||||
"""The prompt's escalation sentences, the marker's among them. None off the ladder or on its top rung. Where escalation_rungs opens none, the worker escalates only with the human's yes.
|
||||
Else they name the rungs escalation_rungs opens to a subagent, and offer to resume the worker one rung up for the rest of the chunk, up to the highest of those rungs.
|
||||
|
||||
For a worker on Opus 5.5 at high, on an Opus 5.5 project, routed by item 3 of L 4, they read: `When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort xhigh`, one rung above yours, and on each further trigger one rung higher, up to `model opus, effort max`; above that, ask the human first.`, `Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number.` and `Where the hard part is the rest of the chunk, end your run instead, asking loop-claude for a higher rung and naming a trigger that fired since your last step-up, if any: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `model opus, effort max`.`
|
||||
"""
|
||||
if project is None or route.rung not in LADDER[:-1]:
|
||||
return []
|
||||
marked = f"Open the subagent's prompt with `{ESCALATION_MARKER} <n>:`, n the trigger's number."
|
||||
rungs = [f"`{rung.agent_args()}`" for rung in escalation_rungs(project, route)]
|
||||
if not rungs:
|
||||
return f" An escalation trigger in `~/.claude/CLAUDE.md` lets you hand the hard part of a task to a subagent with the Agent tool set to `{climbed(route.rung, 1).agent_args()}`, one rung above yours, only once the human agrees; loop-claude will not resume you higher for a trigger either, so ask the human for that yes.{marked}"
|
||||
return [
|
||||
f"An escalation trigger in `~/.claude/CLAUDE.md` lets you hand the hard part of a task to a subagent with the Agent tool set to `{climbed(route.rung, 1).agent_args()}`, one rung above yours, only once the human agrees; loop-claude will not resume you higher for a trigger either, so ask the human for that yes.",
|
||||
marked,
|
||||
]
|
||||
further = f", and on each further trigger one rung higher, up to {rungs[-1]}" if len(rungs) > 1 else ""
|
||||
resumed_higher = f" Where the hard part is the rest of the chunk, end your run instead, asking loop-claude for a higher rung and naming a trigger that fired since your last such request: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to {rungs[-1]}."
|
||||
return f" When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to {rungs[0]}, one rung above yours{further}; above that, ask the human first.{marked}{resumed_higher}"
|
||||
return [
|
||||
f"When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to {rungs[0]}, one rung above yours{further}; above that, ask the human first.",
|
||||
marked,
|
||||
f"Where the hard part is the rest of the chunk, end your run instead, asking loop-claude for a higher rung and naming a trigger that fired since your last step-up, if any: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to {rungs[-1]}.",
|
||||
]
|
||||
|
||||
|
||||
def reruns(route: Route, anchor: Rung | None) -> str:
|
||||
"""The prompt's sentence naming the rung one above a reviewer's and a seat's, on which each reruns when it asks; empty off the ladder, and leaving out one already on the top rung."""
|
||||
if anchor is None or route.rung not in LADDER:
|
||||
return ""
|
||||
# The rungs off_the_projects_rung launches them on: the seats always on anchor, the reviewers on anchor only while the worker runs below it.
|
||||
reviewer = highest(route.rung, anchor)
|
||||
rerun = {name: climbed(rung, 1) for name, rung in (("reviewer", reviewer), ("comprehension seat", anchor)) if rung != LADDER[-1]}
|
||||
def reruns(route: Route, project: Rung | None) -> list[str]:
|
||||
"""The sentences naming the rung one above a review's, on which it reruns when it asks: shared_reruns' for a reviewer and a seat, then one for each pass a replay lowered. None off the ladder.
|
||||
|
||||
For a worker on Sonnet 5.5 at high, on an Opus 5.5 project whose prose pass a replay lowered to Haiku 5.5 at low, routed by an item of E + I 4, they read: `A reviewer or comprehension seat that asks for a rerun one rung up reruns with the Agent tool set to `model opus, effort high`.` and `Rerun each prose-reviewer that asks with the Agent tool set to `model haiku, effort medium` instead.`
|
||||
"""
|
||||
if project is None or route.rung not in LADDER:
|
||||
return []
|
||||
choice = chosen(project, route)
|
||||
lowered = [f"Rerun each {REVIEWERS[kind]} that asks with the Agent tool set to `{climbed(rung, 1).agent_args()}` instead." for kind, rung in choice.lowered.items()]
|
||||
return [*shared_reruns(choice), *lowered]
|
||||
|
||||
|
||||
def shared_reruns(choice: ReviewChoice) -> list[str]:
|
||||
"""The sentence naming the rung one above choice.reviewers and the one above choice.seat, leaving out either that is already on the top rung."""
|
||||
launched = (("reviewer", choice.reviewers), ("comprehension seat", choice.seat))
|
||||
rerun = {name: climbed(rung, 1) for name, rung in launched if rung != LADDER[-1]}
|
||||
if not rerun:
|
||||
return ""
|
||||
return []
|
||||
if len(set(rerun.values())) == 1:
|
||||
return f" A {' or '.join(rerun)} that asks for a rerun one rung up reruns with the Agent tool set to `{next(iter(rerun.values())).agent_args()}`."
|
||||
return f" A reviewer that asks for a rerun one rung up reruns with the Agent tool set to `{rerun['reviewer'].agent_args()}`, and a comprehension seat with `{rerun['comprehension seat'].agent_args()}`."
|
||||
return [f"A {listed(list(rerun), 'or')} that asks for a rerun one rung up reruns with the Agent tool set to `{next(iter(rerun.values())).agent_args()}`."]
|
||||
return [f"A reviewer that asks for a rerun one rung up reruns with the Agent tool set to `{rerun['reviewer'].agent_args()}`, and a comprehension seat with `{rerun['comprehension seat'].agent_args()}`."]
|
||||
|
||||
|
||||
def resumed(unfinished_evidence: str, route: Route, anchor: Rung | None) -> str:
|
||||
def resumed(unfinished_evidence: str, route: Route, project: Rung | None) -> str:
|
||||
"""Names the worker's rung, so it learns whether its request for a higher rung went through, and the project's again, since a step-up between cycles may have taken the worker above it."""
|
||||
on = f" loop-claude runs you on {route.rung}." if anchor else ""
|
||||
on = f" loop-claude runs you on {route.rung}." if project else ""
|
||||
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}.{on}{off_the_projects_rung(route, anchor)}{escalation(route, anchor)}{reruns(route, anchor)}"
|
||||
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}.{on}{rungs_held(route, project)}"
|
||||
|
||||
|
||||
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 rung_sentences(route: Route, project: Rung | None) -> list[str]:
|
||||
"""The sentences that depend on the worker's rung: where its reviews run and rerun, and where its escalated subagents run."""
|
||||
return [*review_launches(route, project), *escalation(route, project), *reruns(route, project)]
|
||||
|
||||
|
||||
def rungs_held(route: Route, project: Rung | None) -> str:
|
||||
"""rung_sentences, each after a space, to follow the sentence a prompt ends on."""
|
||||
return "".join(f" {sentence}" for sentence in rung_sentences(route, project))
|
||||
|
||||
|
||||
def answered(question: str, answer: str, route: Route, project: Rung | None, stepped: bool) -> str:
|
||||
"""stepped is whether the answer's ruling stepped the worker up."""
|
||||
return f"Your question: {question}\n\n{QUOTE_SOURCES} answers it:\n\n{answer}\n\nContinue the task.{stepped_to(route, project, stepped)}"
|
||||
|
||||
|
||||
def typed(question: str, answer: str, route: Route, project: Rung | None, stepped: bool) -> str:
|
||||
"""The prompt that resumes the worker with the human's answer to an interrupt. answer is one line, as the terminal reads it."""
|
||||
return f"{TYPED_HERE}\n{answer}\n\nYour question was: {question}\n\nContinue the task. The chunk is finished only once {ANSWERS_RECORDED}.{stepped_to(route, project, stepped)}"
|
||||
|
||||
|
||||
# Opens typed's prompt, with the answer on the line after it, so typed_answer finds the answer at the prompt's start, whatever the question holds.
|
||||
TYPED_HERE = "The human answered your question at loop-claude's terminal:"
|
||||
|
||||
|
||||
def typed_answer(prompt: str) -> Typed | None:
|
||||
"""Splits a prompt from typed() into its answer and the rest, so the judge reads the answer as the human's; None for any other prompt."""
|
||||
opening = f"{TYPED_HERE}\n"
|
||||
if not prompt.startswith(opening):
|
||||
return None
|
||||
answer, _, rest = prompt.removeprefix(opening).partition("\n\n")
|
||||
return Typed(rest, answer)
|
||||
|
||||
|
||||
def stepped_to(route: Route, project: Rung | None, stepped: bool) -> str:
|
||||
"""The sentences naming the worker's new rung, as resumed has them, where the ruling that brought the answer stepped the worker up; empty otherwise."""
|
||||
return f" Your request for a higher rung went through: loop-claude runs you on {route.rung}. The escalation triggers that fired before this step are spent.{rungs_held(route, project)}" if stepped else ""
|
||||
|
||||
|
||||
def past_the_cap(question: str, answer: str, cap: int) -> str:
|
||||
|
||||
@@ -14,7 +14,8 @@ RETRY_DELAY = 60
|
||||
UNKNOWN_RESET_POLL = 600
|
||||
|
||||
|
||||
def retried(who: str, attempt: typing.Callable[[], T | Failure | Limited], effects: Effects) -> T | Stop:
|
||||
def retried(who: str, attempt: typing.Callable[[], T | Failure | Limited], effects: Effects, keep: typing.Callable[[Failure], Stop | None] = lambda failure: None) -> T | Stop:
|
||||
"""The attempt's result, retried on a failure. keep sees each failure, the third running included; a Stop from keep ends the retrying."""
|
||||
failures = 0
|
||||
while True:
|
||||
result = attempt()
|
||||
@@ -28,6 +29,8 @@ def retried(who: str, attempt: typing.Callable[[], T | Failure | Limited], effec
|
||||
continue
|
||||
if not isinstance(result, Failure):
|
||||
return result
|
||||
if stop := keep(result):
|
||||
return stop
|
||||
failures += 1
|
||||
if failures == FAILURES_RUNNING:
|
||||
return Stop(1, f"the {who} failed three times running: {result.reason}")
|
||||
|
||||
@@ -2,28 +2,33 @@ 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 loop_claude.cycle.states import Active, Archived, Closing, Ended, Event, HumanTalked, HumanTyped, Interrupting, Judging, QUOTED_ANSWERS_PER_CYCLE, Ruled, State, TalkChosen, Talking, transition, TypedAnswer, WorkerRan, Working
|
||||
from loop_claude.routing import after_ruling, judge_rung
|
||||
from 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.routing import judge_rung
|
||||
from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict
|
||||
from loop_claude.cycle.judge import judge, Rejected
|
||||
from transcript_archive import outcomes
|
||||
from loop_claude.paths import Paths
|
||||
from loop_claude.cycle import prompts
|
||||
from claude_code.transcript import read_transcript, render
|
||||
from loop_claude.cycle.interrupt import put_question, talk, Talk
|
||||
from claude_code.transcript import read_transcript
|
||||
from loop_claude.cycle.retry import retried
|
||||
from model_routing.route import Route
|
||||
from loop_claude.cycle.worker import run_worker, worker_args
|
||||
from model_routing.ladder import Rung
|
||||
from loop_claude.escalation_mark import StepUp
|
||||
from loop_claude.stop import Stop
|
||||
from model_routing import worker_rungs
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Cycle:
|
||||
effects: Effects
|
||||
# What chunk-preflight found, or why it could not run, for a fresh worker's prompt; empty when the session was open as the cycle began.
|
||||
facts: str
|
||||
judge_model: str
|
||||
paths: Paths
|
||||
premises: str
|
||||
@@ -34,27 +39,45 @@ class Cycle:
|
||||
task: str
|
||||
route: Route
|
||||
# The project's rung; None for a model off the ladder.
|
||||
anchor: Rung | None
|
||||
project: Rung | None
|
||||
# Empty when the previous cycle's verdict was not Unfinished.
|
||||
unfinished_evidence: str
|
||||
|
||||
|
||||
def run_cycle(cycle: Cycle) -> Stop | Finished | Unfinished:
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Concluded:
|
||||
"""How a cycle ended: its verdict, and the route it ended on, which an interrupt's or a quoted answer's escalation may have stepped up from the route it began on."""
|
||||
verdict: Finished | Unfinished
|
||||
route: Route
|
||||
|
||||
|
||||
def run_cycle(cycle: Cycle) -> Stop | Concluded:
|
||||
state: State = Working()
|
||||
try:
|
||||
while not isinstance(state, Ended):
|
||||
event = step(cycle, state)
|
||||
if isinstance(event, Stop):
|
||||
return stopped(cycle, event, event.reason)
|
||||
# Only a ruling's step-up changes the route within a cycle. No transition reads the current route, so Cycle holds it, not the states.
|
||||
if isinstance(event, Ruled) and event.step_up:
|
||||
cycle = dataclasses.replace(cycle, route=event.step_up.after)
|
||||
state = transition(state, event)
|
||||
except KeyboardInterrupt:
|
||||
return stopped(cycle, Stop(130, ""), "Ctrl-C")
|
||||
return state.verdict
|
||||
return Concluded(state.verdict, cycle.route)
|
||||
|
||||
|
||||
def ruling_step_up(cycle: Cycle, verdict: Verdict) -> StepUp | None:
|
||||
"""The step-up an interrupt's or a quoted answer's escalation makes, so the work after the answer runs on the stepped route; None where the route holds."""
|
||||
if not (isinstance(verdict, Interrupt | QuotedAnswer) and cycle.project):
|
||||
return None
|
||||
after = after_ruling(cycle.project, cycle.route, verdict)
|
||||
return StepUp(cycle.route, after) if after != cycle.route else None
|
||||
|
||||
|
||||
def stopped(cycle: Cycle, stop: Stop, why: str) -> Stop:
|
||||
path = transcript_file(cycle.session)
|
||||
failure = archive(cycle.project_archive, path, cycle.task, outcomes.stopped(str(cycle.route), why), cycle.effects.now()) if path else None
|
||||
failure = archive(cycle.project_archive, path, cycle.task, outcomes.stopped(cycle.route.worker_line(), why), cycle.effects.now()) if path else None
|
||||
# A failed archive exits 1 whatever the stop; when the stop was this archive failing, its reason is said once.
|
||||
return Stop(1, f"{failure.reason}\n{stop.reason}".rstrip()) if failure and failure.reason != stop.reason else stop
|
||||
|
||||
@@ -66,41 +89,54 @@ def judge_of(cycle: Cycle) -> Rung:
|
||||
|
||||
def step(cycle: Cycle, state: Active) -> Event | Stop:
|
||||
match state:
|
||||
case Working(answered, _):
|
||||
return work(cycle, answered)
|
||||
case Working(answered, _, step_up):
|
||||
return work(cycle, answered, step_up)
|
||||
case Judging(transcript_path, _):
|
||||
return rule(cycle, transcript_path)
|
||||
case Interrupting(transcript_path, ruling, _):
|
||||
return ask(cycle, transcript_path, ruling)
|
||||
case Interrupting(transcript_path, ruling, _, step_up):
|
||||
return ask(cycle, transcript_path, ruling, step_up)
|
||||
case Talking(transcript_path, _):
|
||||
return talk(cycle.root, cycle.session.id, cycle.route.rung, transcript_path, cycle.paths, worker_environment(cycle), cycle.effects) or HumanTalked()
|
||||
case Closing(transcript_path, verdict):
|
||||
return close(cycle, transcript_path, verdict)
|
||||
case _:
|
||||
typing.assert_never(state)
|
||||
|
||||
|
||||
def work(cycle: Cycle, answered: QuotedAnswer | None) -> WorkerRan | Stop:
|
||||
if answered is not None:
|
||||
def work(cycle: Cycle, answered: QuotedAnswer | TypedAnswer | None, step_up: StepUp | None) -> WorkerRan | Stop:
|
||||
if isinstance(answered, QuotedAnswer):
|
||||
print(f"\n=== {prompts.QUOTE_SOURCES} answered: {answered.question} ===\n{answered.answer}", flush=True)
|
||||
if stop := keep_answer(cycle, answered):
|
||||
if stop := keep_answer(cycle, answered, step_up):
|
||||
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):
|
||||
if stop := retried("worker", lambda: run_worker(cycle.root, worker_start(cycle, answered, step_up), worker_environment(cycle), cycle.effects), cycle.effects):
|
||||
return stop
|
||||
path = transcript_file(cycle.session)
|
||||
return WorkerRan(path) if path is not None else Stop(1, f"claude left no transcript for session {cycle.session.id}")
|
||||
|
||||
|
||||
def worker_start(cycle: Cycle, answered: QuotedAnswer | None) -> list[str]:
|
||||
if answered is not None:
|
||||
return worker_args(cycle.session, cycle.route.rung, prompts.answered(answered.question, answered.answer), resume=True)
|
||||
def worker_environment(cycle: Cycle) -> dict[str, str]:
|
||||
"""The rungs the worker's claude is handed, which rule-hook holds its review launches to."""
|
||||
return worker_rungs.environment(cycle.project, cycle.route)
|
||||
|
||||
|
||||
def worker_start(cycle: Cycle, answered: QuotedAnswer | TypedAnswer | None, step_up: StepUp | None) -> list[str]:
|
||||
if isinstance(answered, QuotedAnswer):
|
||||
return worker_args(cycle.session, cycle.route.rung, prompts.answered(answered.question, answered.answer, cycle.route, cycle.project, step_up is not None), resume=True)
|
||||
if isinstance(answered, TypedAnswer):
|
||||
return worker_args(cycle.session, cycle.route.rung, prompts.typed(answered.question, answered.answer, cycle.route, cycle.project, step_up is not None), resume=True)
|
||||
if session_open(cycle.session):
|
||||
return worker_args(cycle.session, cycle.route.rung, prompts.resumed(cycle.unfinished_evidence, cycle.route, cycle.anchor), resume=True)
|
||||
return worker_args(cycle.session, cycle.route.rung, prompts.fresh(cycle.task, cycle.premises, cycle.route, cycle.anchor), resume=False)
|
||||
return worker_args(cycle.session, cycle.route.rung, prompts.resumed(cycle.unfinished_evidence, cycle.route, cycle.project), resume=True)
|
||||
return worker_args(cycle.session, cycle.route.rung, prompts.fresh(cycle.task, cycle.premises, cycle.route, cycle.project, cycle.facts), resume=False)
|
||||
|
||||
|
||||
def keep_answer(cycle: Cycle, answered: QuotedAnswer) -> Stop | None:
|
||||
def keep_answer(cycle: Cycle, answered: QuotedAnswer, step_up: StepUp | None) -> 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, str(judge_of(cycle))), cycle.effects.now())):
|
||||
if not path:
|
||||
return None
|
||||
# As in ask: the answer names the rung the worker ran on until then, and a step-up archived after it names the rung it runs on from then.
|
||||
quoted = outcomes.answered(answered.question, prompts.QUOTE_SOURCES, answered.answer, answered.evidence, answered.escalation, str(judge_of(cycle)), ran_on(cycle, step_up).worker_line())
|
||||
if failure := archive_stepped(cycle, path, quoted, step_up):
|
||||
return Stop(1, failure.reason)
|
||||
return None
|
||||
|
||||
@@ -109,16 +145,43 @@ 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), judge_of(cycle), cycle.effects)
|
||||
return verdict if isinstance(verdict, Stop) else Ruled(verdict)
|
||||
verdict = judge(cycle.root, cycle.task, cycle.premises, cycle.records, entries, cycle.route.escalated_at, judge_of(cycle), cycle.effects, lambda rejected: keep_rejection(cycle, transcript_path, rejected))
|
||||
return verdict if isinstance(verdict, Stop) else Ruled(verdict, ruling_step_up(cycle, verdict))
|
||||
|
||||
|
||||
def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer) -> HumanAnswered | Stop:
|
||||
def keep_rejection(cycle: Cycle, transcript_path: str, rejected: Rejected) -> Stop | None:
|
||||
"""Archives a judge reply loop-claude rejected, so the archive shows what the judge returned before a retry or an exit 1."""
|
||||
if unkept := archive(cycle.project_archive, transcript_path, cycle.task, outcomes.rejected(rejected.reason, rejected.reply, str(judge_of(cycle))), cycle.effects.now()):
|
||||
return Stop(1, unkept.reason)
|
||||
return None
|
||||
|
||||
|
||||
def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer, step_up: StepUp | None) -> HumanTyped | TalkChosen | Stop:
|
||||
question = question_for(ruling)
|
||||
# Archived now, so the transcript the question was asked on is kept with it; the human's answer then grows the transcript.
|
||||
if failure := archive(cycle.project_archive, transcript_path, cycle.task, outcomes.interrupted(question, ruling.evidence, str(judge_of(cycle))), cycle.effects.now()):
|
||||
# The interrupt names the rung the worker ran on before it; a step-up archived after it names the stepped rung, so the figures charge each stretch to its own rung.
|
||||
interrupted = outcomes.interrupted(question, ruling.evidence, str(judge_of(cycle)), ruling.escalation, ran_on(cycle, step_up).worker_line())
|
||||
if failure := archive_stepped(cycle, transcript_path, interrupted, step_up):
|
||||
return Stop(1, failure.reason)
|
||||
return interrupt(cycle.root, cycle.session.id, cycle.route.rung, transcript_path, question, cycle.paths, cycle.effects) or HumanAnswered()
|
||||
# Only the human may cut a release, so a release ready to cut opens claude's session at once.
|
||||
answer = put_question(question, not (isinstance(ruling, Interrupt) and ruling.release_ready), cycle.effects)
|
||||
if isinstance(answer, Stop):
|
||||
return answer
|
||||
# The worker gets the question it asked, not the one put to the human past the cap.
|
||||
return TalkChosen() if isinstance(answer, Talk) else HumanTyped(TypedAnswer(ruling.question, answer))
|
||||
|
||||
|
||||
def ran_on(cycle: Cycle, step_up: StepUp | None) -> Route:
|
||||
"""The route the worker ran on until the ruling: the one before its step-up, if it made one."""
|
||||
return step_up.before if step_up else cycle.route
|
||||
|
||||
|
||||
def archive_stepped(cycle: Cycle, transcript_path: str, outcome: str, step_up: StepUp | None) -> Failure | None:
|
||||
"""Archives the outcome of a ruling, then the step-up it made, if it made one. The first failure is returned."""
|
||||
for kept in (outcome, outcomes.stepped_up(step_up.after.worker_line())) if step_up else (outcome,):
|
||||
if failure := archive(cycle.project_archive, transcript_path, cycle.task, kept, cycle.effects.now()):
|
||||
return failure
|
||||
return None
|
||||
|
||||
|
||||
def question_for(ruling: Interrupt | QuotedAnswer) -> str:
|
||||
@@ -128,7 +191,7 @@ def question_for(ruling: Interrupt | QuotedAnswer) -> str:
|
||||
|
||||
|
||||
def close(cycle: Cycle, transcript_path: str, verdict: Finished | Unfinished) -> Archived | Stop:
|
||||
outcome = outcomes.finished(str(cycle.route), verdict.evidence, str(judge_of(cycle))) if isinstance(verdict, Finished) else outcomes.unfinished(str(cycle.route), verdict.evidence, str(judge_of(cycle)), verdict.escalation)
|
||||
outcome = outcomes.finished(cycle.route.worker_line(), verdict.evidence, str(judge_of(cycle))) if isinstance(verdict, Finished) else outcomes.unfinished(cycle.route.worker_line(), verdict.evidence, str(judge_of(cycle)), verdict.escalation)
|
||||
if failure := archive(cycle.project_archive, transcript_path, cycle.task, outcome, cycle.effects.now()):
|
||||
return Stop(1, failure.reason)
|
||||
if isinstance(verdict, Finished) and (failure := delete_session(cycle.session)):
|
||||
|
||||
@@ -1,16 +1,26 @@
|
||||
import dataclasses
|
||||
|
||||
from loop_claude.cycle.judge import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict
|
||||
from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict
|
||||
from loop_claude.escalation_mark import StepUp
|
||||
|
||||
# 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 TypedAnswer:
|
||||
"""The human's answer to an interrupt, typed at loop-claude's terminal."""
|
||||
question: str
|
||||
answer: str
|
||||
|
||||
|
||||
@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
|
||||
"""The worker runs, resumed with an answer quoted from README.md or the records, or typed by the human, when there is one."""
|
||||
answered: QuotedAnswer | TypedAnswer | None = None
|
||||
quoted_answers: int = 0
|
||||
# The step-up made by the ruling that brought the answer, so the worker is told of it; None for none.
|
||||
step_up: StepUp | None = None
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -26,6 +36,15 @@ class Interrupting:
|
||||
transcript_path: str
|
||||
ruling: Interrupt | QuotedAnswer
|
||||
quoted_answers: int = 0
|
||||
# The step-up the ruling made. It holds through the answer the human types, and drops on /talk.
|
||||
step_up: StepUp | None = None
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Talking:
|
||||
"""The human answers in the worker's claude session, on the terminal."""
|
||||
transcript_path: str
|
||||
quoted_answers: int = 0
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -39,7 +58,7 @@ class Ended:
|
||||
verdict: Finished | Unfinished
|
||||
|
||||
|
||||
Active = Working | Judging | Interrupting | Closing
|
||||
Active = Working | Judging | Interrupting | Talking | Closing
|
||||
State = Active | Ended
|
||||
|
||||
|
||||
@@ -51,11 +70,23 @@ class WorkerRan:
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Ruled:
|
||||
verdict: Verdict
|
||||
# None unless an interrupt's or a quoted answer's escalation stepped the route; always None for a finished or unfinished verdict.
|
||||
step_up: StepUp | None = None
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class HumanAnswered:
|
||||
pass
|
||||
class HumanTyped:
|
||||
typed: TypedAnswer
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class TalkChosen:
|
||||
"""The human typed /talk, or the interrupt is for a release ready to cut."""
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class HumanTalked:
|
||||
"""The human typed in the worker's claude session."""
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -63,23 +94,27 @@ class Archived:
|
||||
pass
|
||||
|
||||
|
||||
Event = WorkerRan | Ruled | HumanAnswered | Archived
|
||||
Event = WorkerRan | Ruled | HumanTyped | TalkChosen | HumanTalked | 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(_, quoted_answers), Ruled(QuotedAnswer() as answered, step_up) if quoted_answers < QUOTED_ANSWERS_PER_CYCLE:
|
||||
return Working(answered, quoted_answers + 1, step_up)
|
||||
case Judging(transcript_path, quoted_answers), Ruled(QuotedAnswer() as ruling, step_up) if quoted_answers >= QUOTED_ANSWERS_PER_CYCLE:
|
||||
return Interrupting(transcript_path, ruling, quoted_answers, step_up)
|
||||
case Judging(transcript_path, quoted_answers), Ruled(Interrupt() as ruling, step_up):
|
||||
return Interrupting(transcript_path, ruling, quoted_answers, step_up)
|
||||
case Judging(transcript_path, _), 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():
|
||||
case Interrupting(_, _, quoted_answers, step_up), HumanTyped(typed):
|
||||
return Working(typed, quoted_answers, step_up)
|
||||
case Interrupting(transcript_path, _, quoted_answers), TalkChosen():
|
||||
return Talking(transcript_path, quoted_answers)
|
||||
# The human worked in the worker's claude session, so the judge rules again on the transcript it leaves.
|
||||
case Talking(transcript_path, quoted_answers), HumanTalked():
|
||||
return Judging(transcript_path, quoted_answers)
|
||||
case Closing(_, verdict), Archived():
|
||||
return Ended(verdict)
|
||||
|
||||
@@ -9,9 +9,9 @@ from claude_code.session import Session
|
||||
PRINTED_TOOL_INPUT = 160
|
||||
|
||||
|
||||
def run_worker(root: str, args: list[str], effects: Effects) -> Failure | Limited | None:
|
||||
def run_worker(root: str, args: list[str], env: dict[str, str], effects: Effects) -> Failure | Limited | None:
|
||||
try:
|
||||
proc = effects.stream_claude(args, root)
|
||||
proc = effects.stream_claude(args, root, env)
|
||||
except OSError as failure:
|
||||
return Failure(f"could not start claude: {failure.strerror}")
|
||||
result: dict | None = None
|
||||
@@ -47,6 +47,8 @@ def worker_args(session: Session, worker: Rung, prompt: str, resume: bool) -> li
|
||||
*start,
|
||||
"--output-format", "stream-json",
|
||||
"--permission-mode", "bypassPermissions",
|
||||
# A pending wakeup keeps claude -p from exiting, which holds back the judge.
|
||||
"--disallowedTools", "ScheduleWakeup",
|
||||
"--verbose",
|
||||
*worker.flags(),
|
||||
]
|
||||
|
||||
@@ -2,9 +2,22 @@ import dataclasses
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import termios
|
||||
import time
|
||||
import typing
|
||||
|
||||
from failure import Failure
|
||||
import git_repo
|
||||
|
||||
# Seconds before a Python script loop-claude runs is stopped, so a hung one, such as chunk-preflight, cannot hold the loop.
|
||||
PYTHON_TIMEOUT = 600
|
||||
|
||||
|
||||
class Git(typing.Protocol):
|
||||
"""Runs git in cwd, as git_repo.git does."""
|
||||
|
||||
def __call__(self, *args: str, cwd: str) -> str | Failure: ...
|
||||
|
||||
|
||||
class Streaming(typing.Protocol):
|
||||
"""A started claude whose stream-json lines arrive as it works."""
|
||||
@@ -17,21 +30,24 @@ class Streaming(typing.Protocol):
|
||||
@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]
|
||||
claude_on_terminal: typing.Callable[[list[str], str, dict[str, str]], int]
|
||||
# Drops what was typed on the terminal and not yet read.
|
||||
discard_typed: typing.Callable[[], None]
|
||||
execv: typing.Callable[[str, list[str]], None]
|
||||
git: typing.Callable[[list[str], str], subprocess.CompletedProcess[str]]
|
||||
git: Git
|
||||
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]]
|
||||
# Runs a Python script in a directory, as run_python does.
|
||||
python: typing.Callable[[list[str], str], subprocess.CompletedProcess[str]]
|
||||
sleep: typing.Callable[[float], None]
|
||||
stream_claude: typing.Callable[[list[str], str], Streaming]
|
||||
stream_claude: typing.Callable[[list[str], str, dict[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 __init__(self, args: list[str], cwd: str, env: dict[str, str]) -> None:
|
||||
self.proc = subprocess.Popen(["claude", *args], cwd=cwd, env={**os.environ, **env}, encoding="utf-8", errors="replace", stdin=subprocess.DEVNULL, stdout=subprocess.PIPE)
|
||||
|
||||
def lines(self) -> typing.Iterable[str]:
|
||||
with self.proc:
|
||||
@@ -44,14 +60,26 @@ class StreamingClaude:
|
||||
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,
|
||||
claude_on_terminal=lambda args, cwd, env: subprocess.run(["claude", *args], cwd=cwd, env={**os.environ, **env}).returncode,
|
||||
discard_typed=lambda: termios.tcflush(sys.stdin, termios.TCIFLUSH),
|
||||
execv=os.execv,
|
||||
git=lambda args, cwd: subprocess.run(["git", *args], capture_output=True, cwd=cwd, text=True),
|
||||
git=git_repo.git,
|
||||
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),
|
||||
python=lambda args, cwd: run_python(args, cwd, PYTHON_TIMEOUT),
|
||||
sleep=time.sleep,
|
||||
stream_claude=StreamingClaude,
|
||||
)
|
||||
|
||||
|
||||
def run_python(args: list[str], cwd: str, timeout: float) -> subprocess.CompletedProcess[str]:
|
||||
"""Runs a Python script in cwd. One that cannot start, or still runs after timeout seconds and is stopped, reads as exit 1, saying why on stderr."""
|
||||
command = [sys.executable, *args]
|
||||
try:
|
||||
return subprocess.run(command, capture_output=True, cwd=cwd, encoding="utf-8", errors="replace", stdin=subprocess.DEVNULL, timeout=timeout)
|
||||
except OSError as failure:
|
||||
return subprocess.CompletedProcess(command, 1, "", f"could not start: {failure}")
|
||||
except subprocess.TimeoutExpired:
|
||||
return subprocess.CompletedProcess(command, 1, "", f"stopped after {timeout} s")
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
"""The escalation mark makes one escalation trigger step the worker up one rung, never two (docs/decisions.md → `routing: a worker whose run ends asking for a higher rung`).
|
||||
|
||||
A worker whose run ends asking loop-claude for a higher rung cites the trigger that fired, and the judge quotes the passage where it fired as the verdict's escalation. The mark, Route.escalated_at, is how many transcript entries the session held when an escalation last stepped the worker up, 0 before any. The session's transcript only grows, so the mark holds across cycles, and the archive's Worker: lines keep it for a rerun.
|
||||
|
||||
- Stamp. stamped() writes on the judge's verdict how many entries the judge read.
|
||||
- Step. routing.after_unfinished() and routing.after_ruling() step the worker up on an escalation and move the mark to moved_to(verdict). A ruling's StepUp travels through the cycle's states, so the archive and the worker's next prompt name it.
|
||||
- Show. transcript() puts STEP_LINE after the mark, telling the judge that the triggers before that line are spent. QUOTE_AFTER_STEP, in the judge's schema, tells the judge to quote only the worker's words after that line.
|
||||
- Check. checked() keeps an escalation only where it quotes both the transcript the judge was shown and the worker's own lines after the mark, which since_step() renders, so a passage that bought one step cannot buy another.
|
||||
"""
|
||||
import dataclasses
|
||||
import typing
|
||||
|
||||
from loop_claude.verdicts import Escalating, Verdict
|
||||
from claude_code.entries import human_text, loop_text
|
||||
from claude_code.transcript import render, Typed, verbatim
|
||||
from model_routing.route import Route
|
||||
|
||||
# Only the judge reads the step line, so it is not a [loop] line.
|
||||
STEP_TAG = "[step]"
|
||||
STEP_LINE = f"{STEP_TAG} loop-claude stepped the worker up a rung here, so the escalation triggers that fired before this line are spent."
|
||||
# Reply.escalation's description in cycle/judge.py carries this sentence, so the judge reads STEP_LINE as the mark.
|
||||
QUOTE_AFTER_STEP = f"Where a {STEP_TAG} line says loop-claude stepped the worker up a rung, quote only the worker's own words after it, and leave this empty where the trigger fired only before it."
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class StepUp:
|
||||
"""An interrupt's or a quoted answer's escalation stepping the route within a cycle: the route the worker ran on until the ruling, and the one it runs on after."""
|
||||
before: Route
|
||||
after: Route
|
||||
|
||||
|
||||
def stamped(verdict: Verdict, entries_read: int) -> Verdict:
|
||||
"""The verdict with how many transcript entries the judge read, where it may carry an escalation."""
|
||||
return dataclasses.replace(verdict, entries_read=entries_read) if isinstance(verdict, Escalating) else verdict
|
||||
|
||||
|
||||
def moved_to(verdict: Escalating) -> int | None:
|
||||
"""Where the verdict's escalation would move the mark, if the escalation steps the worker; None for a verdict without one."""
|
||||
return verdict.entries_read if verdict.escalation else None
|
||||
|
||||
|
||||
def transcript(entries: list[dict], at: int, typed_answer: typing.Callable[[str], Typed | None]) -> str:
|
||||
"""The transcript as the judge sees it. Where the mark, at, is above 0, STEP_LINE comes after that many entries."""
|
||||
return "\n\n".join(part for part in (render(entries[:at], typed_answer), STEP_LINE if at else "", render(entries[at:], typed_answer)) if part)
|
||||
|
||||
|
||||
def since_step(entries: list[dict], at: int) -> str:
|
||||
"""The worker's own lines after the mark, all of them, however much of the transcript the judge is shown. loop-claude's prompts and the human's lines are left out, since they repeat earlier passages, such as the judge's evidence or the worker's question."""
|
||||
# No loop-claude prompt is left to carry an answer the human typed.
|
||||
return render([entry for entry in entries[at:] if human_text(entry) is None and loop_text(entry) is None], lambda prompt: None)
|
||||
|
||||
|
||||
def checked(verdict: Verdict, *, since: str, shown: str) -> Verdict:
|
||||
"""The verdict without its escalation unless the escalation quotes both texts: since, the worker's lines after the mark as since_step renders them, and shown, the transcript the judge was shown. A misquote, or a quote of a passage before the mark, drops the escalation, so the worker's rung holds."""
|
||||
if isinstance(verdict, Escalating) and verdict.escalation and not (verbatim(verdict.escalation, since) and verbatim(verdict.escalation, shown)):
|
||||
return dataclasses.replace(verdict, escalation="")
|
||||
return verdict
|
||||
+126
-105
@@ -4,8 +4,10 @@ usage: loop-claude <task>
|
||||
|
||||
Run it anywhere inside a project checkout whose README.md has ## Goals and ## Audience, the
|
||||
premises; the task runs at the checkout root. Each cycle a worker runs the task. A chunk's first
|
||||
worker prompt also quotes the premises, which choose between ways to deliver the chunk's todo.md
|
||||
items, or else the task, and never widen them. A judge then reads the transcript's end, the premises, and the records: the project's AGENTS.md and docs/decisions.md,
|
||||
worker prompt also quotes the premises. They, with code health
|
||||
(~/.claude/CLAUDE.md → "Shared goal") ranked first unless README.md voids it, choose between ways
|
||||
to deliver the chunk's todo.md items, or else the task, and never widen them. A judge then reads
|
||||
the transcript's end, the premises, and the records: the project's AGENTS.md and docs/decisions.md,
|
||||
and the human's ~/.claude/CLAUDE.md, ~/.claude/rules/*.md and
|
||||
~/.claude/skills/larv-review/standards/*.md, where they exist. It rules whether the chunk, the work
|
||||
of one PR, is finished. A chunk stays unfinished until each answer the human typed in it that a
|
||||
@@ -15,78 +17,60 @@ worker made that the premises or the records settle is not asked about. When the
|
||||
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, and the worker is shown the passage the judge quoted as the work remaining.
|
||||
The next chunk starts a fresh session.
|
||||
the human too, with the quote. An unfinished chunk resumes its session next cycle, and the worker
|
||||
is shown the passage the judge quoted as the work remaining. The next chunk starts a fresh session.
|
||||
Cycles continue until an exit below or Ctrl-C. Words: ~/.claude/CLAUDE.md → "Vocabulary".
|
||||
|
||||
A question only the human can answer is an interrupt (bin/loop_claude/cycle/interrupt.py).
|
||||
loop-claude prints the question and reads a one-line answer on its terminal. The worker resumes
|
||||
headless with the answer. The judge reads it as the human's, so the chunk stays unfinished until the
|
||||
answer is recorded. An empty answer stops the loop. Typing /talk instead opens the worker's session
|
||||
on the terminal with `claude --resume`, to read the diff or discuss first. Once that claude exits,
|
||||
the judge rules on what was typed there. A release ready to cut opens that session at once, since
|
||||
only the human may cut it. Before claude opens, the checkout and each of its worktrees are marked
|
||||
trusted in ~/.claude.json.
|
||||
|
||||
As a chunk starts, before it is routed, loop-claude runs bin/chunk-preflight (bin/chunk_preflight/),
|
||||
which finds the chunk's facts and makes its worktree; chunk-preflight --help lists them, and
|
||||
prompts.preflight_facts in bin/loop_claude/cycle/prompts.py quotes them in the first prompt. A
|
||||
preflight that fails, or is still running after 600 s and is stopped, leaves the worker to find the
|
||||
facts itself.
|
||||
|
||||
Each project has one session, named "A <key> loop-claude", where <key> is the checkout's path
|
||||
relative to ~/code, or to / outside it. The session is deleted when its chunk finishes. At every
|
||||
interrupt, and as every cycle ends, Ctrl-C and a failure included, the session's transcript is
|
||||
copied 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, any passage it quoted to
|
||||
show an escalation trigger fired, and the judge's rung; 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>.
|
||||
copied into a folder per chunk under $LOOP_CLAUDE_TRANSCRIPTS/<key> (default root
|
||||
~/.claude/loop-claude-transcripts), named by its hash, with an outcomes file beside it: the task,
|
||||
then each verdict, quoted answer, rejected judge reply, step-up and stop, each opened by its UTC
|
||||
time. The layout, and when a copy is replaced, are in bin/transcript_archive/__init__.py.
|
||||
|
||||
Every claude loop-claude starts runs the project's model, saved per <key> in
|
||||
~/.claude/loop-claude-models.json and read each cycle, unless routing, below, puts the worker,
|
||||
the interrupt and the judge on another rung; 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.
|
||||
the session /talk opens and the judge on another rung, a model at an effort. A project without an
|
||||
entry, as on its first run, is asked for one. LOOP_CLAUDE_JUDGE_MODEL overrides the model for the
|
||||
judge, LOOP_CLAUDE_WORKER_MODEL for the worker and the session /talk opens; with both set, nothing
|
||||
is asked.
|
||||
|
||||
Where that model is on the routing ladder (bin/model_routing/ladder.py), the worker and the
|
||||
interrupt run on one of the ladder's rungs: a model at an effort. As a chunk starts, the R + C of
|
||||
todo.md's top item in the next release that does not wait picks the rung: an item waits while it is
|
||||
marked question, or while an item that blocks it is still in the table. The R + C
|
||||
counts from the model's cheapest rung, and an R + C of 8 or less picks a rung below it; without
|
||||
such an item, or with a C missing, the chunk runs on the model's cheapest rung. The worker's first
|
||||
prompt names the rung and the item, and asks the worker to name each item the chunk takes, with its
|
||||
R + C. When that rung is below the model's cheapest, the prompt also has the worker launch each
|
||||
reviewer, each comprehension seat and the security pass in subagents on the cheapest rung. When it
|
||||
is above, the prompt has the worker launch only each comprehension seat and the security pass on
|
||||
the cheapest rung. The prompt after each unfinished verdict
|
||||
says this again, since a step-up may have taken the worker above the cheapest rung. A reviewer or
|
||||
seat that rules the work below standard may ask to rerun one rung up; each prompt names that rung. The
|
||||
judge reports the highest R + C the worker states, and the next cycle steps up to the rung that
|
||||
R + C picks, never down. Every second unfinished verdict on a chunk steps it up one rung. So does
|
||||
an unfinished verdict on a worker that ended its run asking for a higher rung, once the judge quotes
|
||||
the transcript showing that the escalation trigger it named fired
|
||||
(~/.claude/CLAUDE.md → "Working with the codebase" lists them). That step stops two rungs above the rung the chunk's item picks, and the
|
||||
worker's prompts offer it only while the worker is below that limit. Each
|
||||
finished or unfinished verdict, stop and step-up in the archive names the worker's rung, with the
|
||||
item and R + C that routed the chunk; a rerun resumes an open chunk on the latest rung named there,
|
||||
and counts its unfinished verdicts afresh. A rung no longer on the ladder, or below the one its
|
||||
item's R + C picks, is dropped, and the chunk is routed afresh from todo.md. A todo.md or an
|
||||
archive that cannot be read or parsed is said on stderr, and the chunk is routed without it.
|
||||
Where the project's model is on the routing ladder (bin/model_routing/ladder.py), the worker and the
|
||||
session /talk opens run on the rung that the chunk's todo.md item picks, and the judge of some
|
||||
models on another; a chunk no item routes runs on the project's model. The worker's prompts name the
|
||||
rungs it launches its reviews on. The worker's rung steps up as a chunk stays unfinished, or when
|
||||
the judge finds in the transcript an escalation trigger that fired and the worker asked for a higher
|
||||
rung. The rules are in bin/loop_claude/routing.py and bin/model_routing/ladder.py, the choice of
|
||||
each review's rung in bin/model_routing/review_choice.py, and the prompts' wording in
|
||||
bin/loop_claude/cycle/prompts.py. Each verdict, interrupt, quoted answer, stop and
|
||||
step-up in the archive ends with a Worker: line, the route as JSON (Route.worker_line in
|
||||
bin/model_routing/route.py); a rerun resumes an open chunk on the latest route named there. A
|
||||
todo.md or an archive that cannot be read or parsed is said on stderr, and the chunk is routed
|
||||
without it.
|
||||
|
||||
The judge of a model listed in JUDGE_REPLAYED (bin/loop_claude/routing.py) runs on the rung the
|
||||
routed item's R + C picks from that model, never below the model's cheapest rung, and on the
|
||||
cheapest rung when no item routed the chunk. Its rung stays put when the worker steps up or takes in
|
||||
another item. A model is listed once judge-replay found its cheapest rung returning every verdict
|
||||
the reference judge reproduced. Any other model's judge runs at the effort its settings give.
|
||||
|
||||
Counting the cycles a verdict closed across all projects in the archive, the first loop to close
|
||||
one 20 or more cycles after the last measurement measures every finished chunk there, with no model
|
||||
run: tokens by project, subagent type, rung and the tool whose results they took in, and, for each
|
||||
chunk a todo.md item routed, grouped by the rung it started on: its review rounds past each pass's
|
||||
first, its unfinished verdicts and its subagents' rungs. It writes them to routing-figures.md at the archive's root. They call for a
|
||||
routing change when chunks routed onto a rung took more review rounds or unfinished verdicts than
|
||||
chunks routed onto the next rung up, each rung with 5 chunks or more, or when the reports of 5 or
|
||||
more subagents of one type were longer than the tool results they read. Each call not raised before
|
||||
is an interrupt: claude, on the project's model, on the terminal in ~/.claude, asked to put the
|
||||
calls to the human. Once that claude ends, the calls are listed in routing-calls-raised.md beside the
|
||||
figures, and not raised again. Off a terminal, the calls are said on stderr, the loop goes on, and
|
||||
they are raised again at the next measurement. A line `- <UTC time> Reset` in
|
||||
routing-calls-raised.md restarts both: the figures count only chunks that finished after it, and a
|
||||
call raised before it may be raised again. A chunk that cannot be read is skipped and named in the
|
||||
figures; figures that cannot be measured or written are said on stderr, and the loop goes on.
|
||||
Once 20 cycles have closed across all projects in the archive since the last measurement, the next
|
||||
loop to close one measures every finished chunk there, with no model run, and writes
|
||||
routing-figures.md at the archive's root (bin/routing_figures/measure.py). Each call the figures
|
||||
make for a routing change, unless raised before, is an interrupt: claude, on the project's model,
|
||||
on the terminal in ~/.claude, asked to put the calls to the human. Once that claude ends, the calls
|
||||
are listed in routing-calls-raised.md beside the figures, and not raised again. Off a terminal, the
|
||||
calls are said on stderr, the loop goes on, and they are raised again at the next measurement.
|
||||
|
||||
A change to bin/loop-claude or any bin/**/*.py takes effect at the next cycle boundary, once
|
||||
loop-claude --help succeeds: the loop reloads into the edited script.
|
||||
@@ -108,9 +92,8 @@ Exit 1, saying why, when:
|
||||
- the worker or the judge fails three times running, retried a minute apart within the cycle. A
|
||||
worker fails when claude cannot start, exits non-zero, is killed, or ends without a result event;
|
||||
a judge when claude cannot start, exits non-zero or prints no json reply, or its reply misses or
|
||||
mistypes a field, interrupts or quotes an answer without a question, gives an unfinished verdict
|
||||
an R + C outside 0 to 20, or quotes a passage the transcript does not hold; it holds an elided
|
||||
passage when each fragment appears in order.
|
||||
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
|
||||
@@ -119,7 +102,8 @@ Exit 1, saying why, when:
|
||||
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
|
||||
- an interrupt's answer is empty, or the input ends before one is typed
|
||||
- the claude opened for /talk, or for a release ready to cut, ends with nothing typed
|
||||
Rerunning resumes any open session.
|
||||
|
||||
"""
|
||||
@@ -128,16 +112,18 @@ import pathlib
|
||||
import sys
|
||||
import typing
|
||||
|
||||
from loop_claude.routing import after_unfinished, first_route, kept, routed_item
|
||||
from transcript_archive.write import archive
|
||||
from transcript_archive.location import archive_root, project_archive
|
||||
from loop_claude.loop.routing_check import check_routing
|
||||
from loop_claude.project.checkout import checkout_root
|
||||
from loop_claude.cycle.run import Cycle, run_cycle
|
||||
from loop_claude.cycle.run import Concluded, Cycle, run_cycle
|
||||
from loop_claude.loop.reload import decode_handed, exec_if_edited, fingerprint, LoopRun, RELOAD_FLAG
|
||||
from chunk_pick import default_plan, DefaultPlan
|
||||
from git_repo import default_ref
|
||||
from loop_claude.effects import Effects
|
||||
from failure import Failure
|
||||
from loop_claude.cycle.judge import Finished, Unfinished
|
||||
from loop_claude.routing import first_route, kept, routed_item, stepped
|
||||
from loop_claude.verdicts import Finished, Unfinished
|
||||
from loop_claude.project.model_choice import get_or_ask_models
|
||||
from todo_table import Item
|
||||
from transcript_archive.read import latest_worker
|
||||
@@ -145,12 +131,16 @@ from transcript_archive import outcomes
|
||||
from loop_claude.paths import Paths
|
||||
from project_key import project_key
|
||||
from model_routing.ladder import project_rung, Rung
|
||||
from loop_claude.cycle import prompts
|
||||
from loop_claude.project.premises import read_premises
|
||||
from loop_claude.project.records import read_records
|
||||
from model_routing.route import Route, route_from
|
||||
from claude_code.session import Session, session_named, transcript_file
|
||||
from claude_code.session import Session, session_named, session_open, transcript_file
|
||||
from loop_claude.stop import Stop
|
||||
|
||||
# Seconds routing waits for origin to name its default branch, asked only where the checkout records none; past them, the chunk runs on the project's rung.
|
||||
ORIGIN_TIMEOUT = 60
|
||||
|
||||
|
||||
def main(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher: pathlib.Path, cwd: pathlib.Path, effects: Effects) -> int:
|
||||
try:
|
||||
@@ -184,43 +174,51 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc
|
||||
models = get_or_ask_models(key, paths, env, effects)
|
||||
if isinstance(models, Stop):
|
||||
return models
|
||||
anchor = project_rung(models.worker)
|
||||
root = loop_run.root
|
||||
loop_run = routed(loop_run, anchor, lambda: archived_route(archive_folder, session), lambda: plan_item(root))
|
||||
route = loop_run.route or Route(Rung(models.worker))
|
||||
# After the reads above, so a loop that stops on one makes no worktree.
|
||||
facts, item = chunk_start(session, launcher.with_name("chunk-preflight"), loop_run.root, effects)
|
||||
project = project_rung(models.worker)
|
||||
route = routed(loop_run.route, project, models.worker, lambda: archived_route(archive_folder, session), item)
|
||||
print(f"\n=== cycle {loop_run.cycle_number}, worker on {route.rung} ===", flush=True)
|
||||
verdict = run_cycle(Cycle(anchor=anchor, effects=effects, judge_model=models.judge, paths=paths, premises=premises, project_archive=archive_folder, records=records, root=loop_run.root, route=route, session=session, task=loop_run.task, unfinished_evidence=loop_run.unfinished_evidence))
|
||||
if isinstance(verdict, Stop):
|
||||
return verdict
|
||||
before, loop_run = loop_run.route, after_verdict(loop_run, anchor, verdict)
|
||||
if stop := archive_step(archive_folder, session, loop_run, before, effects):
|
||||
concluded = run_cycle(Cycle(effects=effects, facts=facts, judge_model=models.judge, paths=paths, premises=premises, project=project, project_archive=archive_folder, records=records, root=loop_run.root, route=route, session=session, task=loop_run.task, unfinished_evidence=loop_run.unfinished_evidence))
|
||||
if isinstance(concluded, Stop):
|
||||
return concluded
|
||||
loop_run = after_verdict(loop_run, project, concluded)
|
||||
if stop := archive_step(archive_folder, session, loop_run.task, concluded.route, loop_run.route, effects):
|
||||
return stop
|
||||
if stop := check_routing(archive_root(paths.home, env), anchor or Rung(models.worker), paths, effects):
|
||||
if stop := check_routing(archive_root(paths.home, env), project or Rung(models.worker), paths, effects):
|
||||
return stop
|
||||
|
||||
|
||||
def routed(loop_run: LoopRun, anchor: Rung | None, archived: typing.Callable[[], Route | None], item: typing.Callable[[], Item | None]) -> LoopRun:
|
||||
"""The loop run with its chunk's route, or None when the project's model is off the ladder. A chunk keeps its route, or on a rerun the one its archive last names,
|
||||
while that is at or above the rung its item's R + C picks from anchor, the project's rung; else the plan item routes it afresh."""
|
||||
if anchor is None:
|
||||
return dataclasses.replace(loop_run, route=None)
|
||||
route = loop_run.route or archived()
|
||||
return dataclasses.replace(loop_run, route=route if route and kept(route, anchor) else first_route(anchor, item()))
|
||||
def routed(route: Route | None, project: Rung | None, model: str, archived: typing.Callable[[], Route | None], item: typing.Callable[[], Item | None]) -> Route:
|
||||
"""The route the cycle runs on. project is the project's rung, and model the project's model.
|
||||
|
||||
Where project is None, the model is off the ladder, and the worker runs on it. Otherwise the chunk keeps route, or on a rerun the route its archive last names, as routing.kept allows. Else the plan item routes the chunk afresh.
|
||||
"""
|
||||
if project is None:
|
||||
return Route(Rung(model))
|
||||
route = route or archived()
|
||||
return route if route and kept(route, project) else first_route(project, item())
|
||||
|
||||
|
||||
def after_verdict(loop_run: LoopRun, anchor: Rung | None, verdict: Finished | Unfinished) -> LoopRun:
|
||||
def after_verdict(loop_run: LoopRun, project: Rung | None, concluded: Concluded) -> LoopRun:
|
||||
"""The loop run the next cycle starts from. A finished chunk drops its route. An unfinished one takes the route stepped_route makes, and the evidence the judge gave for the verdict."""
|
||||
verdict = concluded.verdict
|
||||
if isinstance(verdict, Finished):
|
||||
return dataclasses.replace(loop_run, route=None, unfinished_evidence="")
|
||||
route = stepped(anchor, loop_run.route, verdict.bundled, bool(verdict.escalation)) if anchor and loop_run.route else loop_run.route
|
||||
return dataclasses.replace(loop_run, route=route, unfinished_evidence=verdict.evidence)
|
||||
return dataclasses.replace(loop_run, route=stepped_route(project, concluded.route, verdict), unfinished_evidence=verdict.evidence)
|
||||
|
||||
|
||||
def archive_step(archive_folder: pathlib.Path, session: Session, loop_run: LoopRun, before: Route | None, effects: Effects) -> Stop | None:
|
||||
"""Archives the rung an unfinished verdict stepped the chunk up to; the verdict itself names the rung its cycle ran on."""
|
||||
if not (before and loop_run.route) or loop_run.route.rung == before.rung:
|
||||
def stepped_route(project: Rung | None, ended_on: Route, verdict: Unfinished) -> Route:
|
||||
"""The route an unfinished chunk's next cycle starts on: the route after_unfinished makes of the route its cycle ended on, which an interrupt's or a quoted answer's escalation may have raised. Off the ladder there is no rung to step, and it keeps that route."""
|
||||
return after_unfinished(project, ended_on, verdict) if project else ended_on
|
||||
|
||||
|
||||
def archive_step(archive_folder: pathlib.Path, session: Session, task: str, before: Route, after: Route | None, effects: Effects) -> Stop | None:
|
||||
"""Archives the route after an unfinished verdict as a step-up, where its worker line differs from the one before it: a higher rung, or a higher E + I taken in. The verdict itself names the route before, which its cycle ran on."""
|
||||
if after is None or after.worker_line() == before.worker_line():
|
||||
return None
|
||||
path = transcript_file(session)
|
||||
failure = archive(archive_folder, path, loop_run.task, outcomes.stepped_up(str(loop_run.route)), effects.now()) if path else None
|
||||
failure = archive(archive_folder, path, task, outcomes.stepped_up(after.worker_line()), effects.now()) if path else None
|
||||
return Stop(1, failure.reason) if failure else None
|
||||
|
||||
|
||||
@@ -231,17 +229,40 @@ def archived_route(archive_folder: pathlib.Path, session: Session) -> Route | No
|
||||
if isinstance(worker, Failure):
|
||||
print(f"routing the chunk afresh: {worker.reason}", file=sys.stderr)
|
||||
return None
|
||||
return route_from(worker) if worker else None
|
||||
route = route_from(worker) if worker else None
|
||||
if worker and route is None:
|
||||
print(f"routing the chunk afresh: the archive's latest Worker: line names no route loop-claude can read: {worker}", file=sys.stderr)
|
||||
return route
|
||||
|
||||
|
||||
def plan_item(root: str) -> Item | None:
|
||||
"""The item that routes a chunk; None without one, so the chunk runs on the project's rung."""
|
||||
try:
|
||||
item = routed_item(pathlib.Path(root, "todo.md").read_text(encoding="utf-8"))
|
||||
except FileNotFoundError:
|
||||
return None
|
||||
except (OSError, ValueError) as failure:
|
||||
item = Failure(f"could not read todo.md: {failure}")
|
||||
def chunk_start(session: Session, preflight: pathlib.Path, root: str, effects: Effects) -> tuple[str, typing.Callable[[], Item | None]]:
|
||||
"""The facts for a fresh worker's prompt, empty where the session is open, and the reader of the item that routes the chunk. The reader reads the default branch as last fetched: for a fresh chunk, by the preflight that runs first; for an open session, which runs none, by whatever fetched last."""
|
||||
facts = "" if session_open(session) else chunk_facts(preflight, root, effects)
|
||||
return facts, lambda: plan_item(fetched_plan(root))
|
||||
|
||||
|
||||
def chunk_facts(preflight: pathlib.Path, root: str, effects: Effects) -> str:
|
||||
"""What chunk-preflight printed at the checkout root, for a fresh worker's prompt, or why it could not run."""
|
||||
done = effects.python([str(preflight)], root)
|
||||
if done.returncode:
|
||||
return prompts.preflight_failed(done.stderr.strip() or f"it exited {done.returncode}")
|
||||
return prompts.preflight_facts(done.stdout.strip())
|
||||
|
||||
|
||||
def fetched_plan(root: str) -> DefaultPlan | Failure:
|
||||
"""What the default branch, as last fetched, holds for routing."""
|
||||
ref = default_ref(root, ORIGIN_TIMEOUT)
|
||||
return ref if isinstance(ref, Failure) else default_plan(root, ref)
|
||||
|
||||
|
||||
def plan_item(plan: DefaultPlan | Failure) -> Item | None:
|
||||
"""The item that routes a chunk, chunk_pick.chunk_item's pick from the default branch; None without one, so the chunk runs on the project's rung."""
|
||||
if isinstance(plan, Failure):
|
||||
item: Item | Failure | None = plan
|
||||
elif isinstance(plan.todo, Failure):
|
||||
item = plan.todo
|
||||
else:
|
||||
item = routed_item(plan.todo, plan.cut)
|
||||
if isinstance(item, Failure):
|
||||
print(f"routing on the project's rung: {item.reason}", file=sys.stderr)
|
||||
return None
|
||||
|
||||
@@ -22,7 +22,7 @@ class LoopRun:
|
||||
root: str
|
||||
task: str
|
||||
unfinished_evidence: str
|
||||
# None until the chunk is routed, and where the project's model is off the ladder.
|
||||
# Set by each unfinished verdict; None before the chunk's first one, and once it finishes.
|
||||
route: Route | None = None
|
||||
|
||||
|
||||
@@ -32,24 +32,36 @@ def decode_handed(handed: str, kind: type[T]) -> T | None:
|
||||
except ValueError:
|
||||
return None
|
||||
decoded = decoded_as(fields, kind)
|
||||
return None if decoded is REJECTED else typing.cast(T, decoded)
|
||||
return None if decoded in (REJECTED, RETIRED) else typing.cast(T, decoded)
|
||||
|
||||
|
||||
REJECTED = object()
|
||||
# A dataclass handed with a field its RETIRED names: where None may stand in for it, it decodes as None.
|
||||
RETIRED = object()
|
||||
|
||||
|
||||
def decoded_as(value: object, kind: typing.Any) -> typing.Any:
|
||||
"""value as kind, or REJECTED: a dataclass from an object holding its fields, a union's first member that fits, else a value of exactly kind."""
|
||||
"""value as kind, REJECTED or RETIRED: a dataclass from an object holding its fields, a union's first member that fits, else a value of exactly kind."""
|
||||
if isinstance(kind, types.UnionType):
|
||||
return next((found for option in typing.get_args(kind) if (found := decoded_as(value, option)) is not REJECTED), REJECTED)
|
||||
found = [decoded_as(value, option) for option in typing.get_args(kind)]
|
||||
fits = [each for each in found if each is not REJECTED and each is not RETIRED]
|
||||
if fits:
|
||||
return fits[0]
|
||||
return None if RETIRED in found and type(None) in typing.get_args(kind) else REJECTED
|
||||
if isinstance(kind, type) and dataclasses.is_dataclass(kind):
|
||||
shape = typing.get_type_hints(kind)
|
||||
if isinstance(value, dict) and value.keys() & getattr(kind, "RETIRED", frozenset()):
|
||||
return RETIRED
|
||||
hints = typing.get_type_hints(kind)
|
||||
shape = {field.name: hints[field.name] for field in dataclasses.fields(kind)}
|
||||
# A field with a default may be missing, so a field added since the running script started does not stop the loop.
|
||||
required = {field.name for field in dataclasses.fields(kind) if field.default is dataclasses.MISSING and field.default_factory is dataclasses.MISSING}
|
||||
if not isinstance(value, dict) or not required <= value.keys() <= shape.keys():
|
||||
return REJECTED
|
||||
fields = {name: decoded_as(field, shape[name]) for name, field in value.items()}
|
||||
return REJECTED if any(field is REJECTED for field in fields.values()) else kind(**fields)
|
||||
# A dataclass that checks its fields, as Route does, does so in a static method named fits.
|
||||
if any(field in (REJECTED, RETIRED) for field in fields.values()) or not getattr(kind, "fits", lambda _: True)(fields):
|
||||
return REJECTED
|
||||
return kind(**fields)
|
||||
return value if type(value) is kind else REJECTED
|
||||
|
||||
|
||||
@@ -68,11 +80,11 @@ def fingerprint(launcher: pathlib.Path) -> str:
|
||||
def exec_if_edited(launcher: pathlib.Path, baseline: str, loop_run: LoopRun, effects: Effects) -> Stop | None:
|
||||
if fingerprint(launcher) == baseline:
|
||||
return None
|
||||
trial = effects.python([str(launcher), "--help"], loop_run.root)
|
||||
if trial.returncode != 0:
|
||||
print(f"keeping the running script: {trial.stderr.strip() or f'exit {trial.returncode}'}", file=sys.stderr)
|
||||
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>")
|
||||
|
||||
@@ -50,8 +50,8 @@ def raise_calls(root: pathlib.Path, new: list[str], rung: Rung, paths: Paths, ef
|
||||
if not effects.on_terminal():
|
||||
print("Not on a terminal: the calls are raised again at the next measurement.", file=sys.stderr)
|
||||
return None
|
||||
prompt = f"Put these calls for a routing change from loop-claude's figures to the human, and change nothing until they answer:\n{listed}The figures are in {root / archive.FIGURES}. The ladder, its bands and the delegation rule are docs/decisions.md → `routing:`, and a change to them is the human's. Record what they decide as ~/.claude/CLAUDE.md says; the next chunk of this repo files the plan item for these calls."
|
||||
if unstarted := hand_over(rung, [prompt], str(paths.claude_dir), paths, effects):
|
||||
prompt = f"Put these calls for a routing change from loop-claude's figures to the human, and change nothing until they answer:\n{listed}The figures are in {root / archive.FIGURES}. The ladder, its steps and the delegation rule are docs/decisions.md → `routing:`, and a change to them is the human's. Record what they decide as ~/.claude/CLAUDE.md says; the next chunk of this repo files the plan item for these calls."
|
||||
if unstarted := hand_over(rung, [prompt], str(paths.claude_dir), paths, {}, effects):
|
||||
return Stop(1, f"could not start claude for the routing calls: {unstarted.reason}")
|
||||
# Raised once the human has seen them, answered or not: an unanswered call reaches the plan through AGENTS.md, so it is not asked twice.
|
||||
if unmarked := archive.mark_raised(root, new, utc(effects.now())):
|
||||
|
||||
@@ -1,25 +1,17 @@
|
||||
import pathlib
|
||||
|
||||
from failure import Failure
|
||||
|
||||
from loop_claude.effects import Effects
|
||||
from loop_claude.stop import Stop
|
||||
|
||||
|
||||
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()
|
||||
found = effects.git("rev-parse", "--show-toplevel", cwd=str(cwd))
|
||||
return Stop(1, found.reason) if isinstance(found, Failure) else found.strip()
|
||||
|
||||
|
||||
def worktrees(root: str, effects: Effects) -> list[str]:
|
||||
found = [root]
|
||||
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))
|
||||
listing = effects.git("worktree", "list", "--porcelain", cwd=root)
|
||||
listed = [] if isinstance(listing, Failure) else [line.split(" ", 1)[1] for line in listing.splitlines() if line.startswith("worktree ")]
|
||||
return sorted({root, *listed})
|
||||
|
||||
+74
-46
@@ -1,9 +1,20 @@
|
||||
"""Which ladder rung a chunk's worker and judge run on: docs/decisions.md → `routing:`."""
|
||||
"""Which ladder rung a chunk's worker and judge run on: docs/decisions.md → `routing:`.
|
||||
|
||||
The worker, and the session /talk opens, run on a Route (model_routing/route.py). A model off the ladder gets a route without an item, and it is never stepped.
|
||||
|
||||
- Start. routed_item finds the plan item that routes a fresh chunk, if there is one with L, E and I scored; first_route picks the worker's rung from its L, or the project's rung without an item.
|
||||
- Rerun. kept decides whether a rerun resumes the route its archive last names.
|
||||
- Step-up. after_unfinished raises the route after an unfinished verdict, after_ruling after an interrupt or a quoted answer that carries an escalation; escalation_cap bounds an escalation, and loop_claude/escalation_mark.py states the escalation mark's rule.
|
||||
- Judge. judge_rung picks the rung of the judge of a JUDGE_REPLAYED model.
|
||||
"""
|
||||
import dataclasses
|
||||
|
||||
from model_routing.ladder import climbed, highest, LADDER, picked, position, project_rung, Rung, stepped_up
|
||||
from chunk_pick import chunk_item, LastCut, Next
|
||||
from model_routing.ladder import climbed, highest, LADDER, position, project_rung, review_floor, Rung, stepped_up, worker_rung
|
||||
from loop_claude import escalation_mark
|
||||
from failure import Failure
|
||||
from todo_table import Item, items, waiting
|
||||
from loop_claude.verdicts import Interrupt, QuotedAnswer, Unfinished
|
||||
from todo_table import Item, items, NoItemsTable
|
||||
from model_routing.route import Route
|
||||
|
||||
UNFINISHED_PER_STEP = 2
|
||||
@@ -13,82 +24,99 @@ ESCALATION_CAP = 2
|
||||
JUDGE_REPLAYED = ("claude-opus-5-5",)
|
||||
|
||||
|
||||
def routed_item(todo: str) -> Item | Failure | None:
|
||||
"""The next release's first row that does not wait, as todo_table.waiting says, in the table's order; None when there is none, or it has no C."""
|
||||
def routed_item(todo: str, cut: LastCut) -> Item | Failure | None:
|
||||
"""The item chunk_pick.chunk_item picks from todo.md, weighed against the last cut; None when there is none, or it lacks L, E or I."""
|
||||
found = items(todo)
|
||||
if isinstance(found, Failure) or not found:
|
||||
return found if isinstance(found, Failure) else None
|
||||
next_release = min(item.release for item in found)
|
||||
waits = waiting(found)
|
||||
takes = next((item for item in found if item.release == next_release and item.id not in waits), None)
|
||||
return takes if takes and takes.risk_and_complexity else None
|
||||
if isinstance(found, NoItemsTable):
|
||||
return None
|
||||
if isinstance(found, Failure):
|
||||
return found
|
||||
pick = chunk_item(found, cut)
|
||||
takes = pick.item if isinstance(pick, Next) else None
|
||||
return takes if takes and takes.likelihood and takes.escape_and_impact else None
|
||||
|
||||
|
||||
def first_route(anchor: Rung, item: Item | None) -> Route:
|
||||
"""The route a chunk starts on: the rung its item's R + C picks from anchor, the project's rung."""
|
||||
def first_route(project: Rung, item: Item | None) -> Route:
|
||||
"""The route a chunk starts on: the rung its item's L picks from the project's rung, or the project's rung without an item."""
|
||||
if item is None:
|
||||
return Route(anchor)
|
||||
return Route(picked(anchor, item.risk_and_complexity), item.id, item.risk_and_complexity)
|
||||
return Route(project)
|
||||
return Route(worker_rung(project, item.likelihood), item.id, item.likelihood, item.escape_and_impact)
|
||||
|
||||
|
||||
def kept(route: Route, anchor: Rung) -> bool:
|
||||
def kept(route: Route, project: Rung) -> bool:
|
||||
"""Whether a chunk keeps route: its rung is on the ladder and at or above item_rung."""
|
||||
return kept_rung(anchor, route) == route.rung
|
||||
return kept_rung(project, route) == route.rung
|
||||
|
||||
|
||||
def kept_rung(anchor: Rung, route: Route) -> Rung:
|
||||
def kept_rung(project: Rung, route: Route) -> Rung:
|
||||
"""The route's rung, raised to item_rung where it is lower or off the ladder."""
|
||||
return highest(route.rung, item_rung(anchor, route))
|
||||
return highest(route.rung, item_rung(project, route))
|
||||
|
||||
|
||||
def item_rung(anchor: Rung, route: Route) -> Rung:
|
||||
"""The rung the route's item's R + C picks from anchor, the project's rung, or anchor itself when no item routed it. The worker may run on a rung below anchor."""
|
||||
return picked(anchor, route.risk_and_complexity) if route.item else anchor
|
||||
def item_rung(project: Rung, route: Route) -> Rung:
|
||||
"""The rung the route's item's L picks from the project's rung, or the project's rung itself when no item routed it. The worker may run on a rung below the project's."""
|
||||
return worker_rung(project, route.likelihood) if route.item else project
|
||||
|
||||
|
||||
def escalation_rungs(anchor: Rung, route: Route) -> tuple[Rung, ...]:
|
||||
def escalation_rungs(project: Rung, route: Route) -> tuple[Rung, ...]:
|
||||
"""The rungs an escalation trigger opens to the worker, least competent first: from one above its own up to escalation_cap; none off the ladder."""
|
||||
if route.rung not in LADDER:
|
||||
return ()
|
||||
return LADDER[position(route.rung) + 1:position(escalation_cap(anchor, route)) + 1]
|
||||
return LADDER[position(route.rung) + 1:position(escalation_cap(project, route)) + 1]
|
||||
|
||||
|
||||
def escalation_cap(anchor: Rung, route: Route) -> Rung:
|
||||
def escalation_cap(project: Rung, route: Route) -> Rung:
|
||||
"""The highest rung an escalation trigger takes the worker or a task to without the human's yes: docs/decisions.md → `routing: a worker hands a task one rung up`.
|
||||
|
||||
It counts from item_rung, the rung the chunk started on, so a step-up between cycles narrows what the worker may climb without a yes, and never widens it.
|
||||
"""
|
||||
return climbed(item_rung(anchor, route), ESCALATION_CAP)
|
||||
return climbed(item_rung(project, route), ESCALATION_CAP)
|
||||
|
||||
|
||||
def stepped(anchor: Rung, route: Route, bundled: int, escalated: bool) -> Route:
|
||||
"""The route after one more unfinished verdict, never on a lower rung.
|
||||
def after_unfinished(project: Rung, route: Route, verdict: Unfinished) -> Route:
|
||||
"""The route the next cycle runs on after an unfinished verdict.
|
||||
|
||||
bundled and escalated are the verdict's fields, not the verdict, since loop_claude.cycle.judge imports this module through prompts.
|
||||
Its rung never falls. It first rises to the rung that the verdict's highest L taken in picks, where that is higher. From there it steps one rung up on every second unfinished verdict, or on an escalation while below escalation_cap; where both fall on one verdict, it steps once. A step on an escalation moves the mark, as loop_claude/escalation_mark.py says; a step on the count of unfinished verdicts alone keeps it. Last, the route takes in the verdict's highest E + I, as Route.taking_in does.
|
||||
"""
|
||||
rung = taken_in(anchor, route, bundled)
|
||||
unfinished = route.unfinished + 1
|
||||
counted_out = unfinished >= UNFINISHED_PER_STEP
|
||||
# The judge found the escalation trigger the worker cited in asking for a higher rung.
|
||||
escalates = escalated and position(rung) < position(escalation_cap(anchor, route))
|
||||
if counted_out or escalates:
|
||||
return dataclasses.replace(route, rung=stepped_up(rung), unfinished=0)
|
||||
return dataclasses.replace(route, rung=rung, unfinished=unfinished)
|
||||
rung = raised(project, route, verdict.highest_likelihood_taken_in)
|
||||
mark = escalation_mark.moved_to(verdict)
|
||||
if route.unfinished + 1 >= UNFINISHED_PER_STEP or (mark is not None and below_cap(project, route, rung)):
|
||||
after = one_rung_up(route, rung, route.escalated_at if mark is None else mark)
|
||||
else:
|
||||
after = dataclasses.replace(route, rung=rung, unfinished=route.unfinished + 1)
|
||||
return after.taking_in(verdict.highest_escape_and_impact_taken_in)
|
||||
|
||||
|
||||
def taken_in(anchor: Rung, route: Route, bundled: int) -> Rung:
|
||||
"""kept_rung, raised to the rung bundled picks from anchor; bundled is the highest R + C the judge saw the worker take into the chunk, 0 for none."""
|
||||
return highest(kept_rung(anchor, route), picked(anchor, bundled)) if bundled else kept_rung(anchor, route)
|
||||
def after_ruling(project: Rung, route: Route, verdict: Interrupt | QuotedAnswer) -> Route:
|
||||
"""The route after the judge's interrupt or quoted answer: unchanged without an escalation. With one, raised to the rung the highest L taken in picks, and one rung up from there while below escalation_cap, moving the mark as after_unfinished does. Neither is an unfinished verdict, so the count of those restarts only with a step."""
|
||||
mark = escalation_mark.moved_to(verdict)
|
||||
if mark is None:
|
||||
return route
|
||||
rung = raised(project, route, verdict.highest_likelihood_taken_in)
|
||||
return one_rung_up(route, rung, mark) if below_cap(project, route, rung) else dataclasses.replace(route, rung=rung)
|
||||
|
||||
|
||||
def one_rung_up(route: Route, rung: Rung, escalated_at: int) -> Route:
|
||||
"""The route one rung above rung, with the count of unfinished verdicts restarted and the mark at escalated_at."""
|
||||
return dataclasses.replace(route, rung=stepped_up(rung), unfinished=0, escalated_at=escalated_at)
|
||||
|
||||
|
||||
def below_cap(project: Rung, route: Route, rung: Rung) -> bool:
|
||||
"""Whether an escalation trigger may take the worker one rung up from rung without the human's yes: rung is below escalation_cap, two rungs above item_rung."""
|
||||
return position(rung) < position(escalation_cap(project, route))
|
||||
|
||||
|
||||
def raised(project: Rung, route: Route, likelihood_taken_in: int) -> Rung:
|
||||
"""kept_rung, raised to the rung that likelihood_taken_in picks from project. likelihood_taken_in is the highest L the worker took into the chunk, or 0 for none."""
|
||||
return highest(kept_rung(project, route), worker_rung(project, likelihood_taken_in)) if likelihood_taken_in else kept_rung(project, route)
|
||||
|
||||
|
||||
def judge_rung(judge_model: str, route: Route) -> Rung:
|
||||
"""The rung the route's item picks, counted from the judge model's cheapest rung and never below it, whatever rung the worker stepped to.
|
||||
|
||||
An item the worker takes in beyond the routed one lifts the worker's rung, through taken_in, but not the judge's, until todo.md item 153 lifts the judge too.
|
||||
"""The rung the route's reviewed_on E + I picks for a review, counted from the judge model's cheapest rung and never below it, whatever rung the worker stepped to.
|
||||
|
||||
A model off the ladder, or not in JUDGE_REPLAYED, gets no effort flag, so claude runs it at the effort its settings give.
|
||||
"""
|
||||
anchor = project_rung(judge_model)
|
||||
if anchor is None or judge_model not in JUDGE_REPLAYED:
|
||||
cheapest = project_rung(judge_model)
|
||||
if cheapest is None or judge_model not in JUDGE_REPLAYED:
|
||||
return Rung(judge_model)
|
||||
return highest(anchor, item_rung(anchor, route))
|
||||
return review_floor(cheapest, route.reviewed_on())
|
||||
|
||||
@@ -21,6 +21,10 @@ from test_env import isolated_env
|
||||
|
||||
BIN = pathlib.Path(__file__).resolve().parents[1]
|
||||
TASK = "Do the next chunk."
|
||||
# How the archive records a worker that runs off the ladder.
|
||||
OFF_LADDER = '{"model": "worker-model"}'
|
||||
# How a reload hands that worker's route.
|
||||
OFF_LADDER_ROUTE = {"rung": {"model": "worker-model", "effort": ""}, "item": 0, "likelihood": 0, "escape_and_impact": 0, "unfinished": 0, "escape_and_impact_taken_in": 0, "escalated_at": 0}
|
||||
|
||||
|
||||
# Plays claude from FAKE_CLAUDE_SCENARIO, one step per call, logging each call; a step for another role,
|
||||
@@ -115,16 +119,22 @@ if os.path.basename(sys.argv[0]) == "loop-claude":
|
||||
"""
|
||||
|
||||
PREMISES = "# Project\n\n## Goals\n\n1. Work.\n\n## Audience\n\nMe.\n"
|
||||
# Item 4's R + C of 11 steps one rung up from the project's.
|
||||
TODO = "## Items\n\n| ID | Release | Exempt | Item | R | S | C | A | G | Goals | Score |\n|---|---|---|---|---|---|---|---|---|---|---|\n| 4 | 0.1.0 | | **Do it.** | 5 | 2 | 6 | 8 | 9 | 1 | 25 |\n"
|
||||
# Item 4's L of 4 steps one rung up from the project's.
|
||||
TODO = "## Items\n\n| ID | Release | Exempt | Item | L | E | I | R | S | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|---|\n| 4 | 0.1.0 | | **Do it.** | 4 | 2 | 3 | 7 | 2 | 1 by 9 | 25 |\n"
|
||||
# Item 4's L of 2 steps one rung down.
|
||||
CHEAP = TODO.replace("| 4 | 2 | 3 | 7 |", "| 2 | 1 | 2 | 3 |")
|
||||
|
||||
|
||||
# Waits for the interrupt's prompt before typing the answer, since loop-claude drops what was typed before it.
|
||||
ANSWERING = ("Answer (", lambda: None)
|
||||
|
||||
|
||||
def worker(**step):
|
||||
return {"role": "worker", **step}
|
||||
|
||||
|
||||
def judge(interrupt=False, finished=False, evidence="working", question="", bundled=0, escalation="", **step):
|
||||
verdict = {"answer": "", "bundled": bundled, "escalation": escalation, "evidence": evidence, "finished": finished, "interrupt": interrupt, "question": question}
|
||||
def judge(interrupt=False, finished=False, evidence="working", question="", highest_likelihood_taken_in=0, highest_escape_and_impact_taken_in=0, escalation="", release_ready=False, **step):
|
||||
verdict = {"answer": "", "highest_likelihood_taken_in": highest_likelihood_taken_in, "highest_escape_and_impact_taken_in": highest_escape_and_impact_taken_in, "escalation": escalation, "evidence": evidence, "finished": finished, "interrupt": interrupt, "question": question, "release_ready": release_ready}
|
||||
return {"role": "judge", "verdict": verdict, **step}
|
||||
|
||||
|
||||
@@ -188,7 +198,13 @@ class Checkout:
|
||||
def git(self, *args):
|
||||
subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@example.com", *args], capture_output=True, check=True, cwd=self.root, env=self.env)
|
||||
|
||||
def run(self, steps, argv=(TASK,), cwd=None, terminal_input=None, stdout_on_terminal=True, before_typing=None):
|
||||
def commit_plan(self, todo):
|
||||
"""Commits todo as todo.md on the checkout's branch, the default branch routing reads it from."""
|
||||
(self.root / "todo.md").write_text(todo)
|
||||
self.git("add", "todo.md")
|
||||
self.git("commit", "--quiet", "-m", "plan")
|
||||
|
||||
def run(self, steps, argv=(TASK,), cwd=None, terminal_input=None, stdout_on_terminal=True, before_typing=None, typed_early=""):
|
||||
for name in ("FAKE_CLAUDE_LOG", "LOOP_TEST_LOG"):
|
||||
pathlib.Path(self.env[name]).unlink(missing_ok=True)
|
||||
pathlib.Path(self.env["FAKE_CLAUDE_SCENARIO"]).write_text(json.dumps(steps))
|
||||
@@ -198,7 +214,7 @@ class Checkout:
|
||||
done = subprocess.run(command, capture_output=True, cwd=cwd, env=self.env, stdin=subprocess.DEVNULL, text=True, timeout=60)
|
||||
code, stdout, stderr = done.returncode, done.stdout, done.stderr
|
||||
else:
|
||||
code, stdout, stderr = self.run_on_terminal(command, cwd, terminal_input, stdout_on_terminal, before_typing)
|
||||
code, stdout, stderr = self.run_on_terminal(command, cwd, terminal_input, stdout_on_terminal, before_typing, typed_early)
|
||||
started = lines(pathlib.Path(self.env["LOOP_TEST_LOG"]))
|
||||
return Run(
|
||||
calls=lines(pathlib.Path(self.env["FAKE_CLAUDE_LOG"])),
|
||||
@@ -209,8 +225,8 @@ class Checkout:
|
||||
stdout=stdout,
|
||||
)
|
||||
|
||||
def run_on_terminal(self, command, cwd, typed, stdout_on_terminal, before_typing):
|
||||
"""Types the input at once, or once stderr shows before_typing's text and its callback has run."""
|
||||
def run_on_terminal(self, command, cwd, typed, stdout_on_terminal, before_typing, typed_early):
|
||||
"""Types typed_early at once, then the input at once, or once stderr shows before_typing's text and its callback has run."""
|
||||
controller, terminal = pty.openpty()
|
||||
with tempfile.TemporaryFile() as stderr, tempfile.TemporaryFile() as stdout:
|
||||
try:
|
||||
@@ -218,6 +234,7 @@ class Checkout:
|
||||
finally:
|
||||
os.close(terminal)
|
||||
try:
|
||||
os.write(controller, typed_early.encode())
|
||||
prompt, callback = before_typing or (None, None)
|
||||
if prompt is None:
|
||||
os.write(controller, typed.encode())
|
||||
@@ -314,7 +331,15 @@ class Premises(unittest.TestCase):
|
||||
(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")
|
||||
self.assertTrue(run.stderr.startswith("git rev-parse --show-toplevel could not start: "), run.stderr)
|
||||
|
||||
def test_makes_no_worktree_for_a_readme_without_premises(self):
|
||||
checkout = Checkout(self)
|
||||
checkout.commit_plan(TODO)
|
||||
(checkout.root / "README.md").write_text("# Project\n")
|
||||
run = checkout.run([worker()])
|
||||
self.assertEqual((run.code, run.calls), (1, []))
|
||||
self.assertFalse((checkout.home / "code" / "proj-item-4").exists())
|
||||
|
||||
def test_names_the_session_by_the_checkout_relative_to_code_or_else_to_the_root(self):
|
||||
checkout = Checkout(self)
|
||||
@@ -350,7 +375,8 @@ class Cycles(unittest.TestCase):
|
||||
self.assertIsNone(argument(workers[1], "--name"))
|
||||
self.assertEqual(argument(workers[2], "--session-id"), session)
|
||||
self.assertTrue(argument(workers[0], "-p").startswith(f"{TASK}\n\nContinue any open draft PR"))
|
||||
self.assertTrue(argument(workers[0], "-p").endswith("The chunk's todo.md items, or else the task above, set its scope. The goals below choose between ways to deliver that scope, and never widen it.\n\nFrom README.md:\n## Goals\n1. Work.\n\n## Audience\nMe."))
|
||||
self.assertTrue(argument(workers[0], "-p").endswith("The chunk's todo.md items, or else the task above, set its scope. The goals below, " 'which rank after code health (~/.claude/CLAUDE.md → "Shared goal") unless README.md voids it' ", choose between ways to deliver that scope, and never widen it.\n\nFrom README.md:\n## Goals\n1. Work.\n\n## Audience\nMe."))
|
||||
self.assertIn("main or master", argument(workers[0], "-p"))
|
||||
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"))
|
||||
@@ -364,41 +390,65 @@ class Cycles(unittest.TestCase):
|
||||
self.assertEqual([path.name for path in checkout.transcripts()[0].parent.iterdir()], [checkout.transcripts()[0].name])
|
||||
self.assertIn("=== cycle 3, worker on worker-model ===", run.stdout)
|
||||
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\nWorker: worker-model\n", "<UTC> Verdict: finished\n\nEvidence:\n> landed-it\n\nJudge: judge-model\nWorker: worker-model\n", "<UTC> Verdict: unfinished\n\nEvidence:\n> started\n\nJudge: judge-model\nWorker: worker-model\n"])
|
||||
self.assertIn('"text": "landed-it"', copies["<UTC> Verdict: finished\n\nEvidence:\n> landed-it\n\nJudge: judge-model\nWorker: worker-model\n"])
|
||||
self.assertIn('"text": "next chunk"', copies["<UTC> Stopped: Ctrl-C\n\nWorker: worker-model\n"])
|
||||
self.assertEqual(sorted(copies), [f"<UTC> Stopped: Ctrl-C\n\nWorker: {OFF_LADDER}\n", f"<UTC> Verdict: finished\n\nEvidence:\n> landed-it\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n", f"<UTC> Verdict: unfinished\n\nEvidence:\n> started\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n"])
|
||||
self.assertIn('"text": "landed-it"', copies[f"<UTC> Verdict: finished\n\nEvidence:\n> landed-it\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n"])
|
||||
self.assertIn('"text": "next chunk"', copies[f"<UTC> Stopped: Ctrl-C\n\nWorker: {OFF_LADDER}\n"])
|
||||
self.assertEqual(len(list(checkout.archive().glob(f"proj/*/session/{session}.orphaned-1-ab.jsonl"))), 1)
|
||||
|
||||
def test_routes_the_worker_by_its_items_r_plus_c_and_steps_it_up_within_the_chunk(self):
|
||||
def test_routes_the_worker_by_its_items_l_and_steps_it_up_within_the_chunk(self):
|
||||
checkout = Checkout(self)
|
||||
checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = "claude-opus-5-5"
|
||||
(checkout.root / "todo.md").write_text(TODO)
|
||||
checkout.commit_plan(CHEAP)
|
||||
run = checkout.run([
|
||||
worker(say="one"), judge(evidence="one"),
|
||||
worker(say="two"), judge(evidence="two"),
|
||||
worker(say="three"), judge(evidence="three", bundled=17),
|
||||
worker(say="three"), judge(evidence="three", highest_likelihood_taken_in=4),
|
||||
worker(say="four"), judge(finished=True, evidence="four"),
|
||||
worker(say="next chunk"),
|
||||
])
|
||||
self.assertEqual(run.code, 130)
|
||||
workers = [call for call in run.calls if call["role"] == "worker"]
|
||||
self.assertEqual([(argument(call, "--model"), argument(call, "--effort")) for call in workers], [
|
||||
("claude-sonnet-5-5", "high"),
|
||||
("claude-sonnet-5-5", "high"),
|
||||
("claude-opus-5-5", "medium"),
|
||||
("claude-opus-5-5", "high"),
|
||||
("claude-opus-5-5", "high"),
|
||||
("claude-opus-5-5", "xhigh"),
|
||||
("claude-fable-5-1", "max"),
|
||||
("claude-opus-5-5", "high"),
|
||||
("claude-sonnet-5-5", "high"),
|
||||
])
|
||||
self.assertEqual({(argument(call, "--model"), argument(call, "--effort")) for call in run.calls if call["role"] == "judge"}, {("judge-model", None)})
|
||||
self.assertIn("loop-claude runs you on claude-opus-5-5 at high effort, routed by item 4's R + C of 11. Name each todo.md item this chunk takes, with its R + C, whether or not it is item 4.", argument(workers[0], "-p"))
|
||||
self.assertIn("loop-claude runs you on claude-sonnet-5-5 at high effort, routed by item 4's L of 2. Name each todo.md item this chunk takes, with its L and E + I, whether or not it is item 4.", argument(workers[0], "-p"))
|
||||
outcomes = sorted(verdict.removeprefix(f"Task: {TASK}\n\n") for verdict in checkout.archived().values())
|
||||
self.assertIn("<UTC> Verdict: unfinished\n\nEvidence:\n> three\n\nJudge: judge-model\nWorker: claude-opus-5-5 at xhigh effort, routed by item 4's R + C of 11\n\n<UTC> Stepped up\n\nWorker: claude-fable-5-1 at max effort, routed by item 4's R + C of 11\n", outcomes)
|
||||
self.assertIn("<UTC> Verdict: finished\n\nEvidence:\n> four\n\nJudge: judge-model\nWorker: claude-fable-5-1 at max effort, routed by item 4's R + C of 11\n", outcomes)
|
||||
self.assertIn('<UTC> Verdict: unfinished\n\nEvidence:\n> three\n\nJudge: judge-model\nWorker: {"model": "claude-opus-5-5", "effort": "medium", "item": 4, "likelihood": 2, "escape_and_impact": 3}\n\n<UTC> Stepped up\n\nWorker: {"model": "claude-opus-5-5", "effort": "high", "item": 4, "likelihood": 2, "escape_and_impact": 3}\n', outcomes)
|
||||
self.assertIn('<UTC> Verdict: finished\n\nEvidence:\n> four\n\nJudge: judge-model\nWorker: {"model": "claude-opus-5-5", "effort": "high", "item": 4, "likelihood": 2, "escape_and_impact": 3}\n', outcomes)
|
||||
|
||||
def test_routes_on_and_states_the_same_item_from_the_fetched_default_branch_whatever_the_checkout_holds(self):
|
||||
checkout = Checkout(self)
|
||||
checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = "claude-opus-5-5"
|
||||
origin = checkout.temp / "origin.git"
|
||||
checkout.git("init", "--quiet", "--bare", "--initial-branch=main", str(origin))
|
||||
checkout.git("symbolic-ref", "HEAD", "refs/heads/main")
|
||||
checkout.commit_plan(TODO)
|
||||
checkout.git("remote", "add", "origin", str(origin))
|
||||
checkout.git("push", "--quiet", "--set-upstream", "origin", "main")
|
||||
# Item 4 ships elsewhere, and item 6 is next; the checkout is behind origin, and holds a change of its own.
|
||||
elsewhere = checkout.temp / "elsewhere"
|
||||
checkout.git("clone", "--quiet", str(origin), str(elsewhere))
|
||||
(elsewhere / "todo.md").write_text(TODO.replace("| 4 | 0.1.0 |", "| 6 | 0.1.0 |"))
|
||||
checkout.git("-C", str(elsewhere), "commit", "--quiet", "--all", "-m", "item 4 shipped, plan item 6")
|
||||
checkout.git("-C", str(elsewhere), "push", "--quiet", "origin", "main")
|
||||
(checkout.root / "todo.md").write_text(TODO + "\nA change of the checkout's own.\n")
|
||||
(checkout.root / "sub").mkdir()
|
||||
run = checkout.run([worker()], cwd=checkout.root / "sub")
|
||||
self.assertEqual(run.code, 130)
|
||||
prompt = argument(run.calls[0], "-p")
|
||||
self.assertIn("routed by item 6's L of 4", prompt)
|
||||
self.assertIn("item 6, L 4, E + I 5", prompt)
|
||||
self.assertTrue((checkout.home / "code" / "proj-item-6").is_dir())
|
||||
|
||||
def test_steps_the_worker_up_a_rung_when_the_judge_finds_in_the_transcript_the_escalation_trigger_it_cites(self):
|
||||
checkout = Checkout(self)
|
||||
checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = "claude-opus-5-5"
|
||||
(checkout.root / "todo.md").write_text(TODO)
|
||||
checkout.commit_plan(TODO)
|
||||
run = checkout.run([
|
||||
worker(say="Stability round 2: a 🔴. Trigger 3 fired; I ask for a higher rung."), judge(evidence="I ask for a higher rung.", escalation="Stability round 2: a 🔴."),
|
||||
worker(say="Trigger 2 fired; I ask for a higher rung."), judge(evidence="I ask for a higher rung.", escalation="Trigger 2 fired; … a higher rung."),
|
||||
@@ -414,30 +464,67 @@ class Cycles(unittest.TestCase):
|
||||
("claude-opus-5-5", "high"),
|
||||
])
|
||||
outcomes = sorted(verdict.removeprefix(f"Task: {TASK}\n\n") for verdict in checkout.archived().values())
|
||||
self.assertIn("<UTC> Verdict: unfinished\n\nEvidence:\n> I ask for a higher rung.\n\nEscalation:\n> Stability round 2: a 🔴.\n\nJudge: judge-model\nWorker: claude-opus-5-5 at high effort, routed by item 4's R + C of 11\n\n<UTC> Stepped up\n\nWorker: claude-opus-5-5 at xhigh effort, routed by item 4's R + C of 11\n", outcomes)
|
||||
self.assertIn("<UTC> Verdict: unfinished\n\nEvidence:\n> I ask for a higher rung.\n\nJudge: judge-model\nWorker: claude-opus-5-5 at xhigh effort, routed by item 4's R + C of 11\n", outcomes)
|
||||
self.assertIn('<UTC> Verdict: unfinished\n\nEvidence:\n> I ask for a higher rung.\n\nEscalation:\n> Stability round 2: a 🔴.\n\nJudge: judge-model\nWorker: {"model": "claude-opus-5-5", "effort": "high", "item": 4, "likelihood": 4, "escape_and_impact": 5}\n\n<UTC> Stepped up\n\nWorker: {"model": "claude-opus-5-5", "effort": "xhigh", "item": 4, "likelihood": 4, "escape_and_impact": 5, "escalated_at": 4}\n', outcomes)
|
||||
self.assertIn('<UTC> Verdict: unfinished\n\nEvidence:\n> I ask for a higher rung.\n\nJudge: judge-model\nWorker: {"model": "claude-opus-5-5", "effort": "xhigh", "item": 4, "likelihood": 4, "escape_and_impact": 5, "escalated_at": 4}\n', outcomes)
|
||||
|
||||
def test_steps_the_worker_up_once_as_the_judge_interrupts_when_the_run_also_cites_an_escalation_trigger(self):
|
||||
checkout = Checkout(self)
|
||||
checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = "claude-opus-5-5"
|
||||
checkout.commit_plan(TODO)
|
||||
cited = "Stability round 2: a 🔴."
|
||||
run = checkout.run([
|
||||
worker(say=f"{cited} Trigger 3 fired; I ask for a higher rung. Shall I use A or B?"), judge(interrupt=True, evidence="Shall I use A or B?", question="A or B?", escalation=cited),
|
||||
interrupt(type="B"), judge(evidence="B", escalation="Trigger 3 fired; I ask for a higher rung."),
|
||||
worker(say="carrying on"),
|
||||
], terminal_input="/talk\n", before_typing=ANSWERING)
|
||||
self.assertEqual(run.code, 130)
|
||||
self.assertEqual(run.roles(), ["worker", "judge", "interrupt", "judge", "worker", "judge"])
|
||||
self.assertEqual([(argument(call, "--model"), argument(call, "--effort")) for call in run.calls if call["role"] != "judge"], [("claude-opus-5-5", "high"), ("claude-opus-5-5", "xhigh"), ("claude-opus-5-5", "xhigh")])
|
||||
outcomes = sorted(verdict.removeprefix(f"Task: {TASK}\n\n") for verdict in checkout.archived().values())
|
||||
self.assertIn('<UTC> Stepped up\n\nWorker: {"model": "claude-opus-5-5", "effort": "xhigh", "item": 4, "likelihood": 4, "escape_and_impact": 5, "escalated_at": 4}\n', "".join(outcomes))
|
||||
self.assertNotIn("at max effort", "".join(outcomes))
|
||||
self.assertIn('Verdict: interrupt\n\nA or B?\n\nEvidence:\n> Shall I use A or B?\n\nEscalation:\n> Stability round 2: a 🔴.\n\nJudge: judge-model\nWorker: {"model": "claude-opus-5-5", "effort": "high", "item": 4, "likelihood": 4, "escape_and_impact": 5}\n\n<UTC> Stepped up\n\nWorker: {"model": "claude-opus-5-5", "effort": "xhigh", "item": 4, "likelihood": 4, "escape_and_impact": 5, "escalated_at": 4}\n', "".join(outcomes))
|
||||
|
||||
def test_runs_a_cheap_items_worker_below_the_projects_rung_with_its_reviewers_and_judge_on_it(self):
|
||||
checkout = Checkout(self)
|
||||
checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = checkout.env["LOOP_CLAUDE_JUDGE_MODEL"] = "claude-opus-5-5"
|
||||
(checkout.root / "todo.md").write_text(TODO.replace("| 5 | 2 | 6 |", "| 2 | 2 | 5 |"))
|
||||
checkout.commit_plan(CHEAP)
|
||||
run = checkout.run([worker(say="one"), judge(finished=True, evidence="one"), worker(say="next chunk")])
|
||||
self.assertEqual(run.code, 130)
|
||||
first = next(call for call in run.calls if call["role"] == "worker")
|
||||
self.assertEqual((argument(first, "--model"), argument(first, "--effort")), ("claude-sonnet-5-5", "high"))
|
||||
ruling = next(call for call in run.calls if call["role"] == "judge")
|
||||
self.assertEqual((argument(ruling, "--model"), argument(ruling, "--effort")), ("claude-opus-5-5", "medium"))
|
||||
self.assertIn("Judge: claude-opus-5-5 at medium effort\nWorker: claude-sonnet-5-5 at high effort", "".join(checkout.archived().values()))
|
||||
self.assertIn("Your rung is below the project's, claude-opus-5-5 at medium effort: launch each reviewer, each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium", argument(first, "-p"))
|
||||
self.assertIn('Judge: claude-opus-5-5 at medium effort\nWorker: {"model": "claude-sonnet-5-5", "effort": "high", ', "".join(checkout.archived().values()))
|
||||
self.assertIn("Launch each reviewer, each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium, the project's rung.", argument(first, "-p"))
|
||||
|
||||
def test_routes_the_judge_and_the_reviewers_on_the_highest_e_plus_i_the_worker_takes_in(self):
|
||||
checkout = Checkout(self)
|
||||
checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = checkout.env["LOOP_CLAUDE_JUDGE_MODEL"] = "claude-opus-5-5"
|
||||
checkout.commit_plan(CHEAP)
|
||||
run = checkout.run([
|
||||
worker(say="one"), judge(evidence="one", highest_escape_and_impact_taken_in=6),
|
||||
worker(say="two"), judge(finished=True, evidence="two"),
|
||||
worker(say="next chunk"),
|
||||
])
|
||||
self.assertEqual(run.code, 130)
|
||||
self.assertEqual([argument(call, "--effort") for call in run.calls if call["role"] == "judge"], ["medium", "xhigh", "medium"])
|
||||
workers = [call for call in run.calls if call["role"] == "worker"]
|
||||
self.assertEqual({argument(call, "--effort") for call in workers}, {"high"})
|
||||
self.assertIn("Launch each reviewer with the Agent tool set to model opus, effort xhigh, the rung picked by an item of E + I 6 taken into the chunk.", argument(workers[1], "-p"))
|
||||
outcomes = "".join(checkout.archived().values())
|
||||
self.assertIn('<UTC> Stepped up\n\nWorker: {"model": "claude-sonnet-5-5", "effort": "high", "item": 4, "likelihood": 2, "escape_and_impact": 3, "escape_and_impact_taken_in": 6}\n', outcomes)
|
||||
self.assertIn('Judge: claude-opus-5-5 at xhigh effort\nWorker: {"model": "claude-sonnet-5-5", "effort": "high", "item": 4, "likelihood": 2, "escape_and_impact": 3, "escape_and_impact_taken_in": 6}\n', outcomes)
|
||||
|
||||
def test_a_rerun_resumes_an_open_chunk_on_the_rung_it_last_ran(self):
|
||||
checkout = Checkout(self)
|
||||
checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = "claude-opus-5-5"
|
||||
(checkout.root / "todo.md").write_text(TODO)
|
||||
checkout.commit_plan(TODO)
|
||||
run = checkout.run([worker(), judge(), worker(), judge()])
|
||||
self.assertEqual(run.code, 130)
|
||||
self.assertEqual(argument(run.calls[-1], "--effort"), "xhigh")
|
||||
(checkout.root / "todo.md").unlink()
|
||||
checkout.git("rm", "--quiet", "todo.md")
|
||||
checkout.git("commit", "--quiet", "-m", "drop the plan")
|
||||
run = checkout.run([worker()])
|
||||
self.assertIsNotNone(argument(run.calls[0], "--resume"))
|
||||
self.assertEqual((argument(run.calls[0], "--model"), argument(run.calls[0], "--effort")), ("claude-opus-5-5", "xhigh"))
|
||||
@@ -478,7 +565,7 @@ class Cycles(unittest.TestCase):
|
||||
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 printed no json reply; it printed: 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}}')
|
||||
self.assertEqual(run.stderr.strip().splitlines()[-1], 'the judge failed three times running: the judge\'s reply has no answer of type string')
|
||||
|
||||
def test_waits_out_a_usage_limit_which_ends_a_run_of_failures(self):
|
||||
checkout = Checkout(self)
|
||||
@@ -564,7 +651,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\n<UTC> Verdict: interrupt\n\nA or B?\n\nEvidence:\n> Shall I use A or B?\n\nJudge: judge-model\n\n<UTC> Stopped: the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal\n\nWorker: worker-model\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\nJudge: judge-model\nWorker: {OFF_LADDER}\n\n<UTC> Stopped: the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal\n\nWorker: {OFF_LADDER}\n")
|
||||
self.assertEqual(stat.S_IMODE((checkout.temp / "deep").stat().st_mode), 0o700)
|
||||
self.assertIn(f"transcript: {checkout.archive() / 'proj'}/", run.stderr)
|
||||
session = argument(run.calls[0], "--session-id")
|
||||
@@ -577,6 +664,17 @@ class Interrupt(unittest.TestCase):
|
||||
self.assertEqual(run.code, 2)
|
||||
self.assertEqual(len(checkout.archived()), 2)
|
||||
|
||||
def test_resumes_the_worker_headless_with_the_answer_typed_at_its_terminal_not_with_keys_typed_before_it(self):
|
||||
checkout = Checkout(self)
|
||||
asked = [worker(say="Shall I use A or B?"), judge(interrupt=True, evidence="Shall I use A or B?", question="A or B?")]
|
||||
run = checkout.run([*asked, worker(say="Using B."), judge(evidence="Using B.")], terminal_input="B\n", before_typing=ANSWERING, typed_early="stray\n")
|
||||
self.assertEqual(run.code, 130)
|
||||
self.assertEqual(run.roles(), ["worker", "judge", "worker", "judge", "worker"])
|
||||
self.assertIn("A or B?\nAnswer (/talk opens claude, Enter stops the loop): ", run.stderr)
|
||||
self.assertEqual(argument(run.calls[2], "--resume"), argument(run.calls[0], "--session-id"))
|
||||
self.assertIn("[human] B\n\nUsing B.", run.calls[3]["stdin"])
|
||||
self.assertNotIn("stray", run.calls[3]["stdin"])
|
||||
|
||||
def test_hands_the_terminal_over_and_exits_2_when_nothing_is_typed(self):
|
||||
checkout = Checkout(self)
|
||||
checkout.git("commit", "--allow-empty", "--quiet", "-m", "start")
|
||||
@@ -585,7 +683,7 @@ class Interrupt(unittest.TestCase):
|
||||
checkout.claude_json().chmod(0o644)
|
||||
asked = [worker(say="Shall I use A or B?"), judge(interrupt=True, evidence="Shall I use A or B?", question="A or B?")]
|
||||
(checkout.root / "sub").mkdir()
|
||||
run = checkout.run([*asked, interrupt(type="B"), judge(evidence="B"), worker()], cwd=checkout.root / "sub", terminal_input="")
|
||||
run = checkout.run([*asked, interrupt(type="B"), judge(evidence="B"), worker()], cwd=checkout.root / "sub", terminal_input="/talk\n", before_typing=ANSWERING)
|
||||
self.assertEqual(run.code, 130)
|
||||
self.assertEqual(run.roles(), ["worker", "judge", "interrupt", "judge", "worker", "judge"])
|
||||
handed = run.calls[2]["argv"]
|
||||
@@ -603,13 +701,13 @@ class Interrupt(unittest.TestCase):
|
||||
|
||||
for transcript in checkout.transcripts():
|
||||
transcript.unlink()
|
||||
run = checkout.run([*asked, interrupt()], terminal_input="")
|
||||
run = checkout.run([*asked, interrupt()], terminal_input="/talk\n", before_typing=ANSWERING)
|
||||
self.assertEqual((run.code, run.roles()), (2, ["worker", "judge", "interrupt"]))
|
||||
self.assertEqual(run.stderr.strip().splitlines()[-1], "the human is needed to answer the question above, but the interrupt ended with nothing typed")
|
||||
self.assertTrue(run.stderr.strip().endswith("the human is needed to answer the question above, but the interrupt ended with nothing typed"))
|
||||
|
||||
run = checkout.run([worker(say="A or B?"), judge(interrupt=True, evidence="A or B?", question="A or B?", vanish=True)], terminal_input="")
|
||||
run = checkout.run([worker(say="A or B?"), judge(interrupt=True, evidence="A or B?", question="A or B?", vanish=True)], terminal_input="/talk\n", before_typing=ANSWERING)
|
||||
self.assertEqual((run.code, run.roles()), (1, ["worker", "judge"]))
|
||||
self.assertEqual(run.stderr.strip().splitlines()[-1], "could not start claude for the interrupt: No such file or directory")
|
||||
self.assertTrue(run.stderr.strip().endswith("could not start claude for the interrupt: No such file or directory"))
|
||||
|
||||
def test_says_why_the_trust_file_cannot_be_read_and_leaves_it_as_it_was(self):
|
||||
checkout = Checkout(self)
|
||||
@@ -627,14 +725,14 @@ class Interrupt(unittest.TestCase):
|
||||
checkout.claude_json().unlink(missing_ok=True)
|
||||
if text is not None:
|
||||
checkout.claude_json().write_text(text)
|
||||
run = checkout.run(asked, terminal_input="")
|
||||
run = checkout.run(asked, terminal_input="/talk\n", before_typing=ANSWERING)
|
||||
self.assertEqual(run.code, 2)
|
||||
self.assertIn(f"could not read {checkout.claude_json()}: {said}\n", run.stderr)
|
||||
self.assertEqual(checkout.claude_json().read_text() if checkout.claude_json().exists() else None, text)
|
||||
|
||||
trusted = json.dumps({"projects": {str(checkout.root): {"hasTrustDialogAccepted": True}}})
|
||||
checkout.claude_json().write_text(trusted)
|
||||
run = checkout.run(asked, terminal_input="")
|
||||
run = checkout.run(asked, terminal_input="/talk\n", before_typing=ANSWERING)
|
||||
self.assertNotIn(str(checkout.claude_json()), run.stderr)
|
||||
self.assertNotIn("trusted for the interrupt", run.stderr)
|
||||
self.assertEqual(checkout.claude_json().read_text(), trusted)
|
||||
@@ -647,7 +745,7 @@ class Interrupt(unittest.TestCase):
|
||||
checkout.run(asked[:2])
|
||||
checkout.home.chmod(0o500)
|
||||
self.addCleanup(checkout.home.chmod, 0o700)
|
||||
run = checkout.run([worker(), *asked[1:]], terminal_input="")
|
||||
run = checkout.run([worker(), *asked[1:]], terminal_input="/talk\n", before_typing=ANSWERING)
|
||||
self.assertEqual(run.code, 2)
|
||||
self.assertIn(f"could not write {checkout.claude_json()}: Permission denied\n", run.stderr)
|
||||
self.assertEqual(checkout.claude_json().read_text(), "{}")
|
||||
@@ -655,7 +753,7 @@ class Interrupt(unittest.TestCase):
|
||||
@unittest.skipIf(os.geteuid() == 0, "root reads an unreadable file")
|
||||
def test_exits_1_when_the_transcript_cannot_be_read_after_the_interrupt(self):
|
||||
checkout = Checkout(self)
|
||||
run = checkout.run([worker(say="A or B?"), judge(interrupt=True, evidence="A or B?", question="A or B?"), interrupt(type="B", unreadable=True)], terminal_input="")
|
||||
run = checkout.run([worker(say="A or B?"), judge(interrupt=True, evidence="A or B?", question="A or B?"), interrupt(type="B", unreadable=True)], terminal_input="/talk\n", before_typing=ANSWERING)
|
||||
self.assertEqual((run.code, run.roles()), (1, ["worker", "judge", "interrupt"]))
|
||||
self.assertRegex(run.stderr.strip().splitlines()[-1], r"^could not tell whether you typed anything: could not read the transcript .*\.jsonl: Permission denied$")
|
||||
|
||||
@@ -763,7 +861,7 @@ class Reload(unittest.TestCase):
|
||||
self.assertEqual(run.roles(), ["worker", "judge"] * 5)
|
||||
self.assertIn("keeping the running script", run.stderr)
|
||||
reloads = [json.loads(argv[1]) for argv in run.starts if argv[:1] == ["--reloaded"]]
|
||||
self.assertEqual(reloads, [{"cycle_number": cycle, "root": str(checkout.root), "task": TASK, "unfinished_evidence": "working", "route": None} for cycle in (2, 3, 4)])
|
||||
self.assertEqual(reloads, [{"cycle_number": cycle, "root": str(checkout.root), "task": TASK, "unfinished_evidence": "working", "route": OFF_LADDER_ROUTE} for cycle in (2, 3, 4)])
|
||||
self.assertIn("=== cycle 5,", run.stdout)
|
||||
|
||||
outside = checkout.temp / "outside"
|
||||
|
||||
+845
-216
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,50 @@
|
||||
"""The verdicts cycle.judge.verdict_from builds from the judge's reply. They sit outside cycle/, since routing reads them and cycle imports routing."""
|
||||
import dataclasses
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Interrupt:
|
||||
evidence: str
|
||||
question: str
|
||||
# The judge's quote showing that the worker's cited escalation trigger fired; empty for none.
|
||||
escalation: str = ""
|
||||
# The highest L the judge saw the worker take into the chunk, 0 for none: an escalation steps up from the rung that L picks.
|
||||
highest_likelihood_taken_in: int = 0
|
||||
release_ready: bool = False
|
||||
# How many transcript entries the judge read, which escalation_mark.stamped stamps. An escalation the verdict carries moves the route's mark there. None means it was never stamped, and then its escalation doesn't step the worker.
|
||||
entries_read: int | None = None
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class QuotedAnswer:
|
||||
"""The worker asked a question that README.md or the records answer. The answer field quotes the passage."""
|
||||
evidence: str
|
||||
question: str
|
||||
answer: str
|
||||
# As on Interrupt.
|
||||
escalation: str = ""
|
||||
highest_likelihood_taken_in: int = 0
|
||||
entries_read: int | None = None
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Finished:
|
||||
evidence: str
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Unfinished:
|
||||
evidence: str
|
||||
# As on Interrupt; the worker also rises to the rung that L picks.
|
||||
highest_likelihood_taken_in: int = 0
|
||||
# As on Interrupt.
|
||||
escalation: str = ""
|
||||
# The highest E + I the judge saw the worker take into the chunk, 0 for none.
|
||||
highest_escape_and_impact_taken_in: int = 0
|
||||
# As on Interrupt.
|
||||
entries_read: int | None = None
|
||||
|
||||
|
||||
Verdict = Interrupt | QuotedAnswer | Finished | Unfinished
|
||||
# The verdicts that may carry an escalation.
|
||||
Escalating = Interrupt | QuotedAnswer | Unfinished
|
||||
@@ -1,4 +1,5 @@
|
||||
import re
|
||||
import typing
|
||||
|
||||
FENCE = re.compile(r"^ {0,3}(`{3,}|~{3,})", re.M)
|
||||
|
||||
@@ -30,3 +31,8 @@ def sections(text: str) -> dict[str, list[str]]:
|
||||
# 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())
|
||||
|
||||
|
||||
def listed(names: typing.Sequence[str], conjunction: str) -> str:
|
||||
"""The names as `a, b and c`, with conjunction, such as `and` or `or`, before the last."""
|
||||
return names[0] if len(names) == 1 else f"{', '.join(names[:-1])} {conjunction} {names[-1]}"
|
||||
|
||||
+13
-21
@@ -25,19 +25,20 @@ 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.
|
||||
- each file left out of its run because git's output for it is not UTF-8, because git cannot show
|
||||
it, or 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.
|
||||
Exit 1, saying why, on unknown arguments, or when git cannot start or finds no checkout, a tracked
|
||||
file's name is not UTF-8, 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 git_repo import git
|
||||
from metric_bench.python_units import measured, python_units, Unit
|
||||
|
||||
|
||||
@@ -66,7 +67,7 @@ def read_history(given: pathlib.Path | None) -> tuple[str, pathlib.Path, str] |
|
||||
"""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)
|
||||
found = git("rev-parse", "--show-toplevel", cwd=str(given.parent) if given else None)
|
||||
if isinstance(found, Failure):
|
||||
return found
|
||||
history = given or pathlib.Path(found.strip(), "docs", "comprehension-history.md")
|
||||
@@ -89,7 +90,7 @@ def bench_runs(text: str, top: str) -> tuple[list[tuple[str, RunScores]], list[s
|
||||
rows = []
|
||||
notes = []
|
||||
for run in scored_runs(entries(text)):
|
||||
if isinstance(missing := git(["cat-file", "-e", f"{run.commit}^{{commit}}"], top), Failure):
|
||||
if isinstance(missing := git("cat-file", "-e", f"{run.commit}^{{commit}}", cwd=top), Failure):
|
||||
notes.append(f"Skipped, its commit is not in {top}: {run.heading} ({missing.reason})")
|
||||
continue
|
||||
scored = run_scores(run, top)
|
||||
@@ -109,23 +110,22 @@ def noted(notes: list[str]) -> str:
|
||||
|
||||
|
||||
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)
|
||||
"""The run's scores, and why each file left out was: git could not show it as UTF-8, or it does not parse."""
|
||||
# A tracked name that is not UTF-8 fails the run rather than reading with its bytes replaced.
|
||||
listed = git("ls-tree", "-r", "-z", "--name-only", run.commit, cwd=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)
|
||||
source = git("show", f"{run.commit}:{path}", cwd=top)
|
||||
found = source if isinstance(source, Failure) else 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)
|
||||
log = git("-c", "core.quotePath=false", "log", "--no-merges", "--format=tformat:@@", "--name-only", run.commit, cwd=top)
|
||||
if isinstance(log, Failure):
|
||||
return log
|
||||
places, dropped = tracked_places(run.scored_places, tracked)
|
||||
@@ -147,14 +147,6 @@ 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
|
||||
|
||||
@@ -247,6 +247,19 @@ class BlackBox(unittest.TestCase):
|
||||
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_leaves_out_and_names_a_file_that_is_not_utf_8(self):
|
||||
top = self.project("")
|
||||
pathlib.Path(top, "b.py").write_bytes(b"# caf\xe9\n")
|
||||
env = isolated_env()
|
||||
subprocess.run(["git", "add", "b.py"], cwd=top, check=True, env=env)
|
||||
subprocess.run(["git", "commit", "-qm", "b"], 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()
|
||||
pathlib.Path(top, "docs", "comprehension-history.md").write_text(f"# 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("Left out of 2026-10-08T12:50:49Z, PR #1", ran.stdout)
|
||||
self.assertIn("b.py", ran.stdout.split("Left out of")[1])
|
||||
|
||||
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")))
|
||||
|
||||
+73
-12
@@ -1,5 +1,14 @@
|
||||
"""The routing ladder, and the rung an R + C picks from the project's rung: docs/decisions.md → `routing:`."""
|
||||
"""The routing ladder, and the rungs a task's L and E + I pick from the project's rung: docs/decisions.md → `routing:`."""
|
||||
import dataclasses
|
||||
import re
|
||||
import typing
|
||||
|
||||
from review_passes import ReviewedPass, REVIEWERS
|
||||
|
||||
# How Rung.__str__ spells a rung that names an effort, and Rung.parse reads it back.
|
||||
WORDING = re.compile(r"(?P<model>\S+) at (?P<effort>\S+) effort")
|
||||
# What a review launch reviews: such a pass, a comprehension seat or the security pass.
|
||||
ReviewKind = ReviewedPass | typing.Literal["seat", "security"]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -11,14 +20,32 @@ class Rung:
|
||||
def flags(self) -> list[str]:
|
||||
return ["--model", self.model, *(["--effort", self.effort] if self.effort else [])]
|
||||
|
||||
def family(self) -> str:
|
||||
"""The Agent tool's name for the model, such as opus for claude-opus-5-5."""
|
||||
return self.model.split("-")[1]
|
||||
|
||||
def agent_args(self) -> str:
|
||||
"""The rung in the Agent tool's words. The tool takes a family name, such as opus, and runs that family's latest model, which is the model each rung names."""
|
||||
return f"model {self.model.split('-')[1]}, effort {self.effort}"
|
||||
return f"model {self.family()}, effort {self.effort}"
|
||||
|
||||
# The archive records this wording, and model_routing.route.ROUTED reads it back to resume a chunk on its rung.
|
||||
@staticmethod
|
||||
def from_agent(model: str, effort: str) -> "Rung":
|
||||
"""The rung the Agent tool's model and effort name: a family such as opus is its ladder model, at the effort given or else its cheapest. A family off the ladder, or an effort off it, gives a rung that is not on LADDER."""
|
||||
family = next((rung for rung in LADDER if rung.family() == model), None)
|
||||
if family is None:
|
||||
return Rung(model, effort)
|
||||
return Rung(family.model, effort) if effort else family
|
||||
|
||||
# The one spelling of a rung. loop-claude hands it to rule-hook in environment variables, and archive lines written before route.Route.worker_line hold it, so parse must keep reading it.
|
||||
def __str__(self) -> str:
|
||||
return f"{self.model} at {self.effort} effort" if self.effort else self.model
|
||||
|
||||
@staticmethod
|
||||
def parse(text: str) -> "Rung | None":
|
||||
"""The rung that names an effort, which str wrote, whether or not it is on the ladder; None for any other text, such as a bare model."""
|
||||
found = WORDING.fullmatch(text)
|
||||
return Rung(found["model"], found["effort"]) if found else None
|
||||
|
||||
|
||||
# Least competent first.
|
||||
LADDER = (
|
||||
@@ -34,9 +61,12 @@ LADDER = (
|
||||
Rung("claude-opus-5-5", "max"),
|
||||
Rung("claude-fable-5-1", "max"),
|
||||
)
|
||||
# (highest R + C in the band, rungs it steps from the project's rung); a higher R + C steps ABOVE_THE_BANDS.
|
||||
BANDS = ((4, -3), (6, -2), (8, -1), (10, 0), (12, 1), (14, 2), (16, 3))
|
||||
ABOVE_THE_BANDS = 4
|
||||
# The rungs a task's L steps its worker from the project's rung.
|
||||
WORKER_STEPS = {1: -1, 2: -1, 3: 0, 4: 1}
|
||||
# The rungs a task's E + I steps a review up from the project's rung; an E + I under 5 steps none.
|
||||
REVIEW_STEPS = {5: 1, 6: 2, 7: 3, 8: 4}
|
||||
# The rung a pass's replay chose for the projects on a model: docs/decisions.md → `routing: a review pass runs below the project's rung only on a rung that a replay of its rounds shows finding every 🔴 and 🟡 the project's rung finds`.
|
||||
REPLAYED: dict[tuple[ReviewedPass, str], Rung] = {}
|
||||
|
||||
|
||||
def project_rung(model: str) -> Rung | None:
|
||||
@@ -44,14 +74,24 @@ def project_rung(model: str) -> Rung | None:
|
||||
return next((rung for rung in LADDER if rung.model == model), None)
|
||||
|
||||
|
||||
def picked(anchor: Rung, risk_and_complexity: int) -> Rung:
|
||||
"""The rung a task's R + C picks from anchor, the project's rung, stopping at either end of the ladder."""
|
||||
return climbed(anchor, next((step for highest, step in BANDS if risk_and_complexity <= highest), ABOVE_THE_BANDS))
|
||||
def worker_rung(project: Rung, likelihood: int) -> Rung:
|
||||
"""The rung a task's L picks for its worker, counted from the project's rung, stopping at either end of the ladder."""
|
||||
return climbed(project, WORKER_STEPS[likelihood])
|
||||
|
||||
|
||||
def floored(anchor: Rung, risk_and_complexity: int) -> Rung:
|
||||
"""The rung a task's R + C picks from anchor, the project's rung, never below anchor."""
|
||||
return highest(anchor, picked(anchor, risk_and_complexity))
|
||||
def lowest_worker_rung(project: Rung) -> Rung:
|
||||
"""The lowest rung any L routes a worker to, counted from the project's rung."""
|
||||
return climbed(project, min(WORKER_STEPS.values()))
|
||||
|
||||
|
||||
def planning_rung(project: Rung, likelihood: int) -> Rung:
|
||||
"""The rung of a task that files or scores todo.md items: the one its L picks, never below the project's rung."""
|
||||
return highest(project, worker_rung(project, likelihood))
|
||||
|
||||
|
||||
def review_floor(project: Rung, escape_and_impact: int) -> Rung:
|
||||
"""The rung a task's E + I picks for a review, counted up from the project's rung. An E + I of 0, for no task, picks the project's rung."""
|
||||
return climbed(project, REVIEW_STEPS.get(escape_and_impact, 0))
|
||||
|
||||
|
||||
def stepped_up(rung: Rung) -> Rung:
|
||||
@@ -59,6 +99,27 @@ def stepped_up(rung: Rung) -> Rung:
|
||||
return climbed(rung, 1)
|
||||
|
||||
|
||||
def review_rungs(project: Rung, worker: Rung, escape_and_impact: int) -> dict[ReviewKind, Rung]:
|
||||
"""The rung each kind of review in a chunk runs on, where its worker runs on worker and its item has that E + I.
|
||||
|
||||
A pass's reviewer runs on reviewers_rung. Where the E + I steps no review up and the worker runs no higher than the project's rung, a pass whose replay chose a rung for the project's model runs on that rung instead, even below the worker's: the replay compared reviews on the project's rung only, never on a rung an E + I stepped up, nor of a chunk whose worker climbed above the project's rung. A seat and the security pass run on the project's rung, so the seats score every chunk on one rung, and the security pass spends no more than the project chose.
|
||||
"""
|
||||
rungs: dict[ReviewKind, Rung] = {**dict.fromkeys(REVIEWERS, reviewers_rung(project, worker, escape_and_impact)), "seat": project, "security": project}
|
||||
if replay_applies(project, worker, escape_and_impact):
|
||||
rungs |= {kind: rung for (kind, model), rung in REPLAYED.items() if model == project.model}
|
||||
return rungs
|
||||
|
||||
|
||||
def replay_applies(project: Rung, worker: Rung, escape_and_impact: int) -> bool:
|
||||
"""Whether a pass's replay chose its rung for a chunk like this: only where the E + I steps no review up and the worker runs no higher than the project's rung."""
|
||||
return escape_and_impact not in REVIEW_STEPS and position(worker) <= position(project)
|
||||
|
||||
|
||||
def reviewers_rung(project: Rung, worker: Rung, escape_and_impact: int) -> Rung:
|
||||
"""The rung of each pass's reviewer that no replay lowered: the higher of the worker's rung and review_floor's."""
|
||||
return highest(worker, review_floor(project, escape_and_impact))
|
||||
|
||||
|
||||
def highest(*rungs: Rung) -> Rung:
|
||||
"""The most competent of the rungs; one off the ladder ranks below every rung on it."""
|
||||
return max(rungs, key=position)
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
"""Where a chunk's reviews run, chosen from its route and the project's rung."""
|
||||
import dataclasses
|
||||
|
||||
from model_routing.route import HIGHEST_ESCAPE_AND_IMPACT, Route
|
||||
from model_routing.ladder import replay_applies, review_rungs, reviewers_rung, Rung
|
||||
from review_passes import ReviewedPass, REVIEWERS
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class ReviewChoice:
|
||||
# The rung of each pass's reviewer that no replay lowered.
|
||||
reviewers: Rung
|
||||
# The passes whose replay chose another rung, with that rung.
|
||||
lowered: dict[ReviewedPass, Rung]
|
||||
seat: Rung
|
||||
security: Rung
|
||||
# Each rung a higher E + I than the route's picks for the reviewers, with the lowest E + I that picks it, in rising order.
|
||||
higher: dict[Rung, int]
|
||||
|
||||
|
||||
def chosen(project: Rung, route: Route) -> ReviewChoice:
|
||||
"""The rung each kind of review runs on for a chunk whose route is route, on a project whose rung is project."""
|
||||
rungs = review_rungs(project, route.rung, route.reviewed_on())
|
||||
reviewers = reviewers_rung(project, route.rung, route.reviewed_on())
|
||||
lowered = {kind: rungs[kind] for kind in REVIEWERS if rungs[kind] != reviewers}
|
||||
higher: dict[Rung, int] = {}
|
||||
for escape_and_impact in range(route.reviewed_on() + 1, HIGHEST_ESCAPE_AND_IMPACT + 1):
|
||||
# A higher E + I changes a review by moving the reviewers' rung, or by ending the replay that lowered a pass.
|
||||
rung = reviewers_rung(project, route.rung, escape_and_impact)
|
||||
if rung != reviewers or (lowered and not replay_applies(project, route.rung, escape_and_impact)):
|
||||
higher.setdefault(rung, escape_and_impact)
|
||||
return ReviewChoice(reviewers, lowered, rungs["seat"], rungs["security"], higher)
|
||||
+89
-12
@@ -1,33 +1,110 @@
|
||||
"""A chunk's route: its worker's rung and the plan item that picked it, in the words the archive records each verdict's worker in."""
|
||||
"""A chunk's route: its worker's rung and the plan item that picked it. The archive keeps the route as JSON on the Worker: line that ends each outcome."""
|
||||
import dataclasses
|
||||
import json
|
||||
import re
|
||||
import typing
|
||||
|
||||
from model_routing.ladder import Rung
|
||||
from todo_table import LEVELS
|
||||
from model_routing.ladder import REVIEW_STEPS, Rung
|
||||
|
||||
# How a worker opens the prompt of a subagent it escalates a task to, `Escalation trigger 2: …`: docs/decisions.md → `routing: a worker hands a task one rung up`.
|
||||
ESCALATION_MARKER = "Escalation trigger"
|
||||
ROUTED = re.compile(r"(?P<model>\S+) at (?P<effort>\S+) effort(?:, routed by item (?P<item>[0-9]+)'s R \+ C of (?P<sum>[0-9]+))?")
|
||||
# What Route.worker_line writes. The outcome writers take only this as the worker, so mypy refuses a str(route) there.
|
||||
WorkerLine = typing.NewType("WorkerLine", str)
|
||||
# A worker line loop-claude wrote before it archived the route as JSON. Nothing writes this format any more, so its wording never changes. route_from reads it for the chunks the routing figures still count, and for a chunk a rerun resumes across the change.
|
||||
LEGACY_WORKER = re.compile(r"(?P<rung>.+?)(?:, routed by item (?P<item>[0-9]+)'s L of (?P<likelihood>[0-9]+) and E \+ I of (?P<escape_and_impact>[0-9]+))?(?:, taking in an E \+ I of (?P<escape_and_impact_taken_in>[0-9]+))?(?:, escalated at transcript entry (?P<escalated_at>[0-9]+))?")
|
||||
|
||||
|
||||
HIGHEST_ESCAPE_AND_IMPACT = LEVELS["E"] + LEVELS["I"]
|
||||
|
||||
|
||||
def on_its_scale(escape_and_impact: int) -> bool:
|
||||
"""Whether E + I is a level on the scales todo_table.LEVELS gives; E and I each start at 1."""
|
||||
return 2 <= escape_and_impact <= HIGHEST_ESCAPE_AND_IMPACT
|
||||
|
||||
|
||||
def on_their_scales(likelihood: int, escape_and_impact: int) -> bool:
|
||||
"""Whether L and E + I are levels on the scales todo_table.LEVELS gives."""
|
||||
return 1 <= likelihood <= LEVELS["L"] and on_its_scale(escape_and_impact)
|
||||
|
||||
|
||||
def levels_fit(item: int, likelihood: int, escape_and_impact: int, escape_and_impact_taken_in: int) -> bool:
|
||||
"""Whether a route may hold these. It has an item with levels on their scales, or no item and no levels. Its E + I taken in is 0, or on its scale and above the item's; Route.taking_in keeps only one that steps the reviewers further."""
|
||||
routed = on_their_scales(likelihood, escape_and_impact) if item else not (likelihood or escape_and_impact)
|
||||
return routed and (escape_and_impact_taken_in == 0 or (on_its_scale(escape_and_impact_taken_in) and escape_and_impact_taken_in > escape_and_impact))
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Route:
|
||||
"""A chunk's worker rung and the plan item whose R + C picked it, 0 for none.
|
||||
"""A chunk's worker rung and the plan item that picked it, 0 for none. The item's L picked the worker's rung; reviewed_on, the higher of its E + I and the highest E + I the worker took in, picks the reviewers' and the judge's. A route holds only levels that levels_fit, so no rung is picked from a level off its scale.
|
||||
|
||||
unfinished counts the unfinished verdicts towards the next one-rung step; a reload hands it over with the rung.
|
||||
"""
|
||||
# Each field below but rung and unfinished is a key of the archive's worker lines, so renaming one makes the lines already archived unreadable, and their chunks route afresh.
|
||||
# The fields a loop-claude from before L and E + I replaced R + C hands on reload; the reloaded script drops such a route, and the chunk routes afresh.
|
||||
RETIRED: typing.ClassVar[frozenset[str]] = frozenset({"risk_and_complexity"})
|
||||
rung: Rung
|
||||
item: int = 0
|
||||
risk_and_complexity: int = 0
|
||||
likelihood: int = 0
|
||||
escape_and_impact: int = 0
|
||||
unfinished: int = 0
|
||||
# The highest E + I the judge saw the worker take in, kept only where it picks a higher review step than the item's; 0 otherwise.
|
||||
escape_and_impact_taken_in: int = 0
|
||||
# The escalation mark, as loop_claude/escalation_mark.py says: how many transcript entries the session held when an escalation last stepped the worker up, 0 before any.
|
||||
escalated_at: int = 0
|
||||
|
||||
def __str__(self) -> str:
|
||||
"""What the archive records as each verdict's worker; ROUTED reads it back."""
|
||||
return f"{self.rung}, routed by item {self.item}'s R + C of {self.risk_and_complexity}" if self.item else str(self.rung)
|
||||
def __post_init__(self) -> None:
|
||||
# Raises on a programming error only, so nothing catches it: route_from and the reload decoder check fits before they build a route.
|
||||
if not levels_fit(self.item, self.likelihood, self.escape_and_impact, self.escape_and_impact_taken_in):
|
||||
raise ValueError(f"a route by item {self.item} cannot hold an L of {self.likelihood}, an E + I of {self.escape_and_impact} and an E + I taken in of {self.escape_and_impact_taken_in}")
|
||||
|
||||
@staticmethod
|
||||
def fits(fields: typing.Mapping[str, typing.Any]) -> bool:
|
||||
"""Whether a route may be built from these fields."""
|
||||
return levels_fit(fields.get("item", 0), fields.get("likelihood", 0), fields.get("escape_and_impact", 0), fields.get("escape_and_impact_taken_in", 0))
|
||||
|
||||
def taking_in(self, escape_and_impact: int) -> "Route":
|
||||
"""The route after the judge saw the worker take in an item of this E + I, 0 for none: it keeps the E + I only where REVIEW_STEPS steps it further than reviewed_on, so the archive records a step-up only where REVIEW_STEPS steps the review floor further."""
|
||||
return dataclasses.replace(self, escape_and_impact_taken_in=escape_and_impact) if REVIEW_STEPS.get(escape_and_impact, 0) > REVIEW_STEPS.get(self.reviewed_on(), 0) else self
|
||||
|
||||
def reviewed_on(self) -> int:
|
||||
"""The E + I that picks the reviewers' and the judge's rung: the routed item's or the highest taken in, whichever is higher; 0 for neither."""
|
||||
return max(self.escape_and_impact, self.escape_and_impact_taken_in)
|
||||
|
||||
def worker_line(self) -> WorkerLine:
|
||||
"""What the archive records as each verdict's worker: a JSON object of the rung's model and effort and the WORKER_LINE_FIELDS, leaving out each that is 0 or empty; route_from reads it back."""
|
||||
fields = {"model": self.rung.model, "effort": self.rung.effort, **{name: getattr(self, name) for name in WORKER_LINE_FIELDS}}
|
||||
return WorkerLine(json.dumps({name: value for name, value in fields.items() if value}))
|
||||
|
||||
|
||||
# The Route fields a worker line holds beside the rung's model and effort. A human reads the line in the archive, so it is flatter than the JSON a reload hands over (loop_claude/loop/reload.py) and leaves out zeros. It leaves out unfinished, so a rerun restarts that count.
|
||||
WORKER_LINE_FIELDS = tuple(field.name for field in dataclasses.fields(Route) if field.name not in ("rung", "unfinished"))
|
||||
|
||||
|
||||
def route_from(worker: str) -> Route | None:
|
||||
"""The route an archived worker line names; None for a model run off the ladder."""
|
||||
found = ROUTED.fullmatch(worker)
|
||||
if not found:
|
||||
"""The route an archived worker line names, whether JSON or a line written before JSON. None where it names no model, holds fields Route.worker_line never writes, or holds levels off their scales; and for an older line, where it names a model without an effort."""
|
||||
fields = json_fields(worker) if worker.startswith("{") else legacy_fields(worker)
|
||||
if fields is None or not Route.fits(fields):
|
||||
return None
|
||||
return Route(Rung(found["model"], found["effort"]), int(found["item"] or 0), int(found["sum"] or 0))
|
||||
return Route(Rung(fields["model"], fields.get("effort", "")), **{name: fields.get(name, 0) for name in WORKER_LINE_FIELDS})
|
||||
|
||||
|
||||
def json_fields(line: str) -> dict[str, typing.Any] | None:
|
||||
"""The fields of a line Route.worker_line wrote; None for any other text."""
|
||||
try:
|
||||
fields = json.loads(line)
|
||||
except ValueError:
|
||||
return None
|
||||
if not (isinstance(fields, dict) and isinstance(fields.get("model"), str) and isinstance(fields.get("effort", ""), str) and fields.keys() <= {"model", "effort", *WORKER_LINE_FIELDS}):
|
||||
return None
|
||||
# type(), not isinstance(): JSON true is no integer.
|
||||
return fields if all(type(fields.get(name, 0)) is int and fields.get(name, 0) >= 0 for name in WORKER_LINE_FIELDS) else None
|
||||
|
||||
|
||||
def legacy_fields(line: str) -> dict[str, typing.Any] | None:
|
||||
"""The fields of a LEGACY_WORKER line, as json_fields gives them; None for any other text."""
|
||||
found = LEGACY_WORKER.fullmatch(line)
|
||||
rung = Rung.parse(found["rung"]) if found else None
|
||||
if not (found and rung):
|
||||
return None
|
||||
return {"model": rung.model, "effort": rung.effort, **{name: int(value or 0) for name, value in found.groupdict().items() if name != "rung"}}
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
import pathlib
|
||||
import sys
|
||||
import unittest
|
||||
import unittest.mock
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from model_routing.ladder import floored, highest, LADDER, picked, project_rung, Rung, stepped_up
|
||||
from model_routing.ladder import highest, LADDER, lowest_worker_rung, planning_rung, position, project_rung, review_floor, review_rungs, Rung, stepped_up, worker_rung, WORKER_STEPS
|
||||
from model_routing import ladder
|
||||
from todo_table import LEVELS
|
||||
from review_passes import REVIEWERS
|
||||
|
||||
OPUS = Rung("claude-opus-5-5", "medium")
|
||||
|
||||
@@ -22,20 +26,31 @@ class Ladder(unittest.TestCase):
|
||||
self.assertIsNone(project_rung("claude-opus-5"))
|
||||
self.assertIsNone(project_rung("opus"))
|
||||
|
||||
def test_steps_each_band_of_r_plus_c_from_the_projects_rung(self):
|
||||
def test_steps_a_workers_rung_by_its_l_from_the_projects_rung(self):
|
||||
position = LADDER.index(OPUS)
|
||||
self.assertEqual([LADDER.index(picked(OPUS, total)) - position for total in range(2, 21)], [-3, -3, -3, -2, -2, -1, -1, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 4, 4])
|
||||
self.assertEqual([LADDER.index(worker_rung(OPUS, likelihood)) - position for likelihood in range(1, 5)], [-1, -1, 0, 1])
|
||||
|
||||
def test_steps_a_review_up_by_its_e_plus_i_from_the_projects_rung_and_never_down(self):
|
||||
position = LADDER.index(OPUS)
|
||||
self.assertEqual([LADDER.index(review_floor(OPUS, total)) - position for total in range(2, 9)], [0, 0, 0, 1, 2, 3, 4])
|
||||
self.assertEqual(review_floor(OPUS, 0), OPUS)
|
||||
|
||||
def test_a_step_past_either_end_stops_there(self):
|
||||
self.assertEqual(picked(OPUS, 4), Rung("claude-haiku-5-5", "xhigh"))
|
||||
self.assertEqual(picked(OPUS, 17), Rung("claude-fable-5-1", "max"))
|
||||
self.assertEqual(picked(LADDER[1], 2), LADDER[0])
|
||||
self.assertEqual(worker_rung(OPUS, 1), Rung("claude-sonnet-5-5", "high"))
|
||||
self.assertEqual(worker_rung(LADDER[0], 1), LADDER[0])
|
||||
self.assertEqual(review_floor(Rung("claude-opus-5-5", "xhigh"), 8), LADDER[-1])
|
||||
self.assertEqual(stepped_up(LADDER[-1]), LADDER[-1])
|
||||
self.assertEqual(stepped_up(OPUS), Rung("claude-opus-5-5", "high"))
|
||||
|
||||
def test_floors_the_picked_rung_at_the_projects_rung(self):
|
||||
self.assertEqual(floored(OPUS, 2), OPUS)
|
||||
self.assertEqual(floored(OPUS, 12), Rung("claude-opus-5-5", "high"))
|
||||
def test_steps_a_worker_for_every_level_on_ls_scale(self):
|
||||
self.assertEqual(set(WORKER_STEPS), set(range(1, LEVELS["L"] + 1)))
|
||||
|
||||
def test_names_the_lowest_rung_any_l_routes_a_worker_to(self):
|
||||
self.assertEqual(lowest_worker_rung(OPUS), Rung("claude-sonnet-5-5", "high"))
|
||||
|
||||
def test_plans_on_the_rung_l_picks_but_never_below_the_projects(self):
|
||||
self.assertEqual(planning_rung(OPUS, 1), OPUS)
|
||||
self.assertEqual(planning_rung(OPUS, 4), Rung("claude-opus-5-5", "high"))
|
||||
|
||||
def test_names_each_rung_by_a_family_the_agent_tool_takes(self):
|
||||
self.assertEqual({rung.agent_args().split(",")[0] for rung in LADDER}, {"model haiku", "model sonnet", "model opus", "model fable"})
|
||||
@@ -51,6 +66,63 @@ class Ladder(unittest.TestCase):
|
||||
self.assertEqual(str(Rung("claude-opus-5-5", "high")), "claude-opus-5-5 at high effort")
|
||||
self.assertEqual(str(Rung("worker-model")), "worker-model")
|
||||
|
||||
def test_parses_what_str_wrote_for_each_rung_on_the_ladder(self):
|
||||
for rung in LADDER:
|
||||
with self.subTest(rung=rung):
|
||||
self.assertEqual(Rung.parse(str(rung)), rung)
|
||||
|
||||
def test_parses_a_rung_off_the_ladder_too_for_the_caller_to_judge(self):
|
||||
self.assertEqual(Rung.parse("claude-opus-5-5 at low effort"), Rung("claude-opus-5-5", "low"))
|
||||
|
||||
def test_parses_no_other_wording_as_a_rung(self):
|
||||
for text in ("", "claude-opus-5-5", "claude-opus-5-5 medium", "claude-opus-5-5 at medium", "at medium effort", "a b at medium effort"):
|
||||
with self.subTest(text=text):
|
||||
self.assertIsNone(Rung.parse(text))
|
||||
|
||||
def test_reads_the_agent_tools_words_back_as_a_rung(self):
|
||||
for rung in LADDER:
|
||||
with self.subTest(rung=rung):
|
||||
model, effort = (part.split(" ")[1] for part in rung.agent_args().split(", "))
|
||||
self.assertEqual(Rung.from_agent(model, effort), rung)
|
||||
|
||||
def test_reads_a_family_named_without_an_effort_as_its_cheapest_rung(self):
|
||||
self.assertEqual(Rung.from_agent("opus", ""), OPUS)
|
||||
self.assertEqual(Rung.from_agent("sonnet", ""), Rung("claude-sonnet-5-5", "high"))
|
||||
|
||||
def test_reads_an_unknown_family_or_an_effort_off_the_ladder_as_a_rung_off_it(self):
|
||||
for model, effort in (("gpt", "high"), ("gpt", ""), ("opus", "low"), ("haiku", "bogus")):
|
||||
with self.subTest(model=model, effort=effort):
|
||||
self.assertNotIn(Rung.from_agent(model, effort), LADDER)
|
||||
self.assertEqual(Rung.from_agent("opus", "low"), Rung("claude-opus-5-5", "low"))
|
||||
|
||||
def test_puts_reviewers_on_the_highest_of_the_projects_rung_the_workers_and_the_one_e_plus_i_picks(self):
|
||||
haiku, fable = LADDER[4], LADDER[-1]
|
||||
self.assertEqual(review_rungs(OPUS, haiku, 4)["stability"], OPUS)
|
||||
self.assertEqual(review_rungs(OPUS, haiku, 5)["stability"], Rung("claude-opus-5-5", "high"))
|
||||
self.assertEqual(review_rungs(OPUS, fable, 5)["stability"], fable)
|
||||
self.assertEqual(review_rungs(OPUS, Rung("claude-opus-5-5", "high"), 7)["stability"], Rung("claude-opus-5-5", "max"))
|
||||
|
||||
def test_keeps_the_seats_and_the_security_pass_on_the_projects_rung_whatever_the_worker_or_e_plus_i(self):
|
||||
self.assertEqual(review_rungs(OPUS, LADDER[-1], 8), {**dict.fromkeys(REVIEWERS, LADDER[-1]), "seat": OPUS, "security": OPUS})
|
||||
|
||||
def test_runs_a_replayed_pass_on_its_replays_rung_below_the_workers_where_the_e_plus_i_steps_no_review_up_and_the_worker_runs_no_higher_than_the_project(self):
|
||||
sonnet, haiku, opus_high = Rung("claude-sonnet-5-5", "high"), LADDER[0], Rung("claude-opus-5-5", "high")
|
||||
with unittest.mock.patch.dict(ladder.REPLAYED, {("prose", "claude-opus-5-5"): haiku, ("stability", "claude-sonnet-5-5"): haiku}):
|
||||
self.assertEqual(review_rungs(OPUS, LADDER[4], 4), {**dict.fromkeys(REVIEWERS, OPUS), "prose": haiku, "seat": OPUS, "security": OPUS})
|
||||
self.assertEqual(review_rungs(OPUS, OPUS, 4)["prose"], haiku)
|
||||
self.assertEqual(review_rungs(OPUS, opus_high, 4)["prose"], opus_high)
|
||||
self.assertEqual(review_rungs(OPUS, sonnet, 5)["prose"], opus_high)
|
||||
self.assertEqual(review_rungs(OPUS, LADDER[-1], 5)["prose"], LADDER[-1])
|
||||
self.assertEqual((review_rungs(sonnet, sonnet, 4)["prose"], review_rungs(sonnet, sonnet, 4)["stability"]), (sonnet, haiku))
|
||||
|
||||
def test_holds_each_replayed_rung_below_its_models_project_rung_on_the_ladder(self):
|
||||
for (kind, model), rung in ladder.REPLAYED.items():
|
||||
with self.subTest(kind=kind, model=model):
|
||||
project = project_rung(model)
|
||||
self.assertIn(kind, REVIEWERS)
|
||||
self.assertIsNotNone(project)
|
||||
self.assertLess(position(rung), position(project) if project else 0)
|
||||
self.assertIn(rung, LADDER)
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import unittest
|
||||
import unittest.mock
|
||||
|
||||
from model_routing.review_choice import chosen, ReviewChoice
|
||||
from model_routing import ladder
|
||||
from model_routing.route import Route
|
||||
from model_routing.ladder import Rung
|
||||
|
||||
HAIKU = Rung("claude-haiku-5-5", "low")
|
||||
OPUS = Rung("claude-opus-5-5", "medium")
|
||||
OPUS_MAX = Rung("claude-opus-5-5", "max")
|
||||
FABLE = Rung("claude-fable-5-1", "max")
|
||||
SONNET = Rung("claude-sonnet-5-5", "high")
|
||||
|
||||
|
||||
class Chosen(unittest.TestCase):
|
||||
def test_names_no_higher_rung_on_the_top_one(self):
|
||||
self.assertEqual(chosen(OPUS, Route(FABLE, 3, 4, 5)).higher, {})
|
||||
|
||||
def test_names_the_e_plus_i_that_ends_a_replay_even_where_the_reviewers_are_on_the_top_rung(self):
|
||||
with unittest.mock.patch.dict(ladder.REPLAYED, {("prose", "claude-fable-5-1"): HAIKU}):
|
||||
self.assertEqual(chosen(FABLE, Route(OPUS_MAX, 3, 4, 4)), ReviewChoice(FABLE, {"prose": HAIKU}, FABLE, FABLE, {FABLE: 5}))
|
||||
|
||||
def test_puts_every_pass_on_the_reviewers_rung_once_an_e_plus_i_steps_a_review_up(self):
|
||||
with unittest.mock.patch.dict(ladder.REPLAYED, {("prose", "claude-opus-5-5"): HAIKU}):
|
||||
self.assertEqual(chosen(OPUS, Route(SONNET, 3, 2, 5)).lowered, {})
|
||||
@@ -0,0 +1,30 @@
|
||||
import unittest
|
||||
|
||||
from model_routing.worker_rungs import environment, handed
|
||||
from model_routing.route import Route
|
||||
from model_routing.ladder import Rung
|
||||
|
||||
|
||||
class Environment(unittest.TestCase):
|
||||
PROJECT = Rung("claude-opus-5-5", "medium")
|
||||
WORKER = Rung("claude-haiku-5-5", "max")
|
||||
|
||||
def test_the_project_and_the_workers_rungs_and_the_e_plus_i_reviews_take_are_named_in_the_environment(self):
|
||||
self.assertEqual(environment(self.PROJECT, Route(self.WORKER, 3, 1, 5)), {"LOOP_CLAUDE_PROJECT_RUNG": "claude-opus-5-5 at medium effort", "LOOP_CLAUDE_WORKER_RUNG": "claude-haiku-5-5 at max effort", "LOOP_CLAUDE_ESCAPE_AND_IMPACT": "5"})
|
||||
self.assertEqual(environment(self.PROJECT, Route(self.WORKER))["LOOP_CLAUDE_ESCAPE_AND_IMPACT"], "0")
|
||||
self.assertEqual(environment(self.PROJECT, Route(self.WORKER, 3, 1, 5, escape_and_impact_taken_in=6))["LOOP_CLAUDE_ESCAPE_AND_IMPACT"], "6")
|
||||
|
||||
def test_a_project_off_the_ladder_is_handed_an_empty_rung_so_none_is_inherited(self):
|
||||
self.assertEqual(environment(None, Route(self.WORKER)), {"LOOP_CLAUDE_PROJECT_RUNG": "", "LOOP_CLAUDE_WORKER_RUNG": "claude-haiku-5-5 at max effort", "LOOP_CLAUDE_ESCAPE_AND_IMPACT": "0"})
|
||||
|
||||
def test_handed_reads_back_what_environment_named(self):
|
||||
self.assertEqual(handed(environment(self.PROJECT, Route(self.WORKER, 3, 1, 5))), (self.PROJECT, self.WORKER, 5))
|
||||
self.assertEqual(handed(environment(None, Route(self.WORKER))), (None, self.WORKER, 0))
|
||||
|
||||
def test_a_missing_or_unknown_rung_reads_as_none_and_a_missing_or_unknown_e_plus_i_as_0(self):
|
||||
self.assertEqual(handed({}), (None, None, 0))
|
||||
self.assertEqual(handed({"LOOP_CLAUDE_WORKER_RUNG": "claude-haiku-5-5 bogus"}), (None, None, 0))
|
||||
self.assertEqual(handed({"LOOP_CLAUDE_WORKER_RUNG": "claude-haiku-5-5 at bogus effort"}), (None, None, 0))
|
||||
for bogus in ("", "five", "-1", "5.0", "²"):
|
||||
with self.subTest(bogus=bogus):
|
||||
self.assertEqual(handed({"LOOP_CLAUDE_ESCAPE_AND_IMPACT": bogus})[2], 0)
|
||||
@@ -0,0 +1,28 @@
|
||||
"""The rungs and the E + I loop-claude hands a worker's claude in its environment, from which rule-hook works out the rung of each review launch: docs/decisions.md → `routing:`.
|
||||
|
||||
loop-claude sets these variables for its worker and for the claude an interrupt resumes; a human's shell does not, and rule-hook then checks no review launch."""
|
||||
import typing
|
||||
|
||||
from model_routing.ladder import LADDER, Rung
|
||||
from model_routing.route import Route
|
||||
|
||||
PROJECT_RUNG = "LOOP_CLAUDE_PROJECT_RUNG"
|
||||
WORKER_RUNG = "LOOP_CLAUDE_WORKER_RUNG"
|
||||
# The E + I the chunk's reviews are routed on, from which review_rungs works out each review's rung.
|
||||
ESCAPE_AND_IMPACT = "LOOP_CLAUDE_ESCAPE_AND_IMPACT"
|
||||
|
||||
|
||||
def environment(project: Rung | None, route: Route) -> dict[str, str]:
|
||||
"""The variables a worker's claude on route starts with. A project off the ladder gets an empty project rung, so none is inherited from the environment."""
|
||||
return {PROJECT_RUNG: str(project) if project else "", WORKER_RUNG: str(route.rung), ESCAPE_AND_IMPACT: str(route.reviewed_on())}
|
||||
|
||||
|
||||
def handed(environ: typing.Mapping[str, str]) -> tuple[Rung | None, Rung | None, int]:
|
||||
"""The project's and the worker's rungs, each None when unset or not on the ladder, and the reviews' E + I, 0 when unset or not a whole number. An older loop-claude hands no E + I, and 0 steps no review up."""
|
||||
escape_and_impact = environ.get(ESCAPE_AND_IMPACT, "")
|
||||
return on_the_ladder(environ.get(PROJECT_RUNG)), on_the_ladder(environ.get(WORKER_RUNG)), int(escape_and_impact) if escape_and_impact.isdecimal() else 0
|
||||
|
||||
|
||||
def on_the_ladder(value: str | None) -> Rung | None:
|
||||
rung = Rung.parse(value or "")
|
||||
return rung if rung in LADDER else None
|
||||
+168
-101
@@ -1,14 +1,15 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Score todo.md's items by the formula it states, weighing each achieve goal by its position in README.md, and hold them to its bar.
|
||||
"""Score todo.md's items by the formula it states, weighing code health first and then README.md's achieve goals by their position, and hold them to its bar.
|
||||
|
||||
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,
|
||||
question rows come first, then security rows, then the rest, each group by score from highest, then
|
||||
by ID. Then it moves each blocker, an item another's Blocked by cell names, that ranks below an item
|
||||
it blocks to just above the first such item. Orders the details to match. Adds the Blocked by column
|
||||
to a table without it. --check writes nothing and fails when the file is not ranked as it would be.
|
||||
Reads todo.md (default: ./todo.md), the README.md beside it, and docs/decisions.md and
|
||||
docs/comprehension-history.md where they exist. Rewrites each item's Score from the formula and
|
||||
sorts the items by release; within a release, question rows come first, then security rows, then
|
||||
the rest, each group by score from highest, then by ID. Then it moves each blocker, an item
|
||||
another's Blocked by cell names, that ranks below an item it blocks to just above the first such
|
||||
item. Orders the details to match. Writes each item's R, and adds the Blocked by and R columns to a
|
||||
table without them. --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:
|
||||
|
||||
@@ -24,9 +25,9 @@ A valid todo.md; ## Details and each item's detail are optional:
|
||||
|
||||
## Items
|
||||
|
||||
| ID | Release | Blocked by | Exempt | Item | R | S | C | Moves | Score |
|
||||
|---|---|---|---|---|---|---|---|---|---|
|
||||
| 1 | 0.1.0 | | | **Make the first thing work.** | 2 | 3 | 4 | 1 by 9 | 0 |
|
||||
| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |
|
||||
|---|---|---|---|---|---|---|---|---|---|---|---|
|
||||
| 1 | 0.1.0 | | | **Make the first thing work.** | 2 | 2 | 1 | 3 | 3 | 1 by 9 | 0 |
|
||||
|
||||
## Details
|
||||
|
||||
@@ -34,16 +35,25 @@ A valid todo.md; ## Details and each item's detail are optional:
|
||||
|
||||
What the tagline cannot say.
|
||||
|
||||
- The formula holds numbers, + - * / ** and parentheses over R, S and V.
|
||||
- The formula holds numbers, + - * / ** and parentheses over L, E, I, R, S and V.
|
||||
- V sums, over the goals in an item's Moves cell, each goal's weight times how far the item moves it.
|
||||
README.md marks each goal **Maintain:** or **Achieve:**. The one ranked k of n achieve goals, in
|
||||
reading order, a sub-goal such as 1.1 included, weighs (1/k) / (1 + 1/2 + ... + 1/n). Only an item
|
||||
marked defect may name a maintain goal, the one it restores, which weighs as the heaviest achieve
|
||||
goal.
|
||||
README.md marks each goal **Maintain:** or **Achieve:**. Code health, the achieve goal every
|
||||
project shares, ranks first; a Moves cell names it as in `code health by 6`. README.md's achieve
|
||||
goals follow in reading order, a sub-goal such as 1.1 included. Each weighs 0.97 times the one
|
||||
before, and the weights sum to 1. With 5 achieve goals the first weighs 0.212 and the last 0.188.
|
||||
With 15 they weigh 0.082 and 0.053. The overall is the mean of the overall means of every scoring
|
||||
run on docs/comprehension-history.md's newest scored commit. While it is under 7.0, or the history
|
||||
holds no scoring run, code health weighs 4 times its weight by position, and the other goals keep
|
||||
theirs. A line `**Void:** code health, since <reason>.` in README.md's ## Goals drops code health,
|
||||
and an item may not name it. A project must void it where its docs/decisions.md has a
|
||||
`## review opt-out:` title naming the comprehension check. Only an item marked defect may name a
|
||||
maintain goal, the one it restores, which weighs as the heaviest achieve goal.
|
||||
- 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.
|
||||
- An item's R, S and C are whole numbers from 1 to 10. C, how hard the change is to get right, stays
|
||||
out of the formula.
|
||||
- An item's L, E and I are levels that ~/.claude/rules/todo-items.md defines: L from 1 to 4, E from 1
|
||||
to 3 and I from 1 to 5.
|
||||
rank_todo.py writes its R, L + E + I - 2, at least 7 when I is 5 and at least 5 when I is 4. Its S
|
||||
is a whole number from 1 to 10.
|
||||
- An item's Moves cell is empty, or names each goal it moves and how far, a whole number from 1 to
|
||||
10, such as `1.1 by 8, 1.2 by 5`: the most specific goal, and a parent only for a move none of its
|
||||
sub-goals covers, so never a goal beside its own sub-goal. An empty cell scores V 0.
|
||||
@@ -56,29 +66,44 @@ A valid todo.md; ## Details and each item's detail are optional:
|
||||
loop. An ID at or above Next ID fails; one below it that the table no longer holds was finished
|
||||
or deleted, and is dropped.
|
||||
- ## Items holds the table and nothing else: an order goes in the scores or the Blocked by column.
|
||||
- The table holds the columns above. A table without Blocked by gains it. One without C fails, and so
|
||||
does one with a column this version does not know, since writing it would drop that column.
|
||||
- A table in the old shape, with A, G and Goals columns in place of Moves, still ranks, by a formula
|
||||
over R, S, A, G and W and a | Goal | W | table that weighs every README goal, W being the heaviest
|
||||
cited goal's weight; ranking it says to reshape it.
|
||||
- The table holds the columns above. One missing L, E or I fails, and so does one with a column this
|
||||
version does not know, since writing it would drop that column.
|
||||
- A table in the old shape, with C, A, G and Goals columns in place of L, E, I and Moves, still
|
||||
ranks, by a formula over R, S, A, G and W and a | Goal | W | table that weighs every README goal, W
|
||||
being the heaviest cited goal's weight; ranking it says to reshape it.
|
||||
- ## Renamed is optional: one line `- 0.2.1 renamed to 0.3.0` per renamed release. chunk-preflight,
|
||||
loop-claude and larv-review skip the line's first release, and ignore the second, which is for the
|
||||
reader. No item may sit under a marked release, and a line goes once a tag at or past its first
|
||||
release is cut. A release whose items all moved elsewhere without a line reads as finished.
|
||||
|
||||
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.
|
||||
docs/decisions.md that breaks the rules above, a scoring run on docs/comprehension-history.md's
|
||||
newest scored commit with no Mean row ending in its overall, an item that is not exempt scoring
|
||||
under the bar, or --check finding the file unranked.
|
||||
"""
|
||||
import ast
|
||||
import dataclasses
|
||||
import decimal
|
||||
import math
|
||||
import pathlib
|
||||
import re
|
||||
import sys
|
||||
import typing
|
||||
|
||||
from todo_table import BLOCKED_BY, cells, HEADER_START, Item, items_table, MOVES, OLD_SHAPE, parse_row, Shape, shape_of, Table, table_rows
|
||||
from todo_table import BLOCKED_BY, cells, CODE_HEALTH, DETAILS, HEADER_START, Item, item_details, items_table, MOVES, OLD_SHAPE, parse_row, renames, risk, Shape, SHAPE, shape_of, Table, table_rows, version
|
||||
from failure import Failure
|
||||
from markdown_text import FENCE, sections
|
||||
from comprehension_history import FLOOR, HISTORY, latest_overall
|
||||
from markdown_text import listed, sections
|
||||
from file_writes import replace_file
|
||||
|
||||
# What each achieve goal weighs of the one above it; docs/decisions.md records the choice.
|
||||
GOAL_STEP = 0.97
|
||||
# Code health weighs this many times its weight by position while the comprehension panel's overall is under FLOOR, or unmeasured; lilleman's choice, which docs/decisions.md records.
|
||||
UNDER_FLOOR = 4
|
||||
# Any **Void:** line of README.md's ## Goals; ranked_goals accepts only `**Void:** code health, since <reason>.`, as ~/.claude/CLAUDE.md → "Shared goal" spells it.
|
||||
VOID = re.compile(r"^\*\*Void:\*\* (.*)$", re.M)
|
||||
# A docs/decisions.md title opting the project out of the comprehension check, as larv-review's SKILL.md → "Opt-out" spells it.
|
||||
OPTED_OUT = re.compile(r"^## review opt-out:.*\bcomprehension check\b", re.M)
|
||||
LARGEST_FORMULA = 200
|
||||
LONGEST_FORMULA = 4 * LARGEST_FORMULA
|
||||
OPERATORS = (ast.Add, ast.BinOp, ast.Div, ast.Expression, ast.Load, ast.Mult, ast.Pow, ast.Sub, ast.UAdd, ast.UnaryOp, ast.USub)
|
||||
@@ -87,7 +112,7 @@ WEIGHTS_HEADER = "| Goal | W |"
|
||||
FIRST = {"question": 0, "security": 1}
|
||||
# How README.md marks a goal; None where it marks it neither way.
|
||||
Mark = typing.Literal["Maintain", "Achieve"] | None
|
||||
RESHAPE = f"todo.md's items table is in the old shape, scoring A and G against goal weights todo.md states. Until todo.md has the shape rank_todo.py --help shows, reshaping it is the project's only work, as ~/.claude/CLAUDE.md → 'Working loop' says: mark README.md's goals **Maintain:** or **Achieve:**, name each item's {MOVES}, and set the bar below the score of every item to keep"
|
||||
RESHAPE = f"todo.md's items table is in the old shape, scoring A and G against goal weights todo.md states. Until todo.md has the shape rank_todo.py --help shows, reshaping it is the project's only work, as ~/.claude/CLAUDE.md → 'Working loop' says: mark README.md's goals **Maintain:** or **Achieve:**, name each item's {MOVES}, score its L, E and I in place of C, and set the bar below the score of every item to keep"
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -96,9 +121,9 @@ class Scoring:
|
||||
formula: ast.Expression
|
||||
bar: float
|
||||
next_id: int
|
||||
# README.md's goals in reading order, each with its mark.
|
||||
# Every goal in rank order, each with its mark: code health first, unless README.md voids it, then README.md's goals in reading order. In OLD_SHAPE an item may name only the goals weights holds.
|
||||
goals: dict[str, Mark]
|
||||
# The weight of each goal an item may name: in OLD_SHAPE every goal, at the weight todo.md states; else each goal goal_weights weighs.
|
||||
# The weight of each goal an item may name: in OLD_SHAPE each of README.md's goals, at the weight todo.md states; else each goal goal_weights weighs.
|
||||
weights: dict[str, float]
|
||||
|
||||
|
||||
@@ -106,7 +131,7 @@ class Scoring:
|
||||
class Ranked:
|
||||
text: str
|
||||
under_bar: list[str]
|
||||
# What ranking prints and --check does not: an old-shape table's call to reshape, a README with no achieve goal, and each dropped blocker ID, since a mistyped ID drops the same way.
|
||||
# What ranking prints and --check does not: an old-shape table's call to reshape, a README that voids code health and marks no goal **Achieve:**, and each dropped blocker ID, since a mistyped ID drops the same way.
|
||||
notes: list[str]
|
||||
|
||||
|
||||
@@ -123,19 +148,25 @@ def main(argv: list[str]) -> int:
|
||||
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)
|
||||
ranked = rank_file(todo)
|
||||
if isinstance(ranked, Failure):
|
||||
return fail(ranked)
|
||||
if ranked.text != texts[0]:
|
||||
unwritten = write(todo, ranked.text)
|
||||
if unwritten:
|
||||
return fail(unwritten)
|
||||
return 1 if ranked.under_bar else 0
|
||||
|
||||
|
||||
def rank_file(todo: pathlib.Path) -> Ranked | Failure:
|
||||
"""Rank todo in place: rank what read_all reads, write todo where that changed it, and print the notes and under-bar lines on stderr."""
|
||||
texts = read_all(todo)
|
||||
if isinstance(texts, Failure):
|
||||
return texts
|
||||
ranked = rank(*texts)
|
||||
if isinstance(ranked, Failure):
|
||||
return ranked
|
||||
if ranked.text != texts[0] and (unwritten := write(todo, ranked.text)):
|
||||
return unwritten
|
||||
for line in ranked.notes + ranked.under_bar:
|
||||
print(f"{todo}: {line}", file=sys.stderr)
|
||||
return 1 if ranked.under_bar else 0
|
||||
return ranked
|
||||
|
||||
|
||||
def check_failures(todo: pathlib.Path) -> list[str]:
|
||||
@@ -162,10 +193,10 @@ def parse_args(argv: list[str]) -> tuple[bool, pathlib.Path] | Failure:
|
||||
return "--check" in argv, pathlib.Path(paths[0] if paths else "todo.md")
|
||||
|
||||
|
||||
def read_all(todo: pathlib.Path) -> tuple[str, str, str] | Failure:
|
||||
"""todo.md, the README.md beside it, and its docs/decisions.md, empty when there is none."""
|
||||
def read_all(todo: pathlib.Path) -> tuple[str, str, str, str] | Failure:
|
||||
"""todo.md, the README.md beside it, and its docs/decisions.md and docs/comprehension-history.md, each empty when there is none."""
|
||||
texts = []
|
||||
for path, missing in ((todo, "every project keeps a todo.md beside its README.md, and rank_todo.py --help shows one"), (todo.parent / "README.md", "rank_todo.py weighs goals from the README.md beside todo.md"), (todo.parent / "docs" / "decisions.md", None)):
|
||||
for path, missing in ((todo, "every project keeps a todo.md beside its README.md, and rank_todo.py --help shows one"), (todo.parent / "README.md", "rank_todo.py weighs goals from the README.md beside todo.md"), (todo.parent / "docs" / "decisions.md", None), (todo.parent / HISTORY, None)):
|
||||
try:
|
||||
texts.append(path.read_text(encoding="utf-8"))
|
||||
except FileNotFoundError:
|
||||
@@ -176,7 +207,7 @@ def read_all(todo: pathlib.Path) -> tuple[str, str, str] | Failure:
|
||||
return Failure(f"{path}: {failure.strerror}")
|
||||
except UnicodeDecodeError:
|
||||
return Failure(f"{path}: not UTF-8")
|
||||
return texts[0], texts[1], texts[2]
|
||||
return texts[0], texts[1], texts[2], texts[3]
|
||||
|
||||
|
||||
def write(path: pathlib.Path, text: str) -> Failure | None:
|
||||
@@ -184,13 +215,13 @@ def write(path: pathlib.Path, text: str) -> Failure | None:
|
||||
return Failure(f"{path}: {unwritten.reason}") if unwritten else None
|
||||
|
||||
|
||||
def rank(text: str, readme: str, decisions: str) -> Ranked | Failure:
|
||||
def rank(text: str, readme: str, decisions: str, history: str) -> Ranked | Failure:
|
||||
lines = text.split("\n")
|
||||
table = read_table(lines)
|
||||
if isinstance(table, Failure):
|
||||
return table
|
||||
shape = shape_of(table.columns)
|
||||
scoring = read_scoring(text, lines, readme, shape)
|
||||
scoring = read_scoring(text, lines, readme, decisions, history, shape)
|
||||
if isinstance(scoring, Failure):
|
||||
return scoring
|
||||
items = read_items(table, scoring)
|
||||
@@ -198,6 +229,10 @@ def rank(text: str, readme: str, decisions: str) -> Ranked | Failure:
|
||||
return items
|
||||
if uncited := check_citations(items, decisions):
|
||||
return uncited
|
||||
if isinstance(marked := renames(text), Failure):
|
||||
return marked
|
||||
if live := next((item for item in items if item.release in marked), None):
|
||||
return Failure(f"todo.md marks release {version(live.release)} renamed but files item {live.id} under it; drop the mark or move the item")
|
||||
scored = ordered(items, scoring)
|
||||
if isinstance(scored, Failure):
|
||||
return scored
|
||||
@@ -208,11 +243,15 @@ def rank(text: str, readme: str, decisions: str) -> Ranked | Failure:
|
||||
return Ranked(ranked, under_bar, notes(items, scoring))
|
||||
|
||||
|
||||
# The columns ranking fills itself, so a table without one gains it.
|
||||
WRITTEN = (BLOCKED_BY, "R", "Score")
|
||||
|
||||
|
||||
def rewrite_table(lines: list[str], table: Table, shape: Shape, scored: list[tuple[Item, float]]) -> str:
|
||||
"""lines with the table's rows in scored's order, under a header naming every column of shape, so a table from before BLOCKED_BY joined gains the column."""
|
||||
columns = shape.columns
|
||||
"""lines with the table's rows in scored's order, under a header naming, in shape's order, each column the table holds and each of WRITTEN."""
|
||||
columns = tuple(column for column in shape.columns if column in table.columns or column in WRITTEN)
|
||||
header = ["| " + " | ".join(columns) + " |", "|" + "---|" * len(columns)]
|
||||
rows = [render_item(item, value, shape) for item, value in scored]
|
||||
rows = [render_item(item, value, shape, columns) for item, value in scored]
|
||||
return "\n".join(lines[:table.header] + header + rows + lines[table.start + len(table.rows):])
|
||||
|
||||
|
||||
@@ -222,7 +261,7 @@ def notes(items: list[Item], scoring: Scoring) -> list[str]:
|
||||
if scoring.shape is OLD_SHAPE:
|
||||
return [RESHAPE] + dropped
|
||||
# Printed so the under-bar lines it causes do not read as items of low value.
|
||||
unweighed = [] if any(scoring.weights.values()) else ["README.md marks no goal **Achieve:**, so every item scores V 0"]
|
||||
unweighed = [] if any(scoring.weights.values()) else ["README.md voids code health and marks no goal **Achieve:**, so every item scores V 0"]
|
||||
return unweighed + dropped
|
||||
|
||||
|
||||
@@ -254,8 +293,8 @@ def under_the_bar(item: Item, value: float, bar: float, items: list[Item]) -> st
|
||||
return f"item {item.id} scores {value:.1f}, under the bar {bar:g}; delete it{blocked}, or mark it with a reason the bar does not apply"
|
||||
|
||||
|
||||
def read_scoring(text: str, lines: list[str], readme: str, shape: Shape) -> Scoring | Failure:
|
||||
goals = readme_goals(readme)
|
||||
def read_scoring(text: str, lines: list[str], readme: str, decisions: str, history: str, shape: Shape) -> Scoring | Failure:
|
||||
goals = ranked_goals(readme, decisions)
|
||||
if isinstance(goals, Failure):
|
||||
return goals
|
||||
formula = parse_formula(stated(text, "Score"), variables(shape))
|
||||
@@ -267,18 +306,41 @@ def read_scoring(text: str, lines: list[str], readme: str, shape: Shape) -> Scor
|
||||
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")
|
||||
numbers = [number for number, _ in goals]
|
||||
if shape is OLD_SHAPE:
|
||||
weights = parse_weights(lines, numbers)
|
||||
elif WEIGHTS_HEADER in lines:
|
||||
weights = Failure(f"todo.md holds a goal weights table beside a {MOVES} column; drop the table, since rank_todo.py weighs each achieve goal by its position in README.md")
|
||||
else:
|
||||
weights = goal_weights(goals)
|
||||
weights = weigh(lines, history, goals, shape)
|
||||
if isinstance(weights, Failure):
|
||||
return weights
|
||||
return Scoring(shape, formula, bar, int(next_id), dict(goals), weights)
|
||||
|
||||
|
||||
def ranked_goals(readme: str, decisions: str) -> list[tuple[str, Mark]] | Failure:
|
||||
"""Every goal in rank order, each with its mark: code health first, unless README.md voids it, then README.md's goals in reading order. A **Void:** line other than `**Void:** code health, since <reason>.` fails, and so does a docs/decisions.md that opts out of the comprehension check where README.md keeps code health, since the goal then has no signal."""
|
||||
goals = readme_goals(readme)
|
||||
if isinstance(goals, Failure):
|
||||
return goals
|
||||
voids = VOID.findall("".join(sections(readme).get("Goals", [])))
|
||||
if other := [void for void in voids if not void.startswith(f"{CODE_HEALTH}, since ")]:
|
||||
if other[0].lower().startswith(CODE_HEALTH):
|
||||
return Failure(f"README.md's ## Goals voids code health as `{other[0]}`; spell the void exactly `**Void:** {CODE_HEALTH}, since <reason>.`")
|
||||
return Failure(f"README.md's ## Goals voids `{other[0]}`; only code health may be voided, as `**Void:** {CODE_HEALTH}, since <reason>.`")
|
||||
if voids:
|
||||
return goals
|
||||
if OPTED_OUT.search(decisions):
|
||||
return Failure(f"docs/decisions.md opts out of the comprehension check, so code health has no signal; void it in README.md's ## Goals with `**Void:** {CODE_HEALTH}, since <reason>.`, as ~/.claude/CLAUDE.md → 'Shared goal' says")
|
||||
return [(CODE_HEALTH, "Achieve"), *goals]
|
||||
|
||||
|
||||
def weigh(lines: list[str], history: str, goals: list[tuple[str, Mark]], shape: Shape) -> dict[str, float] | Failure:
|
||||
"""Each goal's weight. In OLD_SHAPE, README.md's goals weigh what todo.md states, and code health has no weight, so no item may name it. Otherwise goal_weights gives each its weight, at the overall latest_overall reads where the goals hold code health."""
|
||||
if shape is OLD_SHAPE:
|
||||
return parse_weights(lines, [number for number, _ in goals if number != CODE_HEALTH])
|
||||
if WEIGHTS_HEADER in lines:
|
||||
return Failure(f"todo.md holds a goal weights table beside a {MOVES} column; drop the table, since rank_todo.py weighs the goals itself, as its --help says")
|
||||
overall = latest_overall(history) if CODE_HEALTH in dict(goals) else None
|
||||
if isinstance(overall, Failure):
|
||||
return overall
|
||||
return goal_weights(goals, overall)
|
||||
|
||||
|
||||
def read_table(lines: list[str]) -> Table | Failure:
|
||||
"""The items table, held to its shape's columns and alone under ## Items."""
|
||||
if "## Items" not in lines:
|
||||
@@ -288,25 +350,31 @@ def read_table(lines: list[str]) -> Table | Failure:
|
||||
return Failure(f"## Items holds no table whose header opens {HEADER_START}; rank_todo.py --help shows a valid one")
|
||||
if isinstance(table, Failure):
|
||||
return table
|
||||
# A table without C fails, so no chunk starts on an unscored item.
|
||||
if "C" not in table.columns:
|
||||
return Failure("todo.md's items table has no C column; add one after S, and score each item's C from 1 to 10 per rank_todo.py --help")
|
||||
return unknown_columns(table) or outside_items(lines, table) or table
|
||||
shape = shape_of(table.columns)
|
||||
if missing := [column for column in shape.risk_columns if column not in table.columns]:
|
||||
old = older_columns(table, shape)
|
||||
dropped = f", and drop {listed(old, 'and')}" if old else ""
|
||||
columns = f"{listed(missing, 'and')} column; add it" if len(missing) == 1 else f"{listed(missing, 'and')} columns; add them"
|
||||
return Failure(f"todo.md's items table has no {columns}, scoring each item's {listed(shape.risk_columns, 'and')} as rank_todo.py --help shows{dropped}")
|
||||
return unknown_columns(table, shape) or outside_items(lines, table) or table
|
||||
|
||||
|
||||
def unknown_columns(table: Table) -> Failure | None:
|
||||
def unknown_columns(table: Table, shape: Shape) -> Failure | None:
|
||||
"""Why ranking, which writes only the columns of the table's shape, would drop one of the table's columns; None when it would drop none."""
|
||||
known = shape_of(table.columns).columns
|
||||
unknown = [column for column in table.columns if column not in known]
|
||||
if old := [column for column in unknown if column in OLD_SHAPE.columns]:
|
||||
listed = old[0] if len(old) == 1 else f"{', '.join(old[:-1])} and {old[-1]}"
|
||||
kind = f"a column of the old shape that {MOVES} replaced; drop it" if len(old) == 1 else f"columns of the old shape that {MOVES} replaced; drop them"
|
||||
return Failure(f"todo.md's items table has {listed}, {kind}")
|
||||
unknown = [column for column in table.columns if column not in shape.columns]
|
||||
if old := older_columns(table, shape):
|
||||
kind = "a column of an older shape; drop it" if len(old) == 1 else "columns of an older shape; drop them"
|
||||
return Failure(f"todo.md's items table has {listed(old, 'and')}, {kind}, as rank_todo.py --help shows")
|
||||
if unknown:
|
||||
return Failure(f"todo.md's items table has the column {', '.join(unknown)}, which this rank_todo.py does not know; the columns it knows are {', '.join(known)}. Rename it, or move this machine to the release that added it")
|
||||
return Failure(f"todo.md's items table has the column {', '.join(unknown)}, which this rank_todo.py does not know; the columns it knows are {', '.join(shape.columns)}. Rename it, or move this machine to the release that added it")
|
||||
return None
|
||||
|
||||
|
||||
def older_columns(table: Table, shape: Shape) -> list[str]:
|
||||
"""The table's columns that only OLD_SHAPE knows, where the table is in SHAPE."""
|
||||
return [column for column in table.columns if column not in SHAPE.columns and column in OLD_SHAPE.columns] if shape is SHAPE else []
|
||||
|
||||
|
||||
def read_items(table: Table, scoring: Scoring) -> list[Item] | Failure:
|
||||
items = []
|
||||
for row in table.rows:
|
||||
@@ -346,7 +414,7 @@ def blockers_first(scored: list[tuple[Item, float]]) -> list[tuple[Item, float]]
|
||||
for item, _ in scored:
|
||||
for blocker in item.blocked_by:
|
||||
if blocker in held and held[blocker][0].release > item.release:
|
||||
later, earlier = release_name(held[blocker][0]), release_name(item)
|
||||
later, earlier = version(held[blocker][0].release), version(item.release)
|
||||
return Failure(f"item {item.id}, in release {earlier}, is blocked by item {blocker}, in later release {later}; move item {blocker} to release {earlier} or earlier, or item {item.id} to release {later} or later")
|
||||
result: list[tuple[Item, float]] = []
|
||||
for item, _ in scored:
|
||||
@@ -375,10 +443,6 @@ def place(id_: int, held: dict[int, tuple[Item, float]], position: dict[int, int
|
||||
return [*added, (dataclasses.replace(item, blocked_by=tuple(sorted(blockers))), value)]
|
||||
|
||||
|
||||
def release_name(item: Item) -> str:
|
||||
return ".".join(str(part) for part in item.release)
|
||||
|
||||
|
||||
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))
|
||||
@@ -412,13 +476,15 @@ def readme_goals(readme: str) -> list[tuple[str, Mark]] | Failure:
|
||||
return goals
|
||||
|
||||
|
||||
def goal_weights(goals: list[tuple[str, Mark]]) -> dict[str, float] | Failure:
|
||||
"""Each achieve goal's sum-reciprocal weight: the one ranked k of n in reading order weighs (1/k) / (1 + 1/2 + ... + 1/n). Each maintain goal weighs as the heaviest achieve goal, since a broken one outranks any achieve goal; only a defect that restores it may name it. Every weight is 0 where README.md marks no goal **Achieve:**, so every item scores V 0 and only an exempt one passes the bar."""
|
||||
def goal_weights(goals: list[tuple[str, Mark]], overall: decimal.Decimal | None) -> dict[str, float] | Failure:
|
||||
"""Each achieve goal's weight: the one ranked k of n weighs GOAL_STEP ** (k - 1) / (1 + GOAL_STEP + ... + GOAL_STEP ** (n - 1)), so the weights sum to 1. Code health, where goals holds it, then weighs UNDER_FLOOR times that while the overall is under FLOOR or None, and the other goals keep their weights. Each maintain goal weighs as the heaviest achieve goal, since a broken one outranks any achieve goal; only a defect that restores it may name it. Every weight is 0 where goals holds no achieve goal, as where README.md voids code health and marks no goal **Achieve:**, so every item scores V 0 and only an exempt one passes the bar."""
|
||||
if unmarked := [number for number, mark in goals if mark is None]:
|
||||
return Failure(f"README.md's goal {unmarked[0]} is marked neither **Maintain:** nor **Achieve:**; mark it, as ~/.claude/rules/goals-and-audience.md says, so rank_todo.py knows which goals score")
|
||||
achieve = [number for number, mark in goals if mark == "Achieve"]
|
||||
harmonic = sum(1 / rank for rank in range(1, len(achieve) + 1))
|
||||
weights = {number: 1 / rank / harmonic for rank, number in enumerate(achieve, 1)}
|
||||
total = sum(GOAL_STEP**rank for rank in range(len(achieve)))
|
||||
weights = {number: GOAL_STEP**rank / total for rank, number in enumerate(achieve)}
|
||||
if CODE_HEALTH in weights and (overall is None or overall < FLOOR):
|
||||
weights[CODE_HEALTH] *= UNDER_FLOOR
|
||||
heaviest = max(weights.values(), default=0.0)
|
||||
return weights | {number: heaviest for number, mark in goals if mark == "Maintain"}
|
||||
|
||||
@@ -542,43 +608,44 @@ def parse_weights(lines: list[str], goals: list[str]) -> dict[str, float] | Fail
|
||||
|
||||
|
||||
def parse_item(row: str, scoring: Scoring, table: Table) -> Item | Failure:
|
||||
"""The row as an item, refused where it names a goal it may not; in SHAPE, with the R its L, E and I give."""
|
||||
item = parse_row(row, table)
|
||||
if isinstance(item, Failure):
|
||||
return item
|
||||
if broken := cited_goals_failure(item, scoring):
|
||||
return broken
|
||||
if scoring.shape is OLD_SHAPE:
|
||||
if unknown := [goal for goal, _ in item.moves if goal not in scoring.weights]:
|
||||
return Failure(f"item {item.id} cites goal {', '.join(unknown)}, which the goal weights do not list")
|
||||
return item
|
||||
# R is written here, as the Score is, so --check finds a stale one, and a reader keeps the R the table stored.
|
||||
return dataclasses.replace(item, scores=item.scores | {"R": risk(item.scores["L"], item.scores["E"], item.scores["I"])})
|
||||
|
||||
|
||||
def cited_goals_failure(item: Item, scoring: Scoring) -> Failure | None:
|
||||
"""Why the item may not name one of the goals it names, such as one README.md voids or does not number; None when it may name each. todo_table's parse_moves holds the rules a Moves cell keeps on its own."""
|
||||
if scoring.shape is OLD_SHAPE:
|
||||
unknown = [goal for goal, _ in item.moves if goal not in scoring.weights]
|
||||
return Failure(f"item {item.id} cites goal {', '.join(unknown)}, which the goal weights do not list") if unknown else None
|
||||
for goal, _ in item.moves:
|
||||
if goal == CODE_HEALTH and goal not in scoring.goals:
|
||||
return Failure(f"item {item.id} names {CODE_HEALTH}, which README.md voids; drop it from the item's {MOVES}, or the void from README.md")
|
||||
if goal not in scoring.goals:
|
||||
return Failure(f"item {item.id} cites goal {goal}, which README.md's ## Goals does not number")
|
||||
if scoring.goals[goal] == "Maintain" and item.exempt != "defect":
|
||||
return Failure(f"item {item.id} cites goal {goal}, a maintain goal, which only a defect that restores it may name; name the achieve goals the item moves")
|
||||
return item
|
||||
return None
|
||||
|
||||
|
||||
def render_item(item: Item, value: float, shape: Shape) -> str:
|
||||
"""The item's row, each cell under its column of shape."""
|
||||
written = {"ID": str(item.id), "Release": release_name(item), BLOCKED_BY: ", ".join(map(str, item.blocked_by)), "Exempt": item.exempt, "Item": item.tagline, **{name: str(item.scores[name]) for name in shape.score_columns}, shape.goals_column: shape.write_goals(item.moves), "Score": f"{value:.1f}"}
|
||||
return "| " + " | ".join(written[column] for column in shape.columns) + " |"
|
||||
def render_item(item: Item, value: float, shape: Shape, columns: tuple[str, ...]) -> str:
|
||||
"""The item's row, each cell under its column."""
|
||||
written = {"ID": str(item.id), "Release": version(item.release), BLOCKED_BY: ", ".join(map(str, item.blocked_by)), "Exempt": item.exempt, "Item": item.tagline, **{name: str(score) for name, score in item.scores.items()}, shape.goals_column: shape.write_goals(item.moves), "Score": f"{value:.1f}"}
|
||||
return "| " + " | ".join(written[column] for column in columns) + " |"
|
||||
|
||||
|
||||
def rank_details(text: str, items: list[Item]) -> str | Failure:
|
||||
section = 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")
|
||||
section = DETAILS.search(text)
|
||||
details = item_details(text)
|
||||
if section is None or isinstance(details, Failure):
|
||||
return details if isinstance(details, Failure) else text
|
||||
if unknown := sorted(set(details) - {item.id for item in items}):
|
||||
return Failure(f"## Details holds item {', '.join(map(str, unknown))}, which the items table does not")
|
||||
headed = [f"### {item.id}. {item.tagline.strip('*').replace(chr(92) + '|', '|')}\n\n{details[item.id]}\n" for item in items if item.id in details]
|
||||
|
||||
@@ -9,8 +9,8 @@ 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
|
||||
FIGURE_FILE = re.compile(r"^- `(.+)` (\d+)$")
|
||||
FILES_KEPT = 10
|
||||
RECORD = "docs/reading-cost.md"
|
||||
RESET = "Reading cost reset, "
|
||||
RESET_AT = re.compile(rf"^{RESET}({STAMPED})$")
|
||||
@@ -28,8 +28,8 @@ def chunk_id(chunk: FinishedChunk) -> str:
|
||||
|
||||
|
||||
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 "")
|
||||
files = "".join(f"- `{path}` {times}\n" for path, times in ranked(reading.files))
|
||||
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{files}" if files else "")
|
||||
|
||||
|
||||
# The figures after the last reset, in the order their chunks finished: each machine appends its own archive's chunks.
|
||||
@@ -44,14 +44,14 @@ def readings_of(record: str) -> list[Reading] | Failure:
|
||||
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))}))))
|
||||
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_FILE.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 ranked(files: collections.Counter[str]) -> list[tuple[str, int]]:
|
||||
return sorted(files.items(), key=lambda item: (-item[1], item[0]))[:FILES_KEPT]
|
||||
|
||||
|
||||
def merged(record: str, figures: list[str]) -> str:
|
||||
@@ -65,7 +65,7 @@ def trend(readings: list[Reading]) -> str:
|
||||
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())))
|
||||
read_most = "".join(f"\n- `{path}` {times}" for path, times in ranked(sum((reading.files for reading in readings[-WINDOW:]), collections.Counter())))
|
||||
return f"Rising: {medians}\n\nRead most over the last {WINDOW} (opens and searches):\n{read_most}"
|
||||
|
||||
|
||||
|
||||
+11
-12
@@ -25,7 +25,6 @@ archive or the record cannot be read or written, or a figure in the record canno
|
||||
import dataclasses
|
||||
import os
|
||||
import pathlib
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
@@ -33,6 +32,7 @@ from reading_cost.measure import Checkout, measure, Reading
|
||||
from failure import Failure
|
||||
from reading_cost.figures import figure, merged, readings_of, RECORD, RESET, trend, unheld
|
||||
from transcript_archive.read import finished_chunks, read_threads
|
||||
from git_repo import git
|
||||
from transcript_archive.location import project_archive
|
||||
from file_writes import replace_file
|
||||
from utc_stamp import utc
|
||||
@@ -112,18 +112,17 @@ def failed(failure: Failure) -> int:
|
||||
|
||||
|
||||
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())
|
||||
found = git("rev-parse", "--path-format=absolute", "--show-toplevel", "--git-common-dir")
|
||||
if isinstance(found, Failure):
|
||||
return found
|
||||
if len(lines := found.splitlines()) != 2:
|
||||
return Failure(f"git rev-parse printed {found!r}, not a checkout's top folder and git directory on two lines")
|
||||
top, common = lines
|
||||
listed = git("ls-files", "-z", cwd=top)
|
||||
if isinstance(listed, Failure):
|
||||
return listed
|
||||
# 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"))))
|
||||
return Checkout(top, str(pathlib.Path(common).parent), frozenset(filter(None, listed.split("\0"))))
|
||||
|
||||
|
||||
def read_record(record: pathlib.Path) -> str | Failure:
|
||||
|
||||
@@ -11,9 +11,9 @@ 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."""
|
||||
"""What the worker and its subagents took in before the worker's first commit: tokens counts the new input tokens, and files counts how often each tracked file was opened or searched, by its path in the checkout."""
|
||||
tokens: int
|
||||
places: collections.Counter[str]
|
||||
files: collections.Counter[str]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -32,8 +32,8 @@ def measure(threads: list[bytes], checkout: Checkout, home: str) -> Reading | No
|
||||
before = [[entry for entry in thread if entry.get("type") == "assistant" and str(entry.get("timestamp", "")) < commit] for thread in (worker, *subagents)]
|
||||
reads = [reads_of(part, str(entry.get("cwd") or "/"), home) for thread in before for entry in thread for part in assistant_parts(entry)]
|
||||
roots = [checkout.main_root, *(added for found in reads for added in found.added)]
|
||||
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)
|
||||
files = collections.Counter(file for found in reads for path in found.read if (file := relative(path, roots)) in checkout.tracked)
|
||||
return Reading(sum(map(tokens_in, before)), files)
|
||||
|
||||
|
||||
def entries_of(raw: bytes) -> list[dict]:
|
||||
|
||||
@@ -15,7 +15,7 @@ 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 reading_cost import figures, main, measure
|
||||
from transcript_archive.read import finished_chunks, FinishedChunk
|
||||
from test_env import isolated_env
|
||||
from transcript_archive import outcomes
|
||||
@@ -160,5 +160,29 @@ class ReadingCostTool(unittest.TestCase):
|
||||
self.assertIn("not a git repository", ran.stderr)
|
||||
|
||||
|
||||
class Located(unittest.TestCase):
|
||||
def test_lists_the_whole_checkout_from_a_folder_inside_it(self):
|
||||
temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(temp.cleanup)
|
||||
root = pathlib.Path(temp.name).resolve()
|
||||
(root / "sub").mkdir()
|
||||
(root / "a.txt").write_text("a")
|
||||
(root / "sub" / "b.txt").write_text("b")
|
||||
for args in (("init", "--quiet"), ("add", ".")):
|
||||
subprocess.run(["git", *args], check=True, cwd=root, env=isolated_env())
|
||||
with contextlib.chdir(root / "sub"):
|
||||
found = main.located()
|
||||
self.assertEqual(found, Checkout(str(root), str(root), frozenset({"a.txt", "sub/b.txt"})))
|
||||
|
||||
def test_fails_in_a_checkout_whose_path_holds_a_newline(self):
|
||||
temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(temp.cleanup)
|
||||
root = pathlib.Path(temp.name, "a\nb")
|
||||
root.mkdir()
|
||||
subprocess.run(["git", "init", "--quiet"], check=True, cwd=root, env=isolated_env())
|
||||
with contextlib.chdir(root):
|
||||
self.assertIsInstance(main.located(), Failure)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -41,6 +41,10 @@ class Gitignore(unittest.TestCase):
|
||||
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_no_python_module_or_test_under_bin(self):
|
||||
ignored = subprocess.run(["git", "ls-files", "-oi", "--exclude-standard", "--", "bin/*.py", "bin/**/*.py"], 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,38 @@
|
||||
import pathlib
|
||||
import re
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from review_passes import PASS_AGENTS, PASSES
|
||||
from repo_checks.test_python_floor import ROOT
|
||||
from rule_hook.reviewer_rung import SEAT, SECURITY_OPENER
|
||||
|
||||
OPENING = re.compile(r"^## Opening\n+```\n([^\n]+?\.)(?: |\n)", re.MULTILINE)
|
||||
# An agent's name, as opposed to the skill or plugin that reviews a pass.
|
||||
AGENT_NAME = re.compile(r"[a-z]+(?:-[a-z]+)*")
|
||||
# A row of the pass table: its pass and its reviewer cell.
|
||||
PASS_ROW = re.compile(r"^\| (?!Pass \|)([A-Z][a-z -]+?) \| ([^|]+?) \|", re.MULTILINE)
|
||||
LARV_REVIEW = (ROOT / "skills" / "larv-review" / "SKILL.md").read_text(encoding="utf-8")
|
||||
PASS_TABLE = LARV_REVIEW.split("## 3. Passes", 1)[1].split("A comment is prose", 1)[0]
|
||||
|
||||
|
||||
class ReviewerLaunches(unittest.TestCase):
|
||||
"""rule-hook holds a review launch to its rung by recognising it, and `larv-review round-count` counts the passes by name; these fail when what they recognise drifts from what the skills launch."""
|
||||
|
||||
def test_the_passes_and_their_agents_are_the_ones_larv_review_s_pass_table_names_in_its_order(self):
|
||||
rows = [(name.lower(), reviewer if AGENT_NAME.fullmatch(reviewer) else None) for name, reviewer in PASS_ROW.findall(PASS_TABLE)]
|
||||
self.assertEqual(rows, list(PASS_AGENTS.items()))
|
||||
|
||||
def test_the_seat_opening_is_the_sentence_that_opens_every_seat_prompt(self):
|
||||
opening = OPENING.search((ROOT / "skills" / "comprehension-panel" / "seat-prompts.md").read_text(encoding="utf-8"))
|
||||
self.assertIsNotNone(opening, "seat-prompts.md has a `## Opening` section whose code block opens with a sentence")
|
||||
self.assertEqual(SEAT, opening.group(1) if opening else "")
|
||||
|
||||
def test_the_security_opening_is_the_sentence_larv_review_has_the_security_pass_open_with(self):
|
||||
security = LARV_REVIEW.split("### Security", 1)[1].split("### Overrides", 1)[0]
|
||||
self.assertIn(SECURITY_OPENER, security)
|
||||
|
||||
def test_larv_review_has_the_tool_make_the_reports_folder_rule_hook_lets_a_reviewer_write_into(self):
|
||||
self.assertIn("`~/.claude/bin/larv-review review-folder`", LARV_REVIEW)
|
||||
@@ -0,0 +1,26 @@
|
||||
import json
|
||||
import pathlib
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from settings_filter import cleaned
|
||||
from git_repo import git
|
||||
from repo_checks.test_python_floor import ROOT
|
||||
|
||||
INSTALL = "git config filter.settings.clean bin/settings_filter.py"
|
||||
|
||||
|
||||
class Settings(unittest.TestCase):
|
||||
def test_the_stored_settings_hold_no_model_and_sorted_keys(self):
|
||||
# The index, not the working file: the working file holds this machine's model in Claude Code's key order.
|
||||
stored = git("show", ":settings.json", cwd=str(ROOT))
|
||||
self.assertIsInstance(stored, str, stored)
|
||||
fix = f"commit settings.json with the filter on: {INSTALL}"
|
||||
self.assertNotIn("model", json.loads(stored), fix)
|
||||
self.assertEqual(stored, cleaned(json.loads(stored)), fix)
|
||||
|
||||
def test_the_readme_installs_the_filter_git_attributes_names_for_the_root_settings_only(self):
|
||||
self.assertEqual("/settings.json filter=settings\n", (ROOT / ".gitattributes").read_text(encoding="utf-8"))
|
||||
self.assertIn(f"{INSTALL}\n", (ROOT / "README.md").read_text(encoding="utf-8"))
|
||||
@@ -15,5 +15,5 @@ class Types(unittest.TestCase):
|
||||
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", "-m", "git_repo", "-p", "judge_replay", "-p", "larv_review", "-p", "loop_claude", "-m", "markdown_text", "-p", "metric_bench", "-m", "project_key", "-m", "rank_todo", "-m", "round_titles", "-p", "reading_cost", "-p", "rule_hook", "-p", "rung_replay", "-p", "score_outcomes", "-p", "stability_replay", "-p", "subagent_rung", "-m", "shell_command", "-m", "statusline", "-m", "todo_table", "-p", "transcript_archive", "-m", "utc_stamp"], capture_output=True, cwd=ROOT / "bin", text=True)
|
||||
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", "chunk_preflight", "-p", "claude_code", "-m", "comprehension_history", "-m", "git_repo", "-p", "judge_replay", "-p", "larv_review", "-p", "loop_claude", "-m", "markdown_text", "-p", "metric_bench", "-m", "project_key", "-m", "rank_todo", "-p", "reading_cost", "-m", "review_passes", "-p", "review_replay", "-m", "round_titles", "-p", "rule_hook", "-p", "rung_replay", "-p", "score_outcomes", "-m", "settings_filter", "-m", "shell_command", "-m", "statusline", "-p", "subagent_rung", "-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)
|
||||
|
||||
@@ -5,7 +5,7 @@ import sys
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
|
||||
|
||||
from stability_replay import main
|
||||
from review_replay import main
|
||||
from loop_claude.effects import system_effects
|
||||
|
||||
sys.exit(main.main(sys.argv[1:], os.environ, pathlib.Path.home(), system_effects()))
|
||||
@@ -0,0 +1,11 @@
|
||||
"""The chunk's review folder, where each reviewer writes its report: skills/larv-review/SKILL.md → "Reports"."""
|
||||
import os
|
||||
|
||||
# Why here: docs/decisions.md → `review: each reviewer under agents/ writes its full report into the chunk's review folder`.
|
||||
REPORTS = ".local/state/larv-review"
|
||||
|
||||
|
||||
def review_folder(home: str, worktree: str) -> str:
|
||||
"""The review folder of the chunk whose worktree is at worktree: its path relative to home, or to / outside it, under REPORTS."""
|
||||
inside = worktree.startswith(home.rstrip("/") + "/")
|
||||
return os.path.join(home, REPORTS, os.path.relpath(worktree, home) if inside else worktree.lstrip("/"))
|
||||
@@ -0,0 +1,16 @@
|
||||
"""The passes of larv-review, as skills/larv-review/SKILL.md → "Passes" lists them."""
|
||||
import typing
|
||||
|
||||
# A pass an agent under agents/ reviews, in lower case. A Literal cannot be built from `PASS_AGENTS`, so test_review_passes holds the two together.
|
||||
ReviewedPass = typing.Literal["architecture", "principles", "overrides", "stability", "product-owner", "prose"]
|
||||
# Each pass in the order of SKILL.md's pass table, and the agent under agents/ that reviews it; None where a skill or plugin does. The auto-reviewer is left out: larv-review counts its rounds from its reviews on the PR, not from commit titles.
|
||||
PASS_AGENTS: dict[str, str | None] = {"architecture": "systems-architect", "principles": "principles-auditor", "full scan": None, "security": None, "overrides": "override-reviewer", "stability": "stability-reviewer", "product-owner": "product-owner-reviewer", "prose": "prose-reviewer"}
|
||||
PASSES = tuple(PASS_AGENTS)
|
||||
|
||||
|
||||
def _reviewed(name: str) -> typing.TypeGuard[ReviewedPass]:
|
||||
return name in typing.get_args(ReviewedPass)
|
||||
|
||||
|
||||
# The passes that have an agent. A pass missing from `ReviewedPass` drops out of it, which test_review_passes fails on.
|
||||
REVIEWERS: dict[ReviewedPass, str] = {name: agent for name, agent in PASS_AGENTS.items() if agent and _reviewed(name)}
|
||||
@@ -0,0 +1,273 @@
|
||||
"""Replay a review pass's archived rounds on the rungs below the project's, to find which rungs may run its reviewer: docs/decisions.md → `routing: a review pass runs below the project's rung only on a rung that a replay of its rounds shows finding every 🔴 and 🟡 the project's rung finds`.
|
||||
|
||||
usage: review-replay <pass> <model>
|
||||
|
||||
<pass> is one of architecture, principles, overrides, stability, product-owner or prose.
|
||||
<model> is a project model on the routing ladder, such as claude-opus-5-5. The tool replays the
|
||||
latest 10 archived rounds of the pass whose report holds a 🔴 or 🟡 finding, from the projects
|
||||
that ~/.claude/loop-claude-models.json runs on the model. It replays each round on the code it
|
||||
reviewed: in a throwaway clone of the project's checkout, at the newest commit of origin/HEAD
|
||||
authored by the time the round began, on the branch the reviewer started on. The clone's default
|
||||
branch stands at the newest commit authored before the round's chunk began, so a diff against it
|
||||
shows the chunk's change. The prompt names the clone in place of the worktree it named, which the
|
||||
chunk has since removed. A round whose code it cannot find in this way is not replayed; stderr
|
||||
names it and why. The prompt also names a copy of the chunk's review folder in place of that
|
||||
folder, holding only the reports written after the chunk began and before the round did. A replay
|
||||
finds nothing where its prompt still names the review folder, or names a file there, other than a
|
||||
round's report, that the folder did not hold from the chunk's start until the round's.
|
||||
|
||||
It first replays every round on the project's rung, the reference reviewer. Archived findings
|
||||
that the reference reviewer does not raise again may rest on code or rules that have changed
|
||||
since; no rung is held to them. It then replays the rounds where the reference raised any, on each
|
||||
rung below, highest first, down to the ladder's lowest, and stops at the first rung that misses
|
||||
one. For each replay, claude on the project's rung matches the report to the archived findings,
|
||||
and counts a finding only where the report raises it as 🔴 or 🟡. The tool prints each finding a
|
||||
rung missed and the lowest rung that, like each rung above it, missed none. That rung is the
|
||||
evidence for running the pass's reviewer on it; the decision above records each run.
|
||||
|
||||
Like the loop, it tries claude three times running before it counts a reply as failed. A failed
|
||||
review or match finds nothing. Exit 1, saying why, on bad arguments, an unreadable archive or
|
||||
models file, no archived round to replay, or a usage limit.
|
||||
"""
|
||||
import dataclasses
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import typing
|
||||
|
||||
from transcript_archive.location import archive_root
|
||||
from rung_replay.command import arguments_or_exit, down_from, failed, limited_exit, projects_on
|
||||
from review_replay.rounds import authored_by, lost_inputs, report, reviewed_path, Round, round_from, sample, stamp_seconds
|
||||
from project_key import checkout_of
|
||||
from claude_code.reply import claude_reply, Limited
|
||||
from loop_claude.effects import Effects
|
||||
from failure import Failure
|
||||
from rung_replay.search import first_reply, replayed
|
||||
from claude_code.transcript import first_timestamped_line, read_transcript
|
||||
from model_routing.ladder import LADDER, project_rung, Rung
|
||||
from claude_code.entries import parse_entry, structured_output
|
||||
from review_folder import REPORTS, review_folder
|
||||
from review_passes import ReviewedPass, REVIEWERS
|
||||
|
||||
TOOL = "review-replay"
|
||||
USAGE = f"{TOOL} <pass> <model>, <pass> one of {', '.join(REVIEWERS)} and <model> a model on the routing ladder"
|
||||
LATEST = 10
|
||||
MATCH_SCHEMA = {"type": "object", "properties": {"found": {"type": "array", "items": {"type": "integer"}}}, "required": ["found"], "additionalProperties": False}
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Code:
|
||||
"""Where a round's reviewer read the code, the commit it read, the default branch, and where that branch stood as the chunk began."""
|
||||
path: str
|
||||
reviewed: str
|
||||
default: str
|
||||
base: str
|
||||
|
||||
|
||||
def main(argv: list[str], env: typing.Mapping[str, str], home: pathlib.Path, effects: Effects) -> int:
|
||||
read = arguments_or_exit(TOOL, argv, __doc__, USAGE, pass_and_model)
|
||||
if isinstance(read, int):
|
||||
return read
|
||||
reviewed, anchor = read
|
||||
rounds = archived_rounds(REVIEWERS[reviewed], anchor.model, archive_root(home, env), home)
|
||||
if isinstance(rounds, Failure):
|
||||
return failed(TOOL, rounds.reason)
|
||||
codes = codes_found(rounds, effects)
|
||||
if not codes:
|
||||
return failed(TOOL, f"no archived {reviewed} round of projects on {anchor.model} in {archive_root(home, env)} holds a 🔴 or 🟡 on code it can find")
|
||||
chosen = sample(list(codes), LATEST)
|
||||
# The project's rung is the reference, so the candidates start below it. They reach the ladder's lowest rung, below the lowest a worker routes to, since a pass may run below the worker's rung.
|
||||
candidates = down_from(anchor, LADDER[0])[1:]
|
||||
|
||||
def found_on(found: Round, rung: Rung) -> set[int] | Limited:
|
||||
return findings_found(found, codes[found], rung, anchor, home, effects)
|
||||
|
||||
replay = replayed(chosen, anchor, candidates, found_on, reproduced, f"{reviewed} rounds")
|
||||
if isinstance(replay, Limited):
|
||||
return limited_exit(TOOL, replay)
|
||||
print(report(reviewed, anchor.model, anchor, chosen, replay))
|
||||
return 0
|
||||
|
||||
|
||||
def pass_and_model(argv: list[str]) -> tuple[ReviewedPass, Rung] | None:
|
||||
"""The pass and the project's rung of the model argv names, as `<pass> <model>`; None for any other argv."""
|
||||
if len(argv) != 2:
|
||||
return None
|
||||
reviewed = next((kind for kind in REVIEWERS if kind == argv[0]), None)
|
||||
anchor = project_rung(argv[1])
|
||||
return (reviewed, anchor) if reviewed and anchor else None
|
||||
|
||||
|
||||
def codes_found(rounds: list[Round], effects: Effects) -> dict[Round, Code]:
|
||||
"""The code each round reviewed, as code_of finds it; stderr names each round left out, and why."""
|
||||
codes = {}
|
||||
for found in rounds:
|
||||
if isinstance(code := code_of(found, effects), Failure):
|
||||
print(f"{found.root} {found.at} is left out: {code.reason}", file=sys.stderr, flush=True)
|
||||
else:
|
||||
codes[found] = code
|
||||
return codes
|
||||
|
||||
|
||||
def reproduced(_: Round, found: set[int]) -> list[int]:
|
||||
"""The indexes of the round's findings that a replay on the reference reviewer found, which each lower rung is held to."""
|
||||
return sorted(found)
|
||||
|
||||
|
||||
def archived_rounds(reviewer: str, model: str, root: pathlib.Path, home: pathlib.Path) -> list[Round] | Failure:
|
||||
projects = projects_on(model, home)
|
||||
if isinstance(projects, Failure):
|
||||
return projects
|
||||
found = []
|
||||
try:
|
||||
for key in projects:
|
||||
for chunk in sorted(path for path in (root / key).glob("*") if path.is_dir()):
|
||||
found += chunk_rounds(reviewer, checkout_of(key, home), chunk)
|
||||
except (OSError, UnicodeDecodeError, ValueError) as failure:
|
||||
return Failure(f"could not read the archive {root}: {failure}")
|
||||
return found
|
||||
|
||||
|
||||
def chunk_rounds(reviewer: str, checkout: str, chunk: pathlib.Path) -> list[Round]:
|
||||
copies = sorted(chunk.glob("*.jsonl"))
|
||||
began = parse_entry(first_timestamped_line(copies[0].read_bytes())) if copies else None
|
||||
if not began or not isinstance(began.get("timestamp"), str):
|
||||
return []
|
||||
found = []
|
||||
for meta in sorted(chunk.glob("session/*/subagents/*.meta.json")):
|
||||
described = json.loads(meta.read_text(encoding="utf-8"))
|
||||
if not isinstance(described, dict) or described.get("agentType") != reviewer:
|
||||
continue
|
||||
entries = read_transcript(str(meta.with_name(meta.name.removesuffix(".meta.json") + ".jsonl")))
|
||||
if not isinstance(entries, Failure) and (one := round_from(reviewer, checkout, stamp_seconds(began["timestamp"]), entries)):
|
||||
found.append(one)
|
||||
return found
|
||||
|
||||
|
||||
def code_of(found: Round, effects: Effects) -> Code | Failure:
|
||||
"""Where, and at which commits, found's reviewer read the code, as the archive lets it be found again: the folder rounds.reviewed_path guesses from the prompt, and the commits authored by then.
|
||||
|
||||
Recording the reviewed commit at review time would need no such reading, but then no round archived before that change could be replayed. A wrong guess costs no rung: the reference reviewer, replayed on that code, finds fewer of the archived findings, and no rung is held to those.
|
||||
"""
|
||||
if not os.path.isdir(found.root):
|
||||
return Failure("the project has no checkout")
|
||||
path = reviewed_path(found.prompt, found.root, os.path.exists)
|
||||
if path is None:
|
||||
return Failure("the prompt names neither one removed worktree nor the checkout")
|
||||
default = effects.git("symbolic-ref", "--short", "refs/remotes/origin/HEAD", cwd=found.root)
|
||||
if isinstance(default, Failure):
|
||||
return default
|
||||
default = default.strip().removeprefix("origin/")
|
||||
log = effects.git("log", "--format=%H %at", f"refs/remotes/origin/{default}", cwd=found.root)
|
||||
main_line = effects.git("log", "--first-parent", "--format=%H %at", f"refs/remotes/origin/{default}", cwd=found.root)
|
||||
if isinstance(log, Failure):
|
||||
return log
|
||||
if isinstance(main_line, Failure):
|
||||
return main_line
|
||||
reviewed, base = authored_by(commit_log(log), found.seconds), authored_by(commit_log(main_line), found.began)
|
||||
if reviewed is None or base is None:
|
||||
return Failure("no commit was authored by then")
|
||||
return Code(path, reviewed, default, base)
|
||||
|
||||
|
||||
def commit_log(listed: str) -> list[tuple[str, float]]:
|
||||
return [(commit, float(authored)) for commit, authored in (line.split() for line in listed.splitlines())]
|
||||
|
||||
|
||||
def findings_found(found: Round, code: Code, rung: Rung, anchor: Rung, home: pathlib.Path, effects: Effects) -> set[int] | Limited:
|
||||
"""The indexes of the round's findings that its replay on rung reports, as the reviewer on anchor matches them."""
|
||||
reviewed: str | Failure | Limited = first_reply(lambda: review(found, code, rung, home, effects))
|
||||
if isinstance(reviewed, Limited):
|
||||
return reviewed
|
||||
matched: set[int] | Failure | Limited = reviewed if isinstance(reviewed, Failure) else first_reply(lambda: match(found.findings, reviewed, found.root, anchor, effects))
|
||||
if isinstance(matched, Failure):
|
||||
print(f" {found.root} {found.at} on {rung} found nothing: {matched.reason}", file=sys.stderr, flush=True)
|
||||
return set()
|
||||
return matched
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Copies:
|
||||
"""The throwaway copies a replay hands its reviewer: clone, of the project's checkout, and reports, of the chunk's review folder."""
|
||||
clone: str
|
||||
reports: str
|
||||
|
||||
|
||||
# The shell makes and removes the clone itself, and is tested on a temporary home as judge-replay's is; rounds.py's core takes the filesystem as an argument.
|
||||
def review(found: Round, code: Code, rung: Rung, home: pathlib.Path, effects: Effects) -> str | Failure | Limited:
|
||||
try:
|
||||
(home / REPORTS).mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
with tempfile.TemporaryDirectory(prefix="review-replay-", ignore_cleanup_errors=True) as clone, tempfile.TemporaryDirectory(prefix="review-replay-", dir=home / REPORTS, ignore_cleanup_errors=True) as reports:
|
||||
return reviewed_in(found, code, rung, Copies(clone, reports), home, effects)
|
||||
except OSError as failure:
|
||||
return Failure(f"could not prepare the replay: {failure}")
|
||||
|
||||
|
||||
def reviewed_in(found: Round, code: Code, rung: Rung, copies: Copies, home: pathlib.Path, effects: Effects) -> str | Failure | Limited:
|
||||
"""The report of found's reviewer on rung, replayed on code cloned into copies.clone, with its review folder copied into copies.reports."""
|
||||
folder = pathlib.Path(review_folder(str(home), code.path))
|
||||
copy_reports(found, folder, copies.reports)
|
||||
prompt = redirected(found.prompt, home, folder, code.path, copies)
|
||||
if isinstance(prompt, Failure):
|
||||
return prompt
|
||||
if lost := lost_inputs(prompt, copies.reports, lambda name: (pathlib.Path(copies.reports) / name).exists()):
|
||||
return Failure(f"the prompt names {', '.join(lost)}, which the review folder did not hold from the chunk's start until the round's")
|
||||
if isinstance(cloned := clone_reviewed(found, code, copies.clone, effects), Failure):
|
||||
return cloned
|
||||
reply = claude_reply(effects.claude, ["--agent", found.reviewer, *rung.flags()], copies.clone, prompt, "claude")
|
||||
if isinstance(reply, Failure | Limited):
|
||||
return reply
|
||||
return reply["result"] if isinstance(reply.get("result"), str) else Failure("the reviewer replied with no report")
|
||||
|
||||
|
||||
def copy_reports(found: Round, folder: pathlib.Path, reports: str) -> None:
|
||||
"""Copies into reports each report written to folder after found's chunk began and before its round did."""
|
||||
# The round's own report, any later one, and one from an earlier attempt at the item in the same worktree would each hand the reviewer the findings it is to find.
|
||||
for written in folder.iterdir() if folder.is_dir() else ():
|
||||
if written.is_file() and found.began <= written.stat().st_mtime < found.seconds:
|
||||
shutil.copy2(written, reports)
|
||||
|
||||
|
||||
def redirected(prompt: str, home: pathlib.Path, folder: pathlib.Path, worktree: str, copies: Copies) -> str | Failure:
|
||||
"""prompt naming copies.reports in place of the review folder, in either spelling, and copies.clone in place of the worktree; a Failure where it still names the review folder."""
|
||||
# Replace the folder's path first: outside home it contains the worktree's path, which replacing the worktree's would otherwise turn into the clone's.
|
||||
prompt = prompt.replace(str(folder), copies.reports).replace(f"~/{folder.relative_to(home)}", copies.reports).replace(worktree, copies.clone)
|
||||
# A spelling the rewrite misses, such as $HOME/, would leave the reviewer the live folder and the findings in it.
|
||||
if REPORTS in prompt.replace(copies.reports, ""):
|
||||
return Failure("the prompt names the review folder in a spelling the replay does not redirect")
|
||||
return prompt
|
||||
|
||||
|
||||
def clone_reviewed(found: Round, code: Code, clone: str, effects: Effects) -> Failure | None:
|
||||
"""Clones found's checkout into clone, on the commit its reviewer read, with the default branch where it stood as the chunk began."""
|
||||
for command in (
|
||||
("clone", "--quiet", "--shared", "--no-checkout", found.root, clone),
|
||||
("-C", clone, "update-ref", f"refs/remotes/origin/{code.default}", code.base),
|
||||
("-C", clone, "update-ref", f"refs/heads/{code.default}", code.base),
|
||||
("-C", clone, "checkout", "--quiet", *(("-B", found.branch) if found.branch and found.branch != code.default else ("--detach",)), code.reviewed),
|
||||
):
|
||||
if isinstance(ran := effects.git(*command, cwd=found.root), Failure):
|
||||
return ran
|
||||
return None
|
||||
|
||||
|
||||
def match(findings: tuple[str, ...], replay_report: str, root: str, rung: Rung, effects: Effects) -> set[int] | Failure | Limited:
|
||||
numbered = "\n\n".join(f"{n}. {finding}" for n, finding in enumerate(findings, 1))
|
||||
prompt = (
|
||||
"A code reviewer reported the numbered findings below. Another reviewer then reviewed the same change; its report follows them. "
|
||||
"List the number of each finding that the other report also raises as 🔴 or 🟡: the same defect, at the same place or from the same cause, however it is worded. "
|
||||
"A finding it raises only as 🟢 or ❓, or not at all, is not listed.\n\n"
|
||||
f"The findings:\n{numbered}\n\nThe other report:\n{replay_report}"
|
||||
)
|
||||
args = ["--json-schema", json.dumps(MATCH_SCHEMA), *rung.flags(), "--tools", ""]
|
||||
reply = claude_reply(effects.claude, args, root, prompt, "claude")
|
||||
if isinstance(reply, Failure | Limited):
|
||||
return reply
|
||||
output = structured_output(reply)
|
||||
numbers = output.get("found") if isinstance(output, dict) else None
|
||||
if not isinstance(numbers, list) or not all(isinstance(n, int) for n in numbers):
|
||||
return Failure(f"the match replied: {json.dumps(reply)}")
|
||||
return {n - 1 for n in numbers if 1 <= n <= len(findings)}
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Which archived stability rounds to replay, the code each reviewed, and the report: docs/decisions.md → `routing: the stability reviewer stays on the project's rung`."""
|
||||
"""Which archived rounds of a review pass to replay, the code each reviewed, and the report: docs/decisions.md → `routing: a review pass runs below the project's rung only on a rung that a replay of its rounds shows finding every 🔴 and 🟡 the project's rung finds`."""
|
||||
import dataclasses
|
||||
import datetime
|
||||
import pathlib
|
||||
@@ -14,11 +14,14 @@ FINDING = re.compile(r"^[\s#>*+|-]*(?:\d+[.)]\s*)?[*_]*\s*(?:🔴|🟡)")
|
||||
# An absolute path in a prompt, up to the quote, bracket or punctuation that ends it.
|
||||
PATH = re.compile(r"/[^\s`'\"()<>\[\],;]+")
|
||||
LINE_OR_STOP = re.compile(r"(?::\d+(?:-\d+)?)?[.:]?$")
|
||||
# A round's report, as skills/larv-review/SKILL.md → "Reports" names it, such as stability-round-2.md or principles-goals-round-1-rerun.md.
|
||||
ROUND_REPORT = re.compile(r"-round-\d+(?:-rerun)?\.md$")
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Round:
|
||||
"""One archived stability review of the checkout at root, at the UTC stamp at, in a chunk that began at began: its prompt, and the 🔴 and 🟡 findings its report holds, each with its lines up to the next blank line or finding."""
|
||||
"""One archived review by the agent reviewer of the checkout at root, at the UTC stamp at, in a chunk that began at began: its prompt, and the 🔴 and 🟡 findings its report holds, each with its lines up to the next blank line or finding."""
|
||||
reviewer: str
|
||||
root: str
|
||||
branch: str
|
||||
at: str
|
||||
@@ -31,15 +34,15 @@ class Round:
|
||||
return stamp_seconds(self.at)
|
||||
|
||||
|
||||
def round_from(root: str, began: float, entries: list[dict]) -> Round | None:
|
||||
"""The round a stability reviewer's transcript holds: its first entry's prompt, and its last text. None without a 🔴 or 🟡 finding to hold a rung to."""
|
||||
def round_from(reviewer: str, root: str, began: float, entries: list[dict]) -> Round | None:
|
||||
"""The round a reviewer's transcript holds: its first entry's prompt, and its last text. None without a 🔴 or 🟡 finding to hold a rung to."""
|
||||
reports = [text for found in entries for part in assistant_parts(found) if (text := part_text(part))]
|
||||
first = entries[0] if entries else {}
|
||||
if not stamped(first) or not reports or not (findings := recorded_findings(reports[-1])):
|
||||
return None
|
||||
prompt = content(first)
|
||||
prompt = prompt if isinstance(prompt, str) else "".join(part_text(part) or "" for part in parts(first))
|
||||
return Round(root, first.get("gitBranch", ""), first["timestamp"], began, prompt, tuple(findings))
|
||||
return Round(reviewer, root, first.get("gitBranch", ""), first["timestamp"], began, prompt, tuple(findings))
|
||||
|
||||
|
||||
def stamped(entry: dict) -> bool:
|
||||
@@ -84,6 +87,12 @@ def reviewed_path(prompt: str, root: str, exists: typing.Callable[[str], bool])
|
||||
return root if not gone and root in named else None
|
||||
|
||||
|
||||
def lost_inputs(prompt: str, reports: str, held: typing.Callable[[str], bool]) -> list[str]:
|
||||
"""The files the prompt names in reports, the copy of a round's review folder, that the copy does not hold, other than round reports. A report the copy lacks is the round's own or a later one, left out on purpose; any other file it lacks, such as a branch diff written again after the round began, would leave the replay without an input the round had."""
|
||||
named = [LINE_OR_STOP.sub("", path).removeprefix(reports + "/") for path in PATH.findall(prompt) if path.startswith(reports + "/")]
|
||||
return sorted({name for name in named if not ROUND_REPORT.search(name) and not held(name)})
|
||||
|
||||
|
||||
def authored_by(log: list[tuple[str, float]], seconds: float) -> str | None:
|
||||
"""The newest commit in log, which lists newest first, authored at or before seconds. A rebase keeps author times, so a merged branch's commits still say what it held."""
|
||||
return next((commit for commit, authored in log if authored <= seconds), None)
|
||||
@@ -94,10 +103,10 @@ def sample(rounds: list[Round], latest: int) -> list[Round]:
|
||||
return sorted(rounds, key=lambda found: (found.seconds, found.root))[-latest:]
|
||||
|
||||
|
||||
def report(model: str, reference: Rung, rounds: list[Round], replay: Replay[Round, int, set[int]]) -> str:
|
||||
def report(reviewed: str, model: str, reference: Rung, rounds: list[Round], replay: Replay[Round, int, set[int]]) -> str:
|
||||
total = sum(len(found_round.findings) for found_round in rounds)
|
||||
lines = [
|
||||
f"Replayed {len(rounds)} stability rounds of {model} projects, holding {total} 🔴 and 🟡 findings.",
|
||||
f"Replayed {len(rounds)} {reviewed} rounds of {model} projects, holding {total} 🔴 and 🟡 findings.",
|
||||
f"The reference reviewer, {reference}, found {sum(len(found) for found in replay.on_reference)} of them.",
|
||||
]
|
||||
for tried in replay.tried:
|
||||
+140
-38
@@ -10,17 +10,19 @@ import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
import unittest.mock
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from stability_replay.rounds import authored_by, recorded_findings, report, reviewed_path, Round, round_from, sample
|
||||
from review_replay.rounds import authored_by, lost_inputs, recorded_findings, report, reviewed_path, Round, round_from, sample, stamp_seconds
|
||||
from loop_claude.effects import Effects, system_effects
|
||||
from failure import Failure
|
||||
from stability_replay import main
|
||||
from review_replay import main
|
||||
from rung_replay.search import Miss, Replay, Tried
|
||||
from review_passes import REVIEWERS
|
||||
from model_routing.ladder import Rung
|
||||
|
||||
TOOL = pathlib.Path(__file__).resolve().parents[1] / "stability-replay"
|
||||
TOOL = pathlib.Path(__file__).resolve().parents[1] / "review-replay"
|
||||
REFERENCE = Rung("claude-opus-5-5", "medium")
|
||||
MIDDLE = Rung("claude-sonnet-5-5", "high")
|
||||
CHEAP = Rung("claude-haiku-5-5", "max")
|
||||
@@ -31,7 +33,7 @@ def entry(kind, text, **fields):
|
||||
|
||||
|
||||
def a_round(at, findings=("🔴 a",)):
|
||||
return Round("/code/p", "x", f"2026-10-14T10:00:0{at}Z", 0, "Review it.", tuple(findings))
|
||||
return Round("stability-reviewer", "/code/p", "x", f"2026-10-14T10:00:0{at}Z", 0, "Review it.", tuple(findings))
|
||||
|
||||
|
||||
class RecordedFindings(unittest.TestCase):
|
||||
@@ -50,19 +52,19 @@ class RoundFrom(unittest.TestCase):
|
||||
entry("assistant", "Reading."),
|
||||
entry("assistant", "BLOCK\n\n🔴 a.py:1 breaks"),
|
||||
]
|
||||
self.assertEqual(round_from("/code/p", 5.0, entries), Round("/code/p", "x", "2026-10-14T10:00:00.500Z", 5.0, "Review branch x in /code/p-x.", ("🔴 a.py:1 breaks",)))
|
||||
self.assertEqual(round_from("/code/p", 5.0, entries).seconds, 1791972000.5)
|
||||
self.assertEqual(round_from("stability-reviewer", "/code/p", 5.0, entries), Round("stability-reviewer", "/code/p", "x", "2026-10-14T10:00:00.500Z", 5.0, "Review branch x in /code/p-x.", ("🔴 a.py:1 breaks",)))
|
||||
self.assertEqual(round_from("stability-reviewer", "/code/p", 5.0, entries).seconds, 1791972000.5)
|
||||
|
||||
def test_reads_a_prompt_given_as_a_string(self):
|
||||
start = {"type": "user", "message": {"content": "Review branch x in /code/p-x."}, "timestamp": "2026-10-14T10:00:00Z", "gitBranch": "x"}
|
||||
self.assertEqual(round_from("/code/p", 5.0, [start, entry("assistant", "🔴 a")]).prompt, "Review branch x in /code/p-x.")
|
||||
self.assertEqual(round_from("stability-reviewer", "/code/p", 5.0, [start, entry("assistant", "🔴 a")]).prompt, "Review branch x in /code/p-x.")
|
||||
|
||||
def test_skips_a_round_with_no_red_or_yellow_finding_or_no_report(self):
|
||||
start = entry("user", "Review.", timestamp="2026-10-14T10:00:00Z", cwd="/code/p", gitBranch="x")
|
||||
self.assertIsNone(round_from("/code/p", 5.0, [start, entry("assistant", "APPROVE\n\n🟢 nit")]))
|
||||
self.assertIsNone(round_from("/code/p", 5.0, [start]))
|
||||
self.assertIsNone(round_from("/code/p", 5.0, []))
|
||||
self.assertIsNone(round_from("/code/p", 5.0, [{**start, "timestamp": "yesterday"}, entry("assistant", "🔴 a")]))
|
||||
self.assertIsNone(round_from("stability-reviewer", "/code/p", 5.0, [start, entry("assistant", "APPROVE\n\n🟢 nit")]))
|
||||
self.assertIsNone(round_from("stability-reviewer", "/code/p", 5.0, [start]))
|
||||
self.assertIsNone(round_from("stability-reviewer", "/code/p", 5.0, []))
|
||||
self.assertIsNone(round_from("stability-reviewer", "/code/p", 5.0, [{**start, "timestamp": "yesterday"}, entry("assistant", "🔴 a")]))
|
||||
|
||||
|
||||
class ReviewedPath(unittest.TestCase):
|
||||
@@ -78,6 +80,13 @@ class ReviewedPath(unittest.TestCase):
|
||||
self.assertIsNone(reviewed_path("Review /code/p-x and /code/p-43.", "/code/p", exists))
|
||||
|
||||
|
||||
class LostInputs(unittest.TestCase):
|
||||
def test_names_each_file_the_prompt_names_in_the_copy_that_it_lacks_other_than_a_round_report(self):
|
||||
prompt = "Read /c/branch.diff and /c/ls-files.txt:3. Earlier: /c/prose-round-1.md. Write /c/principles-goals-round-2-rerun.md; see /elsewhere/x.diff."
|
||||
self.assertEqual(lost_inputs(prompt, "/c", {"ls-files.txt"}.__contains__), ["branch.diff"])
|
||||
self.assertEqual(lost_inputs(prompt, "/c", {"branch.diff", "ls-files.txt"}.__contains__), [])
|
||||
|
||||
|
||||
class AuthoredBy(unittest.TestCase):
|
||||
def test_takes_the_newest_commit_authored_by_then(self):
|
||||
log = [("c3", 30), ("c2", 20), ("c1", 10)]
|
||||
@@ -95,7 +104,7 @@ class Sample(unittest.TestCase):
|
||||
class Report(unittest.TestCase):
|
||||
def test_counts_the_findings_and_names_each_miss_and_the_lowest_rung_that_missed_none(self):
|
||||
rounds = [a_round(1, ("🔴 a\nmore", "🟡 b")), a_round(2)]
|
||||
lines = report("claude-opus-5-5", REFERENCE, rounds, Replay([{0, 1}, set()], [Tried(MIDDLE, []), Tried(CHEAP, [Miss(rounds[0], 0, {1})])], MIDDLE)).splitlines()
|
||||
lines = report("stability", "claude-opus-5-5", REFERENCE, rounds, Replay([{0, 1}, set()], [Tried(MIDDLE, []), Tried(CHEAP, [Miss(rounds[0], 0, {1})])], MIDDLE)).splitlines()
|
||||
self.assertEqual(lines, [
|
||||
"Replayed 2 stability rounds of claude-opus-5-5 projects, holding 3 🔴 and 🟡 findings.",
|
||||
"The reference reviewer, claude-opus-5-5 at medium effort, found 2 of them.",
|
||||
@@ -104,8 +113,8 @@ class Report(unittest.TestCase):
|
||||
" /code/p 2026-10-14T10:00:01Z: 🔴 a",
|
||||
"Lowest rung that finds every finding the reference reviewer finds: claude-sonnet-5-5 at high effort",
|
||||
])
|
||||
self.assertEqual(report("claude-opus-5-5", REFERENCE, rounds, Replay([{0, 1}, {0}], [Tried(MIDDLE, [Miss(rounds[1], 0, set())])], None)).splitlines()[-1], "Lowest rung that finds every finding the reference reviewer finds: none below the project's rung")
|
||||
self.assertEqual(report("claude-opus-5-5", REFERENCE, rounds, Replay([set(), set()], [], None)).splitlines()[-1], "No rung tried: the reference reviewer found no finding to hold one to.")
|
||||
self.assertEqual(report("stability", "claude-opus-5-5", REFERENCE, rounds, Replay([{0, 1}, {0}], [Tried(MIDDLE, [Miss(rounds[1], 0, set())])], None)).splitlines()[-1], "Lowest rung that finds every finding the reference reviewer finds: none below the project's rung")
|
||||
self.assertEqual(report("stability", "claude-opus-5-5", REFERENCE, rounds, Replay([set(), set()], [], None)).splitlines()[-1], "No rung tried: the reference reviewer found no finding to hold one to.")
|
||||
|
||||
|
||||
class Match(unittest.TestCase):
|
||||
@@ -134,15 +143,6 @@ class Match(unittest.TestCase):
|
||||
self.assertIsInstance(self.run_match(json.dumps({"type": "result", "structured_output": output})), Failure)
|
||||
|
||||
|
||||
class Git(unittest.TestCase):
|
||||
def test_says_why_git_cannot_start_in_a_directory_that_is_gone(self):
|
||||
def gone(args, cwd):
|
||||
raise FileNotFoundError(2, "No such file or directory")
|
||||
|
||||
ran = main.git(dataclasses.replace(system_effects(), git=gone), "/code/gone", "log")
|
||||
self.assertEqual(ran, Failure("git log could not start in /code/gone: No such file or directory"))
|
||||
|
||||
|
||||
def unused(*_):
|
||||
raise AssertionError("not called")
|
||||
|
||||
@@ -173,6 +173,7 @@ class Main(unittest.TestCase):
|
||||
for key in ("proj", "other"):
|
||||
self.write_chunk(key, "c1", "2026-10-14T10:00:00Z")
|
||||
self.reviews = []
|
||||
self.agents = set()
|
||||
|
||||
def write_chunk(self, key, chunk, at, began="2026-10-14T09:15:00Z"):
|
||||
"""A chunk that began at began, whose stability round began at at."""
|
||||
@@ -206,6 +207,7 @@ class Main(unittest.TestCase):
|
||||
if "--agent" in args:
|
||||
shown = [subprocess.run(["git", *command], cwd=cwd, capture_output=True, text=True).stdout for command in (["show", "HEAD:a.txt"], ["branch", "--show-current"], ["show", "origin/main:a.txt"])]
|
||||
self.reviews.append((rung, *shown, prompt, cwd))
|
||||
self.agents.add(args[args.index("--agent") + 1])
|
||||
result = review(rung)
|
||||
else:
|
||||
reviewed = Rung(*re.search(r"review on (\S+) (\S+)", prompt).groups())
|
||||
@@ -213,14 +215,14 @@ class Main(unittest.TestCase):
|
||||
result = result if "api_error_status" in result else {"type": "result", "structured_output": {"found": [n + 1 for n in result["found"]]}}
|
||||
return subprocess.CompletedProcess(args, 0, json.dumps(result), "")
|
||||
|
||||
effects = Effects(claude=claude, claude_on_terminal=unused, execv=unused, git=system_effects().git, input=unused, local_time=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused)
|
||||
effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, execv=unused, git=system_effects().git, input=unused, local_time=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused)
|
||||
out, err = io.StringIO(), io.StringIO()
|
||||
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
|
||||
code = main.main(argv, {}, self.home, effects)
|
||||
return code, out.getvalue(), err.getvalue()
|
||||
|
||||
def test_replays_the_models_rounds_on_the_commit_reviewed_from_the_project_rung_down(self):
|
||||
code, out, err = self.run_main(["claude-opus-5-5"], lambda rung: {"found": [0] if rung.model == "claude-haiku-5-5" else [0, 1]})
|
||||
code, out, err = self.run_main(["stability", "claude-opus-5-5"], lambda rung: {"found": [0] if rung.model == "claude-haiku-5-5" else [0, 1]})
|
||||
self.assertEqual(code, 0, err)
|
||||
self.assertEqual([rung for rung, *_ in self.reviews], [REFERENCE, MIDDLE, CHEAP])
|
||||
_, reviewed, branch, base, prompt, cwd = self.reviews[0]
|
||||
@@ -232,15 +234,113 @@ class Main(unittest.TestCase):
|
||||
self.assertIn(f" {self.checkout} 2026-10-14T10:00:00Z: 🟡 slow", out)
|
||||
self.assertTrue(out.endswith("finds: claude-sonnet-5-5 at high effort\n"))
|
||||
|
||||
def test_replays_the_prose_pass_with_the_prose_reviewer(self):
|
||||
code, out, err = self.run_main(["prose", "claude-opus-5-5"], lambda rung: {"found": [0, 1]})
|
||||
self.assertEqual(code, 0, err)
|
||||
self.assertEqual(self.agents, {"prose-reviewer"})
|
||||
self.assertTrue(out.startswith("Replayed 1 prose rounds"), out)
|
||||
|
||||
def test_tries_each_rung_down_to_the_ladders_lowest_below_the_lowest_a_worker_routes_to(self):
|
||||
code, out, err = self.run_main(["prose", "claude-opus-5-5"], lambda rung: {"found": [0, 1]})
|
||||
self.assertEqual(code, 0, err)
|
||||
self.assertEqual([rung for rung, *_ in self.reviews], [REFERENCE, MIDDLE, CHEAP, *(Rung("claude-haiku-5-5", effort) for effort in ("xhigh", "high", "medium", "low"))])
|
||||
self.assertTrue(out.endswith("finds: claude-haiku-5-5 at low effort\n"), out)
|
||||
|
||||
def review_folder_with_round_1(self):
|
||||
"""The chunk's review folder, holding round 1's report from before the replayed round began at 10:00, that round's own and a later pass's reports, written after, and an earlier attempt's report, from before the chunk began at 09:15."""
|
||||
folder = self.home / ".local" / "state" / "larv-review" / "code" / "proj-x"
|
||||
folder.mkdir(parents=True)
|
||||
(folder / "stability-round-1.md").write_text("round 1\n")
|
||||
before = stamp_seconds("2026-10-14T09:50:00Z")
|
||||
os.utime(folder / "stability-round-1.md", (before, before))
|
||||
(folder / "stability-round-2.md").write_text("🔴 a.txt:1 wrong\n")
|
||||
(folder / "prose-round-1.md").write_text("later\n")
|
||||
(folder / "stability-round-3.md").write_text("🔴 a.txt:1 wrong\n")
|
||||
attempt = stamp_seconds("2026-10-14T09:00:00Z")
|
||||
os.utime(folder / "stability-round-3.md", (attempt, attempt))
|
||||
return folder
|
||||
|
||||
def test_points_the_prompts_review_folder_at_a_copy_of_the_reports_from_before_the_round_that_it_removes(self):
|
||||
folder = self.review_folder_with_round_1()
|
||||
self.set_prompt(f"Review branch x in {self.home}/code/proj-x. Write your report to ~/.local/state/larv-review/code/proj-x/stability-round-2.md; the last round's is ~/.local/state/larv-review/code/proj-x/stability-round-1.md.")
|
||||
seen = []
|
||||
|
||||
def review(rung):
|
||||
named = pathlib.Path(re.search(r"report to (\S+)/stability-round-2\.md", self.reviews[-1][4]).group(1))
|
||||
seen.append((named, sorted(path.name for path in named.iterdir()), (named / "stability-round-1.md").read_text()))
|
||||
(named / "stability-round-2.md").write_text("replayed\n")
|
||||
return {"type": "result", "result": f"review on {rung.model} {rung.effort}"}
|
||||
|
||||
code, _, err = self.run_main(["stability", "claude-opus-5-5"], lambda rung: {"found": [0, 1]}, review)
|
||||
self.assertEqual(code, 0, err)
|
||||
named, copied, earlier = seen[0]
|
||||
self.assertEqual(named.parent, folder.parents[1], "the copy sits in the reports folder, where rule-hook lets the reviewer write")
|
||||
self.assertNotEqual(named, folder)
|
||||
self.assertEqual(copied, ["stability-round-1.md"], "the round's own report, later ones and an earlier attempt's would hand the replayed reviewer its findings")
|
||||
self.assertEqual(earlier, "round 1\n")
|
||||
self.assertFalse(named.exists())
|
||||
self.assertEqual(sorted(path.name for path in folder.iterdir()), ["prose-round-1.md", "stability-round-1.md", "stability-round-2.md", "stability-round-3.md"])
|
||||
self.assertEqual((folder / "stability-round-2.md").read_text(), "🔴 a.txt:1 wrong\n")
|
||||
|
||||
def test_points_the_review_folders_absolute_path_at_the_copy(self):
|
||||
folder = self.review_folder_with_round_1()
|
||||
self.set_prompt(f"Review branch x in {self.home}/code/proj-x. Write your report to {folder}/stability-round-2.md.")
|
||||
code, _, err = self.run_main(["stability", "claude-opus-5-5"], lambda rung: {"found": [0, 1]})
|
||||
self.assertEqual(code, 0, err)
|
||||
prompt = self.reviews[0][4]
|
||||
self.assertNotIn(str(folder), prompt)
|
||||
self.assertRegex(prompt, rf"report to {folder.parents[1]}/review-replay-\w+/stability-round-2\.md\.$")
|
||||
|
||||
def test_replays_no_round_whose_prompt_still_names_the_review_folder_after_the_rewrite(self):
|
||||
self.review_folder_with_round_1()
|
||||
self.set_prompt(f"Review branch x in {self.home}/code/proj-x. Write your report to $HOME/.local/state/larv-review/code/proj-x/stability-round-2.md.")
|
||||
code, out, err = self.run_main(["stability", "claude-opus-5-5"], unused)
|
||||
self.assertEqual(code, 0, err)
|
||||
self.assertEqual(self.reviews, [])
|
||||
self.assertIn(f"on {REFERENCE} found nothing: the prompt names the review folder in a spelling the replay does not redirect", err)
|
||||
self.assertTrue(out.endswith("No rung tried: the reference reviewer found no finding to hold one to.\n"))
|
||||
|
||||
def test_replays_a_round_whose_prompt_names_an_input_written_before_it_began_naming_the_copy(self):
|
||||
folder = self.review_folder_with_round_1()
|
||||
(folder / "branch.diff").write_text("the diff\n")
|
||||
before = stamp_seconds("2026-10-14T09:50:00Z")
|
||||
os.utime(folder / "branch.diff", (before, before))
|
||||
self.set_prompt(f"Review branch x in {self.home}/code/proj-x. The diff is ~/.local/state/larv-review/code/proj-x/branch.diff. Write your report to ~/.local/state/larv-review/code/proj-x/stability-round-2.md.")
|
||||
code, _, err = self.run_main(["stability", "claude-opus-5-5"], lambda rung: {"found": [0, 1]})
|
||||
self.assertEqual(code, 0, err)
|
||||
self.assertRegex(self.reviews[0][4], rf"The diff is {folder.parents[1]}/review-replay-\w+/branch\.diff\.")
|
||||
|
||||
def test_replays_no_round_whose_prompt_names_an_input_the_folder_holds_only_as_rewritten_after_the_round_began(self):
|
||||
folder = self.review_folder_with_round_1()
|
||||
(folder / "branch.diff").write_text("a later diff\n")
|
||||
self.set_prompt(f"Review branch x in {self.home}/code/proj-x. The diff is ~/.local/state/larv-review/code/proj-x/branch.diff. Write your report to ~/.local/state/larv-review/code/proj-x/stability-round-2.md.")
|
||||
code, out, err = self.run_main(["stability", "claude-opus-5-5"], unused)
|
||||
self.assertEqual(code, 0, err)
|
||||
self.assertEqual(self.reviews, [])
|
||||
self.assertIn(f"on {REFERENCE} found nothing: the prompt names branch.diff, which the review folder did not hold from the chunk's start until the round's", err)
|
||||
|
||||
def test_finds_nothing_and_leaves_no_folder_behind_when_it_cannot_copy_the_reports(self):
|
||||
folder = self.review_folder_with_round_1()
|
||||
(folder / "stability-round-1.md").chmod(0)
|
||||
self.set_prompt(f"Review branch x in {self.home}/code/proj-x. Write your report to ~/.local/state/larv-review/code/proj-x/stability-round-2.md.")
|
||||
scratch = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory()))
|
||||
self.enterContext(unittest.mock.patch.object(tempfile, "tempdir", str(scratch)))
|
||||
code, _, err = self.run_main(["stability", "claude-opus-5-5"], unused)
|
||||
self.assertEqual(code, 0, err)
|
||||
self.assertEqual(self.reviews, [])
|
||||
self.assertIn(f"on {REFERENCE} found nothing: could not prepare the replay: ", err)
|
||||
self.assertEqual(list(scratch.iterdir()), [], "the clone is removed")
|
||||
self.assertEqual([path.name for path in folder.parent.parent.iterdir()], ["code"], "the copy is removed")
|
||||
|
||||
def test_replays_the_rounds_of_every_chunk(self):
|
||||
self.write_chunk("proj", "c2", "2026-10-14T10:30:00Z")
|
||||
code, out, err = self.run_main(["claude-opus-5-5"], lambda rung: {"found": [0, 1]})
|
||||
code, out, err = self.run_main(["stability", "claude-opus-5-5"], lambda rung: {"found": [0, 1]})
|
||||
self.assertEqual(code, 0, err)
|
||||
self.assertTrue(out.startswith("Replayed 2 stability rounds"), out)
|
||||
|
||||
def test_checks_out_the_commit_detached_when_the_reviewer_started_on_the_default_branch(self):
|
||||
self.set_branch("main")
|
||||
self.assertEqual(self.run_main(["claude-opus-5-5"], lambda rung: {"found": [0]})[0], 0)
|
||||
self.assertEqual(self.run_main(["stability", "claude-opus-5-5"], lambda rung: {"found": [0]})[0], 0)
|
||||
self.assertEqual(self.reviews[0][1:3], ("1\n", ""))
|
||||
|
||||
def test_sets_the_default_branch_to_its_own_line_and_not_to_a_branch_merged_after_the_chunk_began(self):
|
||||
@@ -252,20 +352,20 @@ class Main(unittest.TestCase):
|
||||
run_git(self.checkout, "checkout", "-q", "main")
|
||||
run_git(self.checkout, "merge", "-q", "--no-ff", "-m", "m", "side", at="2026-10-14T09:40:00Z")
|
||||
run_git(self.checkout, "push", "-qf", "origin", "main")
|
||||
self.assertEqual(self.run_main(["claude-opus-5-5"], lambda rung: {"found": [0]})[0], 0)
|
||||
self.assertEqual(self.run_main(["stability", "claude-opus-5-5"], lambda rung: {"found": [0]})[0], 0)
|
||||
self.assertEqual(self.reviews[0][1:4], ("s\n", "x\n", "0\n"))
|
||||
|
||||
def test_finds_nothing_in_a_round_whose_review_has_no_report(self):
|
||||
code, out, err = self.run_main(["claude-opus-5-5"], unused, review=lambda rung: {"type": "result"})
|
||||
code, out, err = self.run_main(["stability", "claude-opus-5-5"], unused, review=lambda rung: {"type": "result"})
|
||||
self.assertEqual(code, 0, err)
|
||||
self.assertEqual([rung for rung, *_ in self.reviews], [REFERENCE] * 3)
|
||||
self.assertIn(f" {self.checkout} 2026-10-14T10:00:00Z on {REFERENCE} found nothing: the reviewer replied with no report", err)
|
||||
self.assertTrue(out.endswith("No rung tried: the reference reviewer found no finding to hold one to.\n"))
|
||||
|
||||
def assert_no_round(self):
|
||||
code, _, err = self.run_main(["claude-opus-5-5"], unused)
|
||||
code, _, err = self.run_main(["stability", "claude-opus-5-5"], unused)
|
||||
self.assertEqual(code, 1)
|
||||
self.assertEqual(err.splitlines(), [f"stability-replay: no archived stability round of projects on claude-opus-5-5 in {self.archive} holds a 🔴 or 🟡 on code it can find"])
|
||||
self.assertEqual(err.splitlines(), [f"review-replay: no archived stability round of projects on claude-opus-5-5 in {self.archive} holds a 🔴 or 🟡 on code it can find"])
|
||||
|
||||
def test_skips_a_chunk_with_no_transcript_copy(self):
|
||||
(self.archive / "proj" / "c1" / "t0.jsonl").unlink()
|
||||
@@ -276,7 +376,7 @@ class Main(unittest.TestCase):
|
||||
self.assert_no_round()
|
||||
|
||||
def assert_left_out(self, reason, root=None):
|
||||
code, _, err = self.run_main(["claude-opus-5-5"], unused)
|
||||
code, _, err = self.run_main(["stability", "claude-opus-5-5"], unused)
|
||||
self.assertEqual(code, 1)
|
||||
self.assertIn(f"{root or self.checkout} 2026-10-14T10:00:00Z is left out: {reason}", err)
|
||||
|
||||
@@ -298,23 +398,25 @@ class Main(unittest.TestCase):
|
||||
self.assert_left_out("no commit was authored by then")
|
||||
|
||||
def test_exits_1_on_a_usage_limit_bad_arguments_or_no_round_to_replay(self):
|
||||
code, _, err = self.run_main(["claude-opus-5-5"], lambda rung: {"type": "result", "api_error_status": 429, "result": "You've hit your limit"})
|
||||
code, _, err = self.run_main(["stability", "claude-opus-5-5"], lambda rung: {"type": "result", "api_error_status": 429, "result": "You've hit your limit"})
|
||||
self.assertEqual(code, 1)
|
||||
self.assertIn("usage limit: You've hit your limit", err)
|
||||
for argv in ([], ["off-ladder"], ["claude-opus-5-5", "x"]):
|
||||
self.assertEqual(self.run_main(argv, unused)[0], 1)
|
||||
code, _, err = self.run_main(["claude-haiku-5-5"], unused)
|
||||
for argv in ([], ["claude-opus-5-5"], ["full scan", "claude-opus-5-5"], ["stability", "off-ladder"], ["stability", "claude-opus-5-5", "x"]):
|
||||
with self.subTest(argv=argv):
|
||||
self.assertEqual(self.run_main(argv, unused)[0], 1)
|
||||
code, _, err = self.run_main(["stability", "claude-haiku-5-5"], unused)
|
||||
self.assertEqual(code, 1)
|
||||
self.assertIn("no archived stability round of projects on claude-haiku-5-5", err)
|
||||
|
||||
def test_prints_the_help(self):
|
||||
code, out, _ = self.run_main(["-h"], unused)
|
||||
self.assertEqual((code, out.splitlines()[2]), (0, "usage: stability-replay <model>"))
|
||||
self.assertEqual((code, out.splitlines()[2]), (0, "usage: review-replay <pass> <model>"))
|
||||
self.assertIn(f"{', '.join(list(REVIEWERS)[:-1])} or {list(REVIEWERS)[-1]}.", " ".join(out.split()))
|
||||
|
||||
def test_the_launcher_prints_the_help(self):
|
||||
ran = subprocess.run([sys.executable, str(TOOL), "--help"], capture_output=True, text=True)
|
||||
self.assertEqual(ran.returncode, 0)
|
||||
self.assertIn("usage: stability-replay <model>", ran.stdout)
|
||||
self.assertIn("usage: review-replay <pass> <model>", ran.stdout)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
+9
-1
@@ -1,8 +1,10 @@
|
||||
"""The titles of larv-review's round commits, `Answer <pass> round <n>: <k> 🔴, <m> 🟡; <summary>`: each pass's round count, and the findings the rounds reported."""
|
||||
import re
|
||||
|
||||
from review_passes import PASSES
|
||||
|
||||
# The most rounds a pass takes before the run asks the human, per `docs/decisions.md` → `review: a pass gets at most three rounds per chunk; …`. rule-hook's `round-cap` refuses a round title past it, and `larv-review round-count` marks a pass at or past it.
|
||||
CAP = 3
|
||||
PASSES = ("architecture", "full scan", "security", "overrides", "stability", "product-owner", "prose")
|
||||
ROUND = re.compile(r"^Answer (.+?) round ([0-9]+):", re.IGNORECASE)
|
||||
# What follows a round title's colon: the round's 🔴 and 🟡 counts, then `;` and its summary, if any.
|
||||
FINDINGS = re.compile(r" ([0-9]+) 🔴, ([0-9]+) 🟡(?:;|$)")
|
||||
@@ -26,6 +28,12 @@ def lacks_counts(title: str) -> bool:
|
||||
return named is not None and not FINDINGS.match(title, named.end())
|
||||
|
||||
|
||||
def past_cap(title: str) -> bool:
|
||||
"""Whether title is a round title numbered past CAP."""
|
||||
named = ROUND.match(title)
|
||||
return named is not None and int(named.group(2)) > CAP
|
||||
|
||||
|
||||
def round_findings(titles: list[str]) -> tuple[int, int] | None:
|
||||
"""The 🔴 and 🟡 counts summed over the round titles among titles; None where a round title lacks them, or no title is a round."""
|
||||
counts = []
|
||||
|
||||
@@ -19,7 +19,7 @@ FIGURES = "routing-figures.md"
|
||||
LOCK = "routing-figures.lock"
|
||||
RAISED = "routing-calls-raised.md"
|
||||
RAISED_HEADING = "# Routing calls raised\n"
|
||||
# Each line is a call and when it was raised, or a reset: `- <UTC time> <call>` or `- <UTC time> Reset`.
|
||||
# Each line is a call and when it was raised, or a reset: `- <UTC time> <call>` or `- <UTC time> Reset`. After a reset the figures count only chunks that finished after it, and a call raised before it may be raised again.
|
||||
RAISED_LINE = re.compile(rf"^- ({STAMPED}) (.+)$", re.MULTILINE)
|
||||
RESET = "Reset"
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Token spend and routing outcomes of the chunks loop-claude finished, and the routing changes they call for: docs/decisions.md → `routing:`."""
|
||||
"""Token spend and routing outcomes of the chunks loop-claude finished, and the routing changes they call for: docs/decisions.md → `routing:`. A chunk that cannot be read is skipped and named in the figures."""
|
||||
import collections
|
||||
import dataclasses
|
||||
import re
|
||||
@@ -125,12 +125,12 @@ def add(tokens: dict[str, collections.Counter[str]], project: str, kind: str, ru
|
||||
tokens["subagent type"][kind] += spent
|
||||
tokens["rung"][rung] += spent
|
||||
# Split whole, the first tools taking the remainder, so the tool table adds up to the others.
|
||||
for place, tool in enumerate(tools):
|
||||
tokens["tool"][tool] += spent // len(tools) + (place < spent % len(tools))
|
||||
for index, tool in enumerate(tools):
|
||||
tokens["tool"][tool] += spent // len(tools) + (index < spent % len(tools))
|
||||
|
||||
|
||||
def rung_at(cycles: list[tuple[str, str]], timestamp: str) -> Rung | str:
|
||||
"""The rung of the cycle running at timestamp: the worker named by the first outcome stamped at or after it, or else by the last outcome. A worker off the ladder is returned as its text."""
|
||||
"""The rung of the cycle running at timestamp: the worker named by the first outcome stamped at or after it, or else by the last outcome. A worker line route_from cannot read is returned as its text, and "unrouted" where no outcome names a worker."""
|
||||
second = timestamp[:19] + "Z"
|
||||
found = next((rung for stamp, rung in cycles if stamp >= second), cycles[-1][1] if cycles else "unrouted")
|
||||
route = route_from(found)
|
||||
|
||||
@@ -15,10 +15,11 @@ from routing_figures.measure import calls, Chunk, ChunkFigures, due, measured, r
|
||||
from failure import Failure
|
||||
from model_routing.ladder import LADDER, Rung
|
||||
from transcript_archive import outcomes, write
|
||||
from model_routing.route import Route
|
||||
|
||||
LOW = Rung("claude-opus-5-5", "medium")
|
||||
HIGH = Rung("claude-opus-5-5", "high")
|
||||
LOW_ROUTE = f"{LOW}, routed by item 7's R + C of 9"
|
||||
LOW_ROUTE = Route(LOW, 7, 3, 4).worker_line()
|
||||
|
||||
|
||||
def message(id_, at, *parts, model="claude-opus-5-5", tokens=(1, 10, 100)):
|
||||
@@ -49,7 +50,7 @@ class Measured(unittest.TestCase):
|
||||
message("m2", "2026-10-14T10:05:00.000Z", {"type": "text", "text": "done"}),
|
||||
message("m3", "2026-10-14T11:00:00.000Z", {"type": "text", "text": "on"}),
|
||||
]
|
||||
kept = stamped("2026-10-14T10:30:00Z", outcomes.unfinished(LOW_ROUTE, "e", "j", "")) + stamped("2026-10-14T10:30:00Z", outcomes.stepped_up(str(HIGH))) + stamped("2026-10-14T12:00:00Z", outcomes.finished(str(HIGH), "merged", "j"))
|
||||
kept = stamped("2026-10-14T10:30:00Z", outcomes.unfinished(LOW_ROUTE, "e", "j", "")) + stamped("2026-10-14T10:30:00Z", outcomes.stepped_up(Route(HIGH).worker_line())) + stamped("2026-10-14T12:00:00Z", outcomes.finished(Route(HIGH).worker_line(), "merged", "j"))
|
||||
found = measured(Chunk("log", [kept], worker, []), "/h")
|
||||
self.assertEqual(found.tokens["project"], {"log": 333})
|
||||
self.assertEqual(found.tokens["subagent type"], {"worker": 333})
|
||||
@@ -84,15 +85,22 @@ class Measured(unittest.TestCase):
|
||||
worker = [commit("m1", "Answer stability round 1: 1 🔴, 0 🟡"), commit("m2", "Answer stability round 2: 0 🔴, 0 🟡"), commit("m3", "Answer stability round 2: 0 🔴, 0 🟡"), commit("m4", "Answer prose round 1: 0 🔴, 1 🟡")]
|
||||
self.assertEqual(measured(Chunk("log", [], worker, []), "/h").rounds_past_first, 1)
|
||||
|
||||
def test_reads_the_route_of_a_line_loop_claude_wrote_before_it_archived_json(self):
|
||||
older = f"{LOW}, routed by item 7's L of 3 and E + I of 4"
|
||||
kept = stamped("2026-10-14T10:00:00Z", outcomes.finished(older, "m", "j"))
|
||||
found = measured(Chunk("log", [kept], [message("m1", "2026-10-14T09:00:00Z")], []), "/h")
|
||||
self.assertEqual(found.start, LOW)
|
||||
self.assertEqual(found.tokens["rung"], {str(LOW): 111})
|
||||
|
||||
def test_starts_no_route_for_a_chunk_no_item_routed(self):
|
||||
kept = stamped("2026-10-14T10:00:00Z", outcomes.finished(str(LOW), "m", "j"))
|
||||
kept = stamped("2026-10-14T10:00:00Z", outcomes.finished(Route(LOW).worker_line(), "m", "j"))
|
||||
found = measured(Chunk("log", [kept], [message("m1", "2026-10-14T09:00:00Z")], []), "/h")
|
||||
self.assertIsNone(found.start)
|
||||
self.assertEqual(found.tokens["rung"], {str(LOW): 111})
|
||||
|
||||
|
||||
def test_puts_a_subagent_on_the_model_it_ran_at_the_effort_of_the_cycle_that_launched_it(self):
|
||||
kept = stamped("2026-10-14T10:00:00Z", outcomes.unfinished(LOW_ROUTE, "e", "j", "")) + stamped("2026-10-14T11:00:00Z", outcomes.finished(str(HIGH), "m", "j"))
|
||||
kept = stamped("2026-10-14T10:00:00Z", outcomes.unfinished(LOW_ROUTE, "e", "j", "")) + stamped("2026-10-14T11:00:00Z", outcomes.finished(Route(HIGH).worker_line(), "m", "j"))
|
||||
worker = [
|
||||
message("m1", "2026-10-14T10:00:00.900Z"),
|
||||
message("m2", "2026-10-14T10:30:00Z", call("Agent", "a1", subagent_type="Explore", model="sonnet")),
|
||||
@@ -184,7 +192,7 @@ class Archive(unittest.TestCase):
|
||||
|
||||
def test_counts_the_verdicts_across_every_projects_chunks(self):
|
||||
self.chunk("home/x", "c1", stamped("2026-10-14T10:00:00Z", outcomes.unfinished("w", "e", "j", "")) + stamped("2026-10-14T10:01:00Z", outcomes.stopped("w", "Ctrl-C")) + stamped("2026-10-14T10:02:00Z", outcomes.finished("w", "e", "j")), [])
|
||||
self.chunk("log", "c2", stamped("2026-10-14T10:00:00Z", outcomes.interrupted("q", "e", "j")), [])
|
||||
self.chunk("log", "c2", stamped("2026-10-14T10:00:00Z", outcomes.interrupted("q", "e", "j", "", "w")), [])
|
||||
self.assertEqual(archive.cycles(self.root), 2)
|
||||
self.assertEqual(archive.cycles(self.root / "missing"), 0)
|
||||
|
||||
@@ -204,7 +212,7 @@ class Archive(unittest.TestCase):
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
self.assertIsNone(write.archive(kept / "log", str(transcript), "t", outcomes.unfinished(LOW_ROUTE, "e", "j", ""), 1790000000))
|
||||
transcript.write_text(json.dumps(first) + "\n" + json.dumps(message("m2", "2099-01-01T00:00:00Z")) + "\n")
|
||||
self.assertIsNone(write.archive(kept / "log", str(transcript), "t", outcomes.finished(str(HIGH), "m", "j"), 4070908800))
|
||||
self.assertIsNone(write.archive(kept / "log", str(transcript), "t", outcomes.finished(Route(HIGH).worker_line(), "m", "j"), 4070908800))
|
||||
(found,) = archive.measure_archive(kept, "/h", "").chunks
|
||||
self.assertEqual((found.start, found.unfinished), (LOW, 1))
|
||||
self.assertEqual(found.tokens["rung"], {str(LOW): 111, str(HIGH): 111})
|
||||
|
||||
@@ -11,6 +11,8 @@ class Call:
|
||||
tool: str
|
||||
given: dict[str, typing.Any]
|
||||
cwd: str
|
||||
# The subagent the call comes from, such as prose-reviewer; empty for the session's own agent.
|
||||
agent: str = ""
|
||||
|
||||
|
||||
def parsed_call(hook_input: object) -> Call | Failure:
|
||||
@@ -19,7 +21,8 @@ def parsed_call(hook_input: object) -> Call | Failure:
|
||||
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)
|
||||
agent = hook_input.get("agent_type")
|
||||
return Call(tool, given, cwd, agent if isinstance(agent, str) else "")
|
||||
|
||||
|
||||
def text(given: dict[str, typing.Any], key: str) -> str:
|
||||
|
||||
+4
-11
@@ -1,20 +1,13 @@
|
||||
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)]
|
||||
import git_repo
|
||||
|
||||
|
||||
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()}")
|
||||
"""What git printed in directory, stripped, run guarded: the hook runs git in a checkout the call has not yet been allowed to touch."""
|
||||
ran = git_repo.git(*args, cwd=directory, guarded=True)
|
||||
return ran if isinstance(ran, Failure) else ran.strip()
|
||||
|
||||
|
||||
def existing(directory: str) -> str:
|
||||
|
||||
+16
-11
@@ -3,7 +3,7 @@
|
||||
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
|
||||
settings.json runs it before each Bash, Edit, MultiEdit, Write and Agent call, in every session and
|
||||
subagent. The rules:
|
||||
|
||||
{rules}
|
||||
@@ -24,7 +24,7 @@ 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
|
||||
Exit 2 with the rule, why it holds and, where the rule takes an override, how to write one, 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.
|
||||
@@ -34,12 +34,15 @@ import os
|
||||
import pathlib
|
||||
import sys
|
||||
import time
|
||||
import typing
|
||||
|
||||
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 rule_hook.rules import Breach, check, Checked, command_breaches, file_breaches, rules_help
|
||||
from git_command import commits
|
||||
from failure import Failure
|
||||
from rule_hook.override_log import Log, log_path, logged, print_overrides, write_override
|
||||
from rule_hook.reviewer_report import report_breaches
|
||||
from rule_hook.reviewer_rung import reviewer_breaches
|
||||
from shell_command import simple_commands
|
||||
from rule_hook.todo_check import todo_breaches
|
||||
|
||||
@@ -60,15 +63,17 @@ def main(argv: list[str], stdin: str) -> int:
|
||||
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("~"))
|
||||
found = breaches_of(call, os.path.expanduser("~"), os.environ)
|
||||
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())
|
||||
return answer(check(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:
|
||||
def breaches_of(call: Call, home: str, environ: typing.Mapping[str, 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 == "Agent":
|
||||
return text(call.given, "prompt"), text(call.given, "subagent_type"), reviewer_breaches(call, environ)
|
||||
if call.tool == "Bash":
|
||||
command = text(call.given, "command")
|
||||
return command, command.split("\n", 1)[0], bash_breaches(command, call.cwd, home)
|
||||
@@ -77,15 +82,15 @@ def breaches_of(call: Call, home: str) -> tuple[str, str, list[Breach]] | None:
|
||||
return None
|
||||
before = read(path)
|
||||
added, after = applied(call, before)
|
||||
return added, path, file_breaches(path, before, added, after)
|
||||
return added, path, report_breaches(call, path, home) + file_breaches(path, before, added, after)
|
||||
|
||||
|
||||
def answer(judged: Outcome, what: str, now: float) -> int:
|
||||
for message in judged.messages:
|
||||
def answer(checked: Checked, what: str, now: float) -> int:
|
||||
for message in checked.messages:
|
||||
print(message, file=sys.stderr)
|
||||
if judged.blocked:
|
||||
if checked.blocked:
|
||||
return 2
|
||||
logs = [(breach, reason, log_path(breach.directory)) for breach, reason in judged.overridden]
|
||||
logs = [(breach, reason, log_path(breach.directory)) for breach, reason in checked.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:
|
||||
|
||||
@@ -34,10 +34,14 @@ def parsed_entry(line: str) -> LogLine | 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."""
|
||||
"""Whether the override is the current branch's: its commit is in the branch's reflog, which holds every commit the branch has had. So:
|
||||
- an override logged at c1 still counts after an amend or a rebase replaced c1 with c2;
|
||||
- one logged under the branch's old name counts after `git branch -m`, which carries the reflog over;
|
||||
- one logged on another branch, at a commit this reflog lacks, doesn't count;
|
||||
- one logged at a default-branch commit, such as the one the branch started from, sits in the reflogs of other branches too, so it counts only under this branch's own name;
|
||||
- one logged before any commit existed, with an empty commit, counts on every branch."""
|
||||
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))
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
"""Refuse a reviewer's file call other than a Write of its report into the reports folder: skills/larv-review/review-findings.md → "Report"."""
|
||||
import os
|
||||
import pathlib
|
||||
|
||||
from rule_hook.rules import Breach
|
||||
from rule_hook.call import Call
|
||||
from review_folder import REPORTS
|
||||
|
||||
# Each agent under agents/, read from the folder, so an agent the routing tables miss is still confined.
|
||||
REVIEWERS = frozenset(path.stem for path in (pathlib.Path(__file__).resolve().parents[2] / "agents").glob("*.md"))
|
||||
|
||||
|
||||
def report_breaches(call: Call, path: str, home: str) -> list[Breach]:
|
||||
"""The breach of a file call from a reviewer that is not a Write under REPORTS in home; none from any other agent."""
|
||||
if call.agent not in REVIEWERS:
|
||||
return []
|
||||
written = os.path.realpath(os.path.join(call.cwd, path))
|
||||
reports = os.path.realpath(os.path.join(home, REPORTS))
|
||||
if call.tool == "Write" and written.startswith(reports + "/"):
|
||||
return []
|
||||
return [Breach("reviewer-report", f"{call.agent} would {call.tool.lower()} {written}; write your report with Write to the path your prompt names, under {reports}/", call.cwd)]
|
||||
@@ -0,0 +1,50 @@
|
||||
"""Refuse an Agent call that launches a review below the rung it needs, worked out from the rungs and the E + I loop-claude hands its worker: docs/decisions.md → `routing:`."""
|
||||
import typing
|
||||
|
||||
from rule_hook.rules import Breach
|
||||
from rule_hook.call import Call, text
|
||||
from model_routing.worker_rungs import handed
|
||||
from model_routing.ladder import position, review_rungs, ReviewKind, Rung
|
||||
from review_passes import REVIEWERS
|
||||
|
||||
# The pass each agent under agents/ reviews.
|
||||
PASS_OF = {agent: kind for kind, agent in REVIEWERS.items()}
|
||||
# The opening of every comprehension seat's prompt: skills/comprehension-panel/seat-prompts.md → "Opening".
|
||||
SEAT = "You are one seat of a comprehension panel."
|
||||
# The opening of the security pass's prompt: skills/larv-review/SKILL.md → "Security".
|
||||
SECURITY_OPENER = "You are the security pass for this chunk."
|
||||
SUBJECTS: dict[ReviewKind, str] = {"seat": "a comprehension seat", "security": "the security pass's subagent"}
|
||||
|
||||
|
||||
def reviewer_breaches(call: Call, environ: typing.Mapping[str, str]) -> list[Breach]:
|
||||
"""The breach of an Agent call that launches a review below its rung; none where loop-claude handed no rungs."""
|
||||
project, worker, escape_and_impact = handed(environ)
|
||||
kind = review_kind(call.given)
|
||||
if kind is None or project is None or worker is None:
|
||||
return []
|
||||
required = review_rungs(project, worker, escape_and_impact)[kind]
|
||||
named = named_rung(call.given, worker)
|
||||
if position(named) >= position(required):
|
||||
return []
|
||||
subject = SUBJECTS.get(kind) or text(call.given, "subagent_type")
|
||||
return [Breach("reviewer-rung", f"{subject} would run on {named}, below {required}: launch it with {required.agent_args()}", call.cwd)]
|
||||
|
||||
|
||||
def review_kind(given: dict[str, typing.Any]) -> ReviewKind | None:
|
||||
"""What a launch reviews, a reviewer's pass, a comprehension seat or the security pass; None for any other subagent."""
|
||||
if pass_reviewed := PASS_OF.get(text(given, "subagent_type")):
|
||||
return pass_reviewed
|
||||
opening = text(given, "prompt").lstrip()
|
||||
if opening.startswith(SEAT):
|
||||
return "seat"
|
||||
if opening.startswith(SECURITY_OPENER):
|
||||
return "security"
|
||||
return None
|
||||
|
||||
|
||||
def named_rung(given: dict[str, typing.Any], worker: Rung) -> Rung:
|
||||
"""The rung an Agent call's model and effort name. A call naming no model runs on the worker's model, at the effort it names or else the worker's; one naming a model but no effort runs on that model's cheapest rung."""
|
||||
model, effort = text(given, "model"), text(given, "effort")
|
||||
if not model:
|
||||
return Rung(worker.model, effort or worker.effort)
|
||||
return Rung.from_agent(model, effort)
|
||||
+36
-9
@@ -3,17 +3,20 @@ import posixpath
|
||||
import re
|
||||
import typing
|
||||
|
||||
from round_titles import CAP, lacks_counts, past_cap
|
||||
from git_command import commits
|
||||
from round_titles import lacks_counts
|
||||
from review_folder import REPORTS
|
||||
from shell_command import Simple
|
||||
|
||||
RuleName = typing.Literal["action-pin", "commit-one-line", "ignorefile-sorted", "image-pin", "no-ai-attribution", "round-title-counts", "todo-rank-check"]
|
||||
RuleName = typing.Literal["action-pin", "commit-one-line", "ignorefile-sorted", "image-pin", "no-ai-attribution", "reviewer-report", "reviewer-rung", "round-cap", "round-title-counts", "todo-rank-check"]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Rule:
|
||||
holds: str
|
||||
checked: str
|
||||
# False where no marker waives the rule: overrides() grants none for it.
|
||||
overridable: bool = True
|
||||
|
||||
|
||||
RULES: dict[RuleName, Rule] = {
|
||||
@@ -37,6 +40,22 @@ RULES: dict[RuleName, 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",
|
||||
),
|
||||
# A reviewer only reports, so no marker waives it.
|
||||
"reviewer-report": Rule(
|
||||
f"a reviewer writes nothing but its report, with Write, into a file under ~/{REPORTS}/",
|
||||
"a Write, Edit or MultiEdit call from inside an agent under agents/",
|
||||
overridable=False,
|
||||
),
|
||||
# A rung is not a judgment call, and the refusal names the arguments to pass, so no marker waives it.
|
||||
"reviewer-rung": Rule(
|
||||
"a reviewer, a comprehension seat or the security pass's subagent runs on the rung loop-claude names for it: for a seat or the security pass the project's rung, and for a reviewer the highest of the project's rung, the worker's and the one the chunk's item's E + I picks, so a worker below the project's rung cannot hand a review to its own cheaper model",
|
||||
"an Agent call, in a claude loop-claude started, whose subagent type is an agent under agents/, or whose prompt opens with seat-prompts.md's opening sentence or the one larv-review's Security section sets",
|
||||
overridable=False,
|
||||
),
|
||||
"round-cap": Rule(
|
||||
f"a larv-review pass takes at most {CAP} rounds per chunk, so a commit titled `Answer <pass> round <n>:` with <n> past {CAP} waits for the human's yes, which the override reason quotes",
|
||||
"a git commit whose message opens `Answer <pass> round <n>:`",
|
||||
),
|
||||
"round-title-counts": Rule(
|
||||
"a larv-review round's commit title gives the counts of 🔴 and 🟡 findings the round reported, such as `Answer stability round 1: 1 🔴, 2 🟡; flag a deleted test`, since score-outcomes counts them",
|
||||
"a git commit whose message opens `Answer <pass> round <n>:`",
|
||||
@@ -46,6 +65,8 @@ RULES: dict[RuleName, Rule] = {
|
||||
"a git commit in a checkout whose todo.md has changes",
|
||||
),
|
||||
}
|
||||
# The lookahead ends each reason at the next marker on its line, or at the line's end. The reason is lazy, so it stops at the next marker instead of running on and swallowing the markers after it.
|
||||
# An HTML marker's closing `-->` stays in its reason; `overrides` strips it.
|
||||
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)
|
||||
@@ -67,7 +88,8 @@ class Breach:
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Outcome:
|
||||
class Checked:
|
||||
"""What rule-hook found in one tool call: the messages to show, whether it blocks the call, and the overrides to log."""
|
||||
messages: list[str]
|
||||
blocked: bool
|
||||
# Each breach an override let through, with its reason; logged only when the call goes through.
|
||||
@@ -75,22 +97,25 @@ class Outcome:
|
||||
|
||||
|
||||
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."""
|
||||
"""The rules the text overrides with their reasons, and the markers that name no rule or give no reason; a marker for a rule that takes no override is neither."""
|
||||
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]
|
||||
granted = {rule: reason for rule, reason in given if rule in RULES and RULES[rule].overridable and reason}
|
||||
return granted, [f"rule-override {rule}: {reason}" for rule, reason in given if rule not in RULES or not reason]
|
||||
|
||||
|
||||
def verdict(breaches: list[Breach], written: str, markdown: bool, bash: bool) -> Outcome:
|
||||
def check(breaches: list[Breach], written: str, markdown: bool, bash: bool) -> Checked:
|
||||
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)
|
||||
if not RULES[rule].overridable:
|
||||
messages.append(f"Blocked by rule {rule}: {details}. The rule: {RULES[rule].holds}.")
|
||||
continue
|
||||
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])
|
||||
return Checked(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]:
|
||||
@@ -104,6 +129,8 @@ def command_breaches(command: str, simples: list[Simple], home: str) -> list[Bre
|
||||
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))
|
||||
if any(past_cap(message) for message in commit.messages):
|
||||
breaches.append(Breach("round-cap", f"the pass has had its {CAP} rounds; ask the human, and quote the yes in the override", commit.directory))
|
||||
if any(lacks_counts(message) for message in commit.messages):
|
||||
breaches.append(Breach("round-title-counts", "open the summary after the round's colon with `<k> 🔴, <m> 🟡;`", commit.directory))
|
||||
return breaches
|
||||
@@ -169,4 +196,4 @@ def blocks(written: str) -> list[list[str]]:
|
||||
|
||||
|
||||
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())
|
||||
return "\n".join(f" {name}\n The rule: {rule.holds}.\n Checked in: {rule.checked}." + ("" if rule.overridable else "\n Takes no override.") for name, rule in RULES.items())
|
||||
|
||||
@@ -5,15 +5,22 @@ import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
import unittest.mock
|
||||
|
||||
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 rule_hook.rules import blocks, Breach, check, command_breaches, file_breaches, overrides
|
||||
from rule_hook.main import breaches_of
|
||||
from rule_hook.call import Call
|
||||
from git_command import Commit, commit_message, commits
|
||||
from test_rank_todo import DECISIONS, README, TODO
|
||||
from test_env import isolated_env
|
||||
from model_routing import ladder
|
||||
from rule_hook.override_log import LogLine, parsed_entry, this_chunks
|
||||
from shell_command import simple_commands
|
||||
from rule_hook.reviewer_rung import reviewer_breaches
|
||||
from rule_hook.git import git as rule_hook_git
|
||||
from model_routing.ladder import Rung
|
||||
from shell_command import segments, simple_commands
|
||||
|
||||
HOOK = pathlib.Path(__file__).resolve().parents[1] / "rule-hook"
|
||||
# Built from parts, so this file carries no attribution of its own.
|
||||
@@ -32,8 +39,8 @@ 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 hook(call: dict, cwd: str, env: dict[str, str] | None = None) -> subprocess.CompletedProcess:
|
||||
return subprocess.run([str(HOOK)], capture_output=True, cwd=cwd, env=isolated_env() | (env or {}), input=json.dumps(call), text=True)
|
||||
|
||||
|
||||
def git(cwd: str, *args: str) -> str:
|
||||
@@ -68,6 +75,20 @@ class Commits(unittest.TestCase):
|
||||
def test_a_line_that_does_not_parse_hides_only_itself(self):
|
||||
self.assertEqual(len(committed("echo 'open\ngit commit -m a")), 1)
|
||||
|
||||
def test_a_redirect_keeps_its_command_s_words_together(self):
|
||||
self.assertEqual(segments("echo hi > f arg"), [["echo", "hi", "arg"]])
|
||||
for redirect in [">", ">>", "<", "<<<", "<>", ">&", "<&", ">|", "&>", "&>>"]:
|
||||
with self.subTest(redirect):
|
||||
self.assertEqual(committed(f"git {redirect} /tmp/x commit -m hi"), [Commit("/r", ["hi"], False)])
|
||||
self.assertEqual(committed("git commit >&2 -m hi 2>&1"), [Commit("/r", ["hi"], False)])
|
||||
self.assertEqual(committed("> out git commit -m hi"), [Commit("/r", ["hi"], False)])
|
||||
|
||||
def test_a_separator_glued_to_a_redirect_still_ends_the_command(self):
|
||||
self.assertEqual(segments("echo a > f; echo b | cat &> g\nls"), [["echo", "a"], ["echo", "b"], ["cat"], ["ls"]])
|
||||
for command in ["echo a &</dev/null git commit -m hi", "echo a;>f git commit -m hi"]:
|
||||
with self.subTest(command):
|
||||
self.assertEqual(committed(command), [Commit("/r", ["hi"], False)])
|
||||
|
||||
|
||||
class CommandBreaches(unittest.TestCase):
|
||||
def test_one_line_passes(self):
|
||||
@@ -84,6 +105,18 @@ class CommandBreaches(unittest.TestCase):
|
||||
self.assertEqual(checked("git commit -m 'Answer stability round 1: 1 🔴, 2 🟡; fix the parser'"), [])
|
||||
self.assertEqual(checked("git commit -m 'Answer the question in the README'"), [])
|
||||
|
||||
def test_a_round_title_past_round_3_breaks_round_cap(self):
|
||||
self.assertEqual(checked("git commit -m 'Answer stability round 4: 0 🔴, 1 🟡; fix the parser'"), ["round-cap"])
|
||||
self.assertEqual(checked("git commit -m 'Answer stability round 3: 0 🔴, 1 🟡; fix the parser'"), [])
|
||||
|
||||
def test_a_round_cap_breach_names_the_commit_s_checkout(self):
|
||||
command = "git -C /x commit -m 'Answer stability round 4: 0 🔴, 1 🟡; fix'"
|
||||
self.assertEqual([(breach.rule, breach.directory) for breach in command_breaches(command, simple_commands(command, "/r", "/h"), "/h")], [("round-cap", "/x")])
|
||||
|
||||
def test_an_override_quoting_the_human_s_yes_lets_a_round_past_the_cap_through(self):
|
||||
command = "git commit -m 'Answer stability round 4: 0 🔴, 1 🟡; fix' # rule-override round-cap: the human answered 'yes, one more'"
|
||||
self.assertFalse(check(command_breaches(command, simple_commands(command, "/r", "/h"), "/h"), command, False, True).blocked)
|
||||
|
||||
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}' ."), [])
|
||||
@@ -127,6 +160,10 @@ 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_a_marker_for_a_rule_that_takes_no_override_is_neither_granted_nor_malformed(self):
|
||||
self.assertEqual(overrides("# rule-override reviewer-rung: trust me"), ({}, []))
|
||||
self.assertEqual(overrides("# rule-override reviewer-rung: trust me\n# rule-override image-pin: a # rule-override nope: b"), ({"image-pin": "a"}, ["rule-override nope: b"]))
|
||||
|
||||
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"])
|
||||
|
||||
@@ -135,13 +172,13 @@ class Overrides(unittest.TestCase):
|
||||
|
||||
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)
|
||||
blocked_call = check(breaches, "# rule-override image-pin: a", False, False)
|
||||
self.assertTrue(blocked_call.blocked)
|
||||
passed = check(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])
|
||||
self.assertIn("`<!-- rule-override no-ai-attribution: <reason> -->`", check([Breach("no-ai-attribution", "x", "/r")], "", True, False).messages[0])
|
||||
|
||||
|
||||
class OverrideLog(unittest.TestCase):
|
||||
@@ -158,6 +195,118 @@ class OverrideLog(unittest.TestCase):
|
||||
self.assertEqual(this_chunks(LogLine("t", branch, commit, "image-pin", "r", "w"), {"base", "c1"}, "chunk", on_default), expected)
|
||||
|
||||
|
||||
class ReviewerRung(unittest.TestCase):
|
||||
# A worker routed to Sonnet 5.5 at high, on a project whose rung is Opus 5.5 at medium, with its reviewers on the project's rung.
|
||||
ENVIRON = {"LOOP_CLAUDE_PROJECT_RUNG": "claude-opus-5-5 at medium effort", "LOOP_CLAUDE_WORKER_RUNG": "claude-sonnet-5-5 at high effort", "LOOP_CLAUDE_ESCAPE_AND_IMPACT": "4"}
|
||||
# The same project, with a worker, and so its reviewers, routed above it to Fable 5.1 at max.
|
||||
ABOVE = {"LOOP_CLAUDE_PROJECT_RUNG": "claude-opus-5-5 at medium effort", "LOOP_CLAUDE_WORKER_RUNG": "claude-fable-5-1 at max effort", "LOOP_CLAUDE_ESCAPE_AND_IMPACT": "4"}
|
||||
|
||||
def refused(self, given: dict, environ: dict[str, str] = ENVIRON) -> list[str]:
|
||||
return rules(reviewer_breaches(Call("Agent", given, "/r"), environ))
|
||||
|
||||
def test_a_reviewer_below_the_project_rung_is_refused_naming_the_arguments_to_pass(self):
|
||||
breaches = reviewer_breaches(Call("Agent", {"subagent_type": "stability-reviewer", "model": "haiku", "effort": "max", "prompt": "Review."}, "/r"), self.ENVIRON)
|
||||
self.assertEqual(rules(breaches), ["reviewer-rung"])
|
||||
self.assertIn("stability-reviewer", breaches[0].detail)
|
||||
self.assertIn("claude-haiku-5-5 at max effort", breaches[0].detail)
|
||||
self.assertIn("model opus, effort medium", breaches[0].detail)
|
||||
|
||||
def test_a_reviewer_on_the_project_rung_or_a_rerun_above_it_passes(self):
|
||||
self.assertEqual(self.refused({"subagent_type": "prose-reviewer", "model": "opus", "effort": "medium"}), [])
|
||||
self.assertEqual(self.refused({"subagent_type": "prose-reviewer", "model": "opus", "effort": "high"}), [])
|
||||
|
||||
def test_an_agent_calls_prompt_is_the_text_scanned_for_a_marker(self):
|
||||
call = Call("Agent", {"subagent_type": "prose-reviewer", "prompt": "Review. # rule-override reviewer-rung: trust me"}, "/r")
|
||||
self.assertEqual(breaches_of(call, "/h", {})[0], "Review. # rule-override reviewer-rung: trust me")
|
||||
|
||||
def test_a_call_naming_no_model_runs_on_the_workers_rung(self):
|
||||
self.assertEqual(self.refused({"subagent_type": "stability-reviewer", "prompt": "Review."}), ["reviewer-rung"])
|
||||
self.assertEqual(self.refused({"subagent_type": "stability-reviewer", "effort": "medium"}), ["reviewer-rung"])
|
||||
|
||||
def test_a_model_named_without_an_effort_runs_on_its_cheapest_rung(self):
|
||||
self.assertEqual(self.refused({"subagent_type": "prose-reviewer", "model": "opus"}), [])
|
||||
self.assertEqual(self.refused({"subagent_type": "prose-reviewer", "model": "sonnet"}), ["reviewer-rung"])
|
||||
|
||||
def test_an_effort_off_the_ladder_for_its_model_is_refused(self):
|
||||
self.assertEqual(self.refused({"subagent_type": "prose-reviewer", "model": "opus", "effort": "low"}), ["reviewer-rung"])
|
||||
|
||||
def test_a_reviewer_is_held_to_the_rung_its_e_plus_i_picks_where_that_is_higher(self):
|
||||
self.assertEqual(self.refused({"subagent_type": "stability-reviewer", "model": "opus", "effort": "medium"}, self.ABOVE), ["reviewer-rung"])
|
||||
self.assertEqual(self.refused({"subagent_type": "stability-reviewer", "model": "fable", "effort": "max"}, self.ABOVE), [])
|
||||
lifted = self.ENVIRON | {"LOOP_CLAUDE_ESCAPE_AND_IMPACT": "5"}
|
||||
self.assertEqual(self.refused({"subagent_type": "stability-reviewer", "model": "opus", "effort": "medium"}, lifted), ["reviewer-rung"])
|
||||
self.assertEqual(self.refused({"prompt": "You are one seat of a comprehension panel.", "model": "opus", "effort": "medium"}, lifted), [])
|
||||
|
||||
def test_holds_a_reviewer_to_the_higher_of_the_workers_and_the_projects_rung_where_loop_claude_handed_no_e_plus_i(self):
|
||||
without = {name: rung for name, rung in self.ABOVE.items() if name != "LOOP_CLAUDE_ESCAPE_AND_IMPACT"}
|
||||
self.assertEqual(self.refused({"subagent_type": "stability-reviewer", "model": "opus", "effort": "medium"}, without), ["reviewer-rung"])
|
||||
below = {name: rung for name, rung in self.ENVIRON.items() if name != "LOOP_CLAUDE_ESCAPE_AND_IMPACT"}
|
||||
self.assertEqual(self.refused({"subagent_type": "stability-reviewer", "model": "sonnet", "effort": "high"}, below), ["reviewer-rung"])
|
||||
self.assertEqual(self.refused({"prompt": "You are one seat of a comprehension panel.", "model": "sonnet", "effort": "high"}, without), ["reviewer-rung"])
|
||||
|
||||
def test_a_replayed_passs_reviewer_is_held_to_its_replays_rung_below_the_workers_unless_the_e_plus_i_steps_reviews_up_or_the_worker_climbed(self):
|
||||
lowered = {"subagent_type": "prose-reviewer", "model": "haiku", "effort": "medium"}
|
||||
with unittest.mock.patch.dict(ladder.REPLAYED, {("prose", "claude-opus-5-5"): Rung("claude-haiku-5-5", "medium")}):
|
||||
self.assertEqual(self.refused(lowered), [])
|
||||
self.assertEqual(self.refused({"subagent_type": "prose-reviewer", "model": "haiku", "effort": "low"}), ["reviewer-rung"])
|
||||
self.assertEqual(self.refused({**lowered, "subagent_type": "stability-reviewer"}), ["reviewer-rung"])
|
||||
self.assertEqual(self.refused(lowered, self.ENVIRON | {"LOOP_CLAUDE_ESCAPE_AND_IMPACT": "5"}), ["reviewer-rung"])
|
||||
self.assertEqual(self.refused(lowered, self.ABOVE), ["reviewer-rung"])
|
||||
|
||||
def test_a_seat_or_a_security_launch_is_held_to_the_project_rung_alone(self):
|
||||
seat = {"prompt": "You are one seat of a comprehension panel. Tools: Read, Grep, Glob.", "model": "opus", "effort": "medium"}
|
||||
self.assertEqual(self.refused(seat, self.ABOVE), [])
|
||||
self.assertEqual(self.refused({"prompt": "You are the security pass for this chunk. Invoke /security-review over the branch diff.", "model": "sonnet", "effort": "high"}), ["reviewer-rung"])
|
||||
self.assertEqual(self.refused({"prompt": "You are the security pass for this chunk. Run /claude-security scan this branch's changes at high.", "model": "opus", "effort": "medium"}), [])
|
||||
|
||||
def test_a_seat_named_below_the_project_rung_is_refused(self):
|
||||
self.assertEqual(self.refused({"prompt": "You are one seat of a comprehension panel.", "model": "sonnet", "effort": "high"}), ["reviewer-rung"])
|
||||
|
||||
def test_any_other_subagent_keeps_its_own_routing(self):
|
||||
self.assertEqual(self.refused({"subagent_type": "Explore", "model": "haiku", "effort": "low", "prompt": "Find the callers of run_worker."}), [])
|
||||
self.assertEqual(self.refused({"prompt": "Note that security-review runs in CI.", "model": "haiku", "effort": "low"}), [])
|
||||
self.assertEqual(self.refused({"prompt": "Find where /security-review is named.", "model": "haiku", "effort": "low"}), [], "a mention without the opening sentence is no launch")
|
||||
self.assertEqual(self.refused({"prompt": "Quote the rule: 'You are the security pass for this chunk.' Then stop.", "model": "haiku", "effort": "low"}), [], "a quote midway is no launch")
|
||||
|
||||
def test_a_claude_loop_claude_did_not_start_is_not_checked(self):
|
||||
self.assertEqual(self.refused({"subagent_type": "stability-reviewer", "model": "haiku", "effort": "low"}, {}), [])
|
||||
|
||||
|
||||
class ReviewerReport(unittest.TestCase):
|
||||
def breached(self, tool: str, path: str, agent: str = "prose-reviewer", cwd: str = "/r") -> list[str]:
|
||||
given = {"file_path": path, "content": "BLOCK\n"} if tool == "Write" else {"file_path": path, "old_string": "a", "new_string": "b"}
|
||||
found = breaches_of(Call(tool, given, cwd, agent), "/h", {})
|
||||
return rules(found[2]) if found else []
|
||||
|
||||
def test_a_reviewer_writes_its_report_into_the_reports_folder(self):
|
||||
self.assertEqual(self.breached("Write", "/h/.local/state/larv-review/.claude-item-73/prose-round-1.md"), [])
|
||||
|
||||
def test_a_relative_path_resolves_against_the_calls_cwd(self):
|
||||
self.assertEqual(self.breached("Write", "prose-round-1.md", cwd="/h/.local/state/larv-review/x"), [])
|
||||
|
||||
def test_a_symlink_in_the_reports_folder_is_followed_to_where_it_points(self):
|
||||
home = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory()))
|
||||
(home / ".local" / "state" / "larv-review").mkdir(parents=True)
|
||||
(home / ".local" / "state" / "larv-review" / "out").symlink_to(home)
|
||||
found = breaches_of(Call("Write", {"file_path": f"{home}/.local/state/larv-review/out/a.md", "content": "x"}, "/r", "prose-reviewer"), str(home), {})
|
||||
self.assertEqual(rules(found[2]), ["reviewer-report"])
|
||||
|
||||
def test_a_reviewer_writing_anywhere_else_is_refused(self):
|
||||
for path in ["/r/README.md", "/h/.local/state/larv-review", "/h/.local/state/larv-review-x/a.md", "/h/.local/state/larv-review/../a.md", "/tmp/larv-review/a.md"]:
|
||||
with self.subTest(path):
|
||||
self.assertEqual(self.breached("Write", path), ["reviewer-report"])
|
||||
|
||||
def test_a_reviewer_edits_no_file_even_in_the_reports_folder(self):
|
||||
self.assertEqual(self.breached("Edit", "/h/.local/state/larv-review/x/prose-round-1.md"), ["reviewer-report"])
|
||||
|
||||
def test_a_reviewers_multiedit_is_refused(self):
|
||||
self.assertEqual(self.breached("MultiEdit", "/r/a.py", "stability-reviewer"), ["reviewer-report"])
|
||||
|
||||
def test_the_worker_and_other_subagents_write_anywhere(self):
|
||||
self.assertEqual(self.breached("Write", "/r/README.md", ""), [])
|
||||
self.assertEqual(self.breached("Write", "/r/README.md", "general-purpose"), [])
|
||||
|
||||
|
||||
class Hook(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.repo = tempfile.mkdtemp()
|
||||
@@ -166,6 +315,10 @@ class Hook(unittest.TestCase):
|
||||
git(self.repo, "commit", "-q", "--allow-empty", "-m", "base")
|
||||
git(self.repo, "checkout", "-q", "-b", "chunk")
|
||||
|
||||
def test_runs_git_guarded(self):
|
||||
git(self.repo, "config", "core.fsmonitor", "/bin/false")
|
||||
self.assertEqual(rule_hook_git(self.repo, "config", "core.fsmonitor"), "false")
|
||||
|
||||
def listed(self) -> str:
|
||||
return subprocess.run([str(HOOK), "overrides"], capture_output=True, check=True, cwd=self.repo, env=isolated_env(), text=True).stdout
|
||||
|
||||
@@ -218,6 +371,28 @@ class Hook(unittest.TestCase):
|
||||
self.assertEqual(hook({"cwd": self.repo, "tool_input": {"command": command}, "tool_name": "Bash"}, self.repo).returncode, 2)
|
||||
self.assertEqual(self.listed(), "")
|
||||
|
||||
def test_an_agent_call_below_its_rung_is_refused_and_offers_no_override(self):
|
||||
call = {"cwd": self.repo, "tool_input": {"subagent_type": "stability-reviewer", "model": "sonnet", "effort": "high", "prompt": "Review. # rule-override reviewer-rung: trust me"}, "tool_name": "Agent"}
|
||||
ran = hook(call, self.repo, ReviewerRung.ENVIRON)
|
||||
self.assertEqual(ran.returncode, 2)
|
||||
self.assertIn("Blocked by rule reviewer-rung", ran.stderr)
|
||||
self.assertIn("stability-reviewer", ran.stderr)
|
||||
self.assertIn("claude-sonnet-5-5 at high effort", ran.stderr)
|
||||
self.assertIn("model opus, effort medium", ran.stderr)
|
||||
self.assertNotIn("rule-override", ran.stderr)
|
||||
|
||||
def test_an_agent_call_at_its_rung_passes(self):
|
||||
call = {"cwd": self.repo, "tool_input": {"subagent_type": "stability-reviewer", "model": "opus", "effort": "medium", "prompt": "Review."}, "tool_name": "Agent"}
|
||||
self.assertEqual(hook(call, self.repo, ReviewerRung.ENVIRON).returncode, 0)
|
||||
|
||||
def test_a_reviewers_write_outside_the_reports_folder_is_refused_and_offers_no_override(self):
|
||||
call = {"agent_type": "prose-reviewer", "cwd": self.repo, "tool_input": {"file_path": f"{self.repo}/a.md", "content": "<!-- rule-override reviewer-report: trust me -->\n"}, "tool_name": "Write"}
|
||||
ran = hook(call, self.repo)
|
||||
self.assertEqual(ran.returncode, 2)
|
||||
self.assertIn("Blocked by rule reviewer-report: prose-reviewer would write ", ran.stderr)
|
||||
self.assertIn("/.local/state/larv-review/", ran.stderr)
|
||||
self.assertNotIn("rule-override", ran.stderr)
|
||||
|
||||
def test_a_commit_override_is_logged_in_the_commit_s_checkout(self):
|
||||
outside = tempfile.mkdtemp()
|
||||
self.addCleanup(subprocess.run, ["rm", "-rf", outside])
|
||||
@@ -281,5 +456,8 @@ class Hook(unittest.TestCase):
|
||||
|
||||
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", "round-title-counts", "todo-rank-check"]:
|
||||
for rule in ["action-pin", "commit-one-line", "ignorefile-sorted", "image-pin", "no-ai-attribution", "reviewer-report", "reviewer-rung", "round-cap", "round-title-counts", "todo-rank-check"]:
|
||||
self.assertIn(f" {rule}\n The rule: ", helped)
|
||||
self.assertIn("reviewer-report\n The rule: a reviewer writes nothing but its report", helped)
|
||||
self.assertRegex(helped, r" reviewer-report\n( .*\n){2} Takes no override\.\n")
|
||||
self.assertRegex(helped, r" image-pin\n( .*\n){2} \S", "a rule a marker waives says nothing of overrides")
|
||||
|
||||
+14
-12
@@ -1,25 +1,27 @@
|
||||
"""What judge-replay's and stability-replay's commands share: the argument, the projects on its model, the candidate rungs and the exits."""
|
||||
"""What judge-replay's and review-replay's commands share: reading the arguments, the projects on a model, the candidate rungs and the exits."""
|
||||
import pathlib
|
||||
import sys
|
||||
import typing
|
||||
|
||||
from failure import Failure
|
||||
from model_routing.ladder import LADDER, picked, position, project_rung, Rung
|
||||
from model_routing.ladder import LADDER, position, Rung
|
||||
from claude_code.reply import Limited
|
||||
from loop_claude.project.model_choice import read_models_file
|
||||
from loop_claude.stop import Stop
|
||||
|
||||
LOWEST_R_PLUS_C = 2
|
||||
# What a tool reads from its arguments, such as the project's rung of the model they name.
|
||||
Parsed = typing.TypeVar("Parsed")
|
||||
|
||||
|
||||
def project_rung_or_exit(tool: str, argv: list[str], help_text: str) -> Rung | int:
|
||||
"""The project's rung of the model argv names, or the exit code: 0 after printing help_text for -h or --help, 1 after saying why argv cannot be read."""
|
||||
def arguments_or_exit(tool: str, argv: list[str], help_text: str, usage: str, read: typing.Callable[[list[str]], Parsed | None]) -> Parsed | int:
|
||||
"""What read makes of argv, or the exit code: 0 after printing help_text for -h or --help, 1 after saying, with usage, that argv cannot be read, where read gives None."""
|
||||
if argv[:1] in (["-h"], ["--help"]):
|
||||
print(help_text.strip())
|
||||
return 0
|
||||
anchor = project_rung(argv[0]) if len(argv) == 1 else None
|
||||
if anchor is None:
|
||||
return failed(tool, f"cannot read the arguments{' ' + ' '.join(argv) if argv else ''}; usage: {tool} <model>, a model on the routing ladder")
|
||||
return anchor
|
||||
arguments = read(argv)
|
||||
if arguments is None:
|
||||
return failed(tool, f"cannot read the arguments{' ' + ' '.join(argv) if argv else ''}; usage: {usage}")
|
||||
return arguments
|
||||
|
||||
|
||||
def projects_on(model: str, home: pathlib.Path) -> list[str] | Failure:
|
||||
@@ -30,9 +32,9 @@ def projects_on(model: str, home: pathlib.Path) -> list[str] | Failure:
|
||||
return sorted(key for key, on in models.items() if on == model)
|
||||
|
||||
|
||||
def down_from(top: Rung) -> list[Rung]:
|
||||
"""top and each rung below it, down to the rung the lowest R + C picks from top, highest first."""
|
||||
return list(LADDER[position(picked(top, LOWEST_R_PLUS_C)):position(top) + 1])[::-1]
|
||||
def down_from(top: Rung, floor: Rung) -> list[Rung]:
|
||||
"""top, the project's rung, and each rung below it, highest first, down to floor."""
|
||||
return list(LADDER[position(floor):position(top) + 1])[::-1]
|
||||
|
||||
|
||||
def limited_exit(tool: str, limited: Limited) -> int:
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""The rung search judge-replay and stability-replay share: replay archived cases on a reference rung, then hold each candidate rung to what the reference reproduced."""
|
||||
"""The rung search judge-replay and review-replay share: replay archived cases on a reference rung, then hold each candidate rung to what the reference reproduced."""
|
||||
import concurrent.futures
|
||||
import dataclasses
|
||||
import sys
|
||||
@@ -13,7 +13,7 @@ from model_routing.ladder import Rung
|
||||
AT_ONCE = 4
|
||||
|
||||
Case = typing.TypeVar("Case")
|
||||
# What of a case's record a reply reproduces, such as a verdict's kind or a finding's index.
|
||||
# What of an archived case a reply reproduces, such as a verdict's kind or a finding's index.
|
||||
Item = typing.TypeVar("Item")
|
||||
Reply = typing.TypeVar("Reply")
|
||||
T = typing.TypeVar("T")
|
||||
|
||||
@@ -63,8 +63,9 @@ class FirstReply(unittest.TestCase):
|
||||
|
||||
|
||||
class DownFrom(unittest.TestCase):
|
||||
def test_runs_from_the_projects_rung_down_to_the_rung_the_lowest_r_plus_c_picks(self):
|
||||
self.assertEqual(down_from(REFERENCE), [REFERENCE, MIDDLE, CHEAP, LOWER])
|
||||
def test_runs_from_the_projects_rung_down_to_the_floor_highest_first(self):
|
||||
self.assertEqual(down_from(REFERENCE, CHEAP), [REFERENCE, MIDDLE, CHEAP])
|
||||
self.assertEqual(down_from(REFERENCE, MIDDLE), [REFERENCE, MIDDLE])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import re
|
||||
|
||||
from todo_table import cells, LEVELS, parse_ids
|
||||
from failure import Failure
|
||||
from score_outcomes.results import render, Result
|
||||
|
||||
ANCHORS_PATH = "docs/score-anchors.md"
|
||||
# A level, such as `L 1`; every scale tops out below 10.
|
||||
LEVEL = re.compile(r"([A-Z]) ([1-9])")
|
||||
# Each level the anchors table names, such as `L 1`, with its items' IDs, in the file's order.
|
||||
Anchors = list[tuple[str, tuple[int, ...]]]
|
||||
|
||||
|
||||
def parse_anchors(text: str) -> Anchors | Failure:
|
||||
found: Anchors = []
|
||||
for row in (line.strip() for line in text.splitlines() if line.strip().startswith("|")):
|
||||
pair = cells(row, 2)
|
||||
if isinstance(pair, Failure):
|
||||
return Failure(f"{ANCHORS_PATH}: {pair.reason}")
|
||||
if pair == ["Level", "Items"] or all(re.fullmatch(r":?-+:?", cell) for cell in pair):
|
||||
continue
|
||||
level, ids = LEVEL.fullmatch(pair[0]), parse_ids(pair[1])
|
||||
if not level or int(level[2]) > LEVELS.get(level[1], 0) or not ids:
|
||||
scales = ", ".join(f"{name} 1 to {top}" for name, top in LEVELS.items())
|
||||
return Failure(f"cannot read the row {row} in {ANCHORS_PATH}; each row names a level, {scales}, and the IDs of shipped items, such as | L 1 | 12, 14 |")
|
||||
if pair[0] in dict(found):
|
||||
return Failure(f"{ANCHORS_PATH} names {pair[0]} twice")
|
||||
found.append((pair[0], ids))
|
||||
return found
|
||||
|
||||
|
||||
def anchor_lines(found: Anchors | Failure, results: list[Result]) -> list[str]:
|
||||
"""Each level, then each of its anchors with what its chunk measured. Where the file cannot be read, one line saying why; where it names no level, one line saying how to choose anchors."""
|
||||
if isinstance(found, Failure):
|
||||
return [f"- None: {found.reason}"]
|
||||
if not found:
|
||||
return [f"- None: the project has no {ANCHORS_PATH}, or it names no level; ~/.claude/rules/todo-items.md says how to choose anchors."]
|
||||
by_id = {result.item.id: result for result in results}
|
||||
lines = []
|
||||
for level, ids in found:
|
||||
lines.append(f"{level}:")
|
||||
lines += [render(by_id[id_]) if id_ in by_id else f"- Item {id_}: no chunk shipped it." for id_ in ids]
|
||||
return lines
|
||||
+134
-49
@@ -1,15 +1,17 @@
|
||||
"""Show what finished chunks measured beside the scores their items were guessed at, to score a new item by.
|
||||
|
||||
usage: score-outcomes [R S C]
|
||||
usage: score-outcomes [L E I S]
|
||||
|
||||
Run it inside a project checkout or one of its worktrees. It fetches origin, when the checkout has
|
||||
that remote, and reads origin's default branch, or else the local main or master; a failed fetch
|
||||
reads origin as last fetched and says so on stderr.
|
||||
|
||||
Git history is the record. A chunk is a merge commit on the default branch's first-parent line
|
||||
whose change removed items from todo.md, and changed more than todo.md and the records below; it
|
||||
shipped those items. Each item's guess is its R, S and C in the todo.md the merge's first parent
|
||||
held; C only where that todo.md scored one. The chunk measures:
|
||||
Git history is the record. The default branch's first-parent line is cut into chunks by one rule: a
|
||||
merge commit is a chunk of its own, and any other commit joins the run of the newer commit above it when
|
||||
both share a commit time, else starts a chunk. A chunk whose change removed items from todo.md, and changed more
|
||||
than todo.md and the records below, shipped those items. Each item's guess is the scores it held in
|
||||
the todo.md the chunk started from: L, E, I, R and S. An item scored before L, E and I replaced C
|
||||
holds R and S, and C too where its table also had A, G and Goals. The chunk measures:
|
||||
|
||||
- lines changed: lines added plus lines deleted against the first parent, leaving out todo.md and
|
||||
the records tools append to, docs/comprehension-history.md and docs/reading-cost.md;
|
||||
@@ -20,35 +22,68 @@ held; C only where that todo.md scored one. The chunk measures:
|
||||
such as `Answer stability round 1: 1 🔴, 2 🟡; flag a deleted test`. Unknown where a round title
|
||||
lacks the counts, or the branch has no round.
|
||||
|
||||
A project that merges without merge commits, by fast-forward or squash, has no chunk to measure.
|
||||
A chunk is marked `by rebase` where a commit in it has a committer time apart from its author time,
|
||||
since a rebase replays a pull request's commits at once, and `never replayed` where none does, since
|
||||
a pushed or fast-forwarded commit may be part of a pull request. A merge's titles are its branch's
|
||||
commits'; any other chunk's are its own. Two pull requests merged in the same second read as one
|
||||
chunk. Rebase drops a round's commit that changed no file, so a rebase or push chunk gives its
|
||||
rounds and findings as lower bounds, `at least`, and the report ends saying all this.
|
||||
|
||||
Given R, S and C, it lists the 5 finished items whose guesses sit closest, closest first: the
|
||||
least mean squared difference over the scores both hold, C only where the item had one, the newest
|
||||
first among equals. Each line gives what the item's chunk measured, which items shipped with it, and its tagline.
|
||||
Given L, E and I, on the levels ~/.claude/rules/todo-items.md defines, and S, it works out R from
|
||||
L, E and I, as rank_todo.py does, and lists the 5 finished items whose guesses sit closest, closest
|
||||
first: the least mean squared difference over the scores both hold, so R and S alone for an item
|
||||
scored before L, E and I, the newest first among equals. Each line gives what the item's chunk
|
||||
measured, which items shipped with it, and its tagline.
|
||||
|
||||
Then, for each score, the median of the outcome it predicts at each value it was guessed at: R
|
||||
against 🔴 findings, S against lines changed, C against review rounds past each pass's first. It counts only chunks that
|
||||
shipped one item, since a chunk measures all its items at once, and reports a score only once 10
|
||||
such chunks hold it and its outcome.
|
||||
Then the project's anchors, the shipped items its docs/score-anchors.md names for each level of L,
|
||||
E and I, read from the checkout's working tree, each line as above, or that no chunk shipped it. A
|
||||
file that cannot be read, a row that does not hold a level on its scale and a list of IDs, or a
|
||||
level named twice leaves the anchors out, saying why.
|
||||
|
||||
Then the median of the outcome R and S each predict at each value they were guessed at: R against 🔴
|
||||
findings, S against lines changed. And how well L, E and I each order chunks by review rounds past
|
||||
each pass's first and by 🔴 findings: Spearman's rank correlation, from -1 to +1, where +1 orders
|
||||
them exactly; none where every chunk held the same level, or the same outcome. It counts only chunks
|
||||
that shipped one item, since a chunk measures all its items at once. It leaves out the chunks never
|
||||
replayed, which may hold only part of a pull request. It reports a score only once 10 of the chunks
|
||||
it counts hold it and its outcomes.
|
||||
|
||||
Exit 1, saying why, on bad arguments, when git cannot start, finds no checkout or reads a shallow
|
||||
clone, or the default branch cannot be read.
|
||||
clone, or the default branch cannot be read; or, after the rest of the report, when the anchors are
|
||||
left out.
|
||||
"""
|
||||
import pathlib
|
||||
import re
|
||||
import sys
|
||||
|
||||
from git_repo import default_branch, file_at, full_history, git
|
||||
from score_outcomes.anchors import anchor_lines, Anchors, ANCHORS_PATH, parse_anchors
|
||||
from score_outcomes.results import Chunk, Landing, nearest, render, report, Result, results_of, shipped
|
||||
from git_repo import default_branch, file_at, full_history, git, top
|
||||
from failure import Failure
|
||||
from score_outcomes.outcomes import nearest, Outcome, outcomes_of, render, report, shipped
|
||||
from todo_table import LEVELS, risk, TOP_SCORE
|
||||
from markdown_text import listed
|
||||
from utc_stamp import utc
|
||||
|
||||
# The scores score-outcomes takes, in order.
|
||||
GIVEN = ("L", "E", "I", "S")
|
||||
# How the report reads the chunks that left no merge commit, which history bounds only by their shared commit time.
|
||||
UNMERGED = [
|
||||
"Chunks that left no merge commit:",
|
||||
"",
|
||||
"- Each is the run of commits on the default branch that share one commit time, since a rebase merge replays a pull request's commits at once. Its guesses come from the todo.md before its first commit.",
|
||||
"- Two pull requests merged in the same second read as one chunk, so a pull request that shipped nothing adds its lines, files and rounds to the chunk it shares a time with.",
|
||||
"- A run whose commits all kept their author time was never replayed: it was pushed or fast-forwarded as committed. It may hold only part of its pull request, so the medians and the rank correlations leave it out.",
|
||||
"- Rebase drops a round's commit that changed no file, so their rounds and findings are at least what history shows, and the medians count the rebased ones as shown.",
|
||||
]
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
if argv[:1] in (["-h"], ["--help"]):
|
||||
print(__doc__.strip())
|
||||
return 0
|
||||
if argv and (len(argv) != 3 or not all(re.fullmatch(r"[1-9]|10", arg) for arg in argv)):
|
||||
print(f"score-outcomes: cannot read the arguments {' '.join(argv)}; usage: score-outcomes [R S C], each a whole number from 1 to 10", file=sys.stderr)
|
||||
if argv and (len(argv) != len(GIVEN) or not all(re.fullmatch(r"[1-9][0-9]?", arg) and int(arg) <= LEVELS.get(name, TOP_SCORE) for name, arg in zip(GIVEN, argv))):
|
||||
scales = listed([f"{name} from 1 to {LEVELS.get(name, TOP_SCORE)}" for name in GIVEN], "and")
|
||||
print(f"score-outcomes: cannot read the arguments {' '.join(argv)}; usage: score-outcomes [L E I S], {scales}", file=sys.stderr)
|
||||
return 1
|
||||
found = default_branch(stale_ok=True)
|
||||
if isinstance(found, Failure):
|
||||
@@ -56,17 +91,26 @@ def main(argv: list[str]) -> int:
|
||||
default, note = found
|
||||
if note:
|
||||
print(f"score-outcomes: {note}", file=sys.stderr)
|
||||
outcomes = read_outcomes(default)
|
||||
if isinstance(outcomes, Failure):
|
||||
return failed(outcomes)
|
||||
if argv:
|
||||
given = dict(zip("RSC", map(int, argv)))
|
||||
print(f"Finished items nearest R {given['R']}, S {given['S']}, C {given['C']}, closest first:\n")
|
||||
print("\n".join(render(outcome) for outcome in nearest(outcomes, given)) or "- None: no merge commit on the default branch shipped an item from todo.md. A project that merges by squash or fast-forward has none.")
|
||||
print()
|
||||
print("Median outcome at each guessed score, among chunks that shipped one item:\n")
|
||||
print("\n".join(report(outcomes)))
|
||||
return 0
|
||||
results = read_results(default)
|
||||
if isinstance(results, Failure):
|
||||
return failed(results)
|
||||
anchored = read_anchors()
|
||||
print(report_text(results, anchored, dict(zip(GIVEN, map(int, argv))) if argv else None))
|
||||
return failed(anchored) if isinstance(anchored, Failure) else 0
|
||||
|
||||
|
||||
def report_text(results: list[Result], anchored: Anchors | Failure, given: dict[str, int] | None) -> str:
|
||||
"""The report: the finished items nearest the given scores, where any are given, then the anchors, then the medians."""
|
||||
sections = []
|
||||
if given is not None:
|
||||
r = risk(given["L"], given["E"], given["I"])
|
||||
near = [render(result) for result in nearest(results, given | {"R": r})] or ["- None: no chunk on the default branch shipped an item from todo.md."]
|
||||
sections.append([f"Finished items nearest L {given['L']}, E {given['E']}, I {given['I']}, so R {r}, and S {given['S']}, closest first:", "", *near])
|
||||
sections.append([f"Anchors in {ANCHORS_PATH}, each level's shipped items:", "", *anchor_lines(anchored, results)])
|
||||
sections.append(["Median outcome at each guessed score, among chunks that shipped one item, never-replayed ones left out:", "", *report(results)])
|
||||
if any(result.landed != "merge" for result in results):
|
||||
sections.append(UNMERGED)
|
||||
return "\n\n".join("\n".join(section) for section in sections)
|
||||
|
||||
|
||||
def failed(failure: Failure) -> int:
|
||||
@@ -74,37 +118,78 @@ def failed(failure: Failure) -> int:
|
||||
return 1
|
||||
|
||||
|
||||
def read_outcomes(default: str) -> list[Outcome] | Failure:
|
||||
def read_anchors() -> Anchors | Failure:
|
||||
"""The checkout's anchors as its working tree holds them, so a branch that edits them shows its edit; none where it has no such file."""
|
||||
root = top()
|
||||
if isinstance(root, Failure):
|
||||
return root
|
||||
try:
|
||||
return parse_anchors((pathlib.Path(root) / ANCHORS_PATH).read_text())
|
||||
except FileNotFoundError:
|
||||
return []
|
||||
except (OSError, UnicodeDecodeError) as failure:
|
||||
return Failure(f"cannot read {ANCHORS_PATH}: {failure}")
|
||||
|
||||
|
||||
def read_results(default: str) -> list[Result] | Failure:
|
||||
"""What each chunk on the default branch's first-parent line measured."""
|
||||
if partial := full_history():
|
||||
return partial
|
||||
merges = git("log", "--first-parent", "--merges", "--format=%H %h %ct", default, "--", "todo.md")
|
||||
if isinstance(merges, Failure):
|
||||
return merges
|
||||
outcomes: list[Outcome] = []
|
||||
for line in merges.splitlines():
|
||||
merge, short, time = line.split()
|
||||
measured = measure(merge, short, utc(int(time)))
|
||||
log = git("log", "--first-parent", "--format=%x1e%h %ct %at %p", "--name-only", default)
|
||||
if isinstance(log, Failure):
|
||||
return log
|
||||
# Each commit's part of the log is its line, then the files it changed against its first parent.
|
||||
commits = [part.splitlines() for part in log.split("\x1e")[1:]]
|
||||
headers = [commit[0] for commit in commits]
|
||||
hashes = [header.split()[0] for header in headers]
|
||||
plan = {short for short, commit in zip(hashes, commits) if "todo.md" in commit}
|
||||
results: list[Result] = []
|
||||
for first, last, committed, landed in chunk_log(headers):
|
||||
# Only a chunk that changed todo.md can ship an item, so the others skip measure's git calls.
|
||||
if not any(short in plan for short in hashes[hashes.index(last):hashes.index(first) + 1]):
|
||||
continue
|
||||
label = first if first == last else f"{first}^..{last}"
|
||||
titled = f"{first}^1..{first}^2" if landed == "merge" else f"{first}^1..{last}"
|
||||
measured = measure(f"{first}^1", last, label, utc(committed), titled, landed)
|
||||
if isinstance(measured, Failure):
|
||||
return measured
|
||||
outcomes += measured
|
||||
return outcomes
|
||||
results += measured
|
||||
return results
|
||||
|
||||
|
||||
def measure(merge: str, short: str, merged: str) -> list[Outcome] | Failure:
|
||||
"""What one merge measured for each item it shipped."""
|
||||
before = file_at(f"{merge}^1", "todo.md")
|
||||
if isinstance(before, Failure):
|
||||
return before
|
||||
after = file_at(merge, "todo.md")
|
||||
def chunk_log(lines: list[str]) -> list[Chunk]:
|
||||
"""The chunks `git log --first-parent --format=%h %ct %at %p` lines cut, newest first: each chunk's first and last commit as short hashes, its commit time, and how it reached the branch. A merge commit is a chunk of its own; any other commit joins the run of the newer commit above it when both share a commit time."""
|
||||
chunks: list[Chunk] = []
|
||||
joinable = False
|
||||
for line in lines:
|
||||
short, committed, authored, *parents = line.split()
|
||||
if len(parents) > 1:
|
||||
chunks.append((short, short, int(committed), "merge"))
|
||||
joinable = False
|
||||
elif joinable and chunks[-1][2] == int(committed):
|
||||
_, newest, time, landed = chunks[-1]
|
||||
chunks[-1] = (short, newest, time, "rebase" if landed == "rebase" or committed != authored else "push")
|
||||
else:
|
||||
chunks.append((short, short, int(committed), "rebase" if committed != authored else "push"))
|
||||
joinable = True
|
||||
return chunks
|
||||
|
||||
|
||||
def measure(before: str, tip: str, label: str, merged: str, titled: str, landed: Landing) -> list[Result] | Failure:
|
||||
"""What one chunk measured for each item it shipped: its change from the commit before it to its tip, and the titles of the commits in the range titled."""
|
||||
planned = file_at(before, "todo.md")
|
||||
if isinstance(planned, Failure):
|
||||
return planned
|
||||
after = file_at(tip, "todo.md")
|
||||
if isinstance(after, Failure):
|
||||
return after
|
||||
items = shipped(before, after)
|
||||
items = shipped(planned, after)
|
||||
if not items:
|
||||
return []
|
||||
numstat = git("diff", "--numstat", f"{merge}^1", merge)
|
||||
numstat = git("diff", "--numstat", before, tip)
|
||||
if isinstance(numstat, Failure):
|
||||
return numstat
|
||||
titles = git("log", "--format=%s", f"{merge}^1..{merge}^2")
|
||||
titles = git("log", "--format=%s", titled)
|
||||
if isinstance(titles, Failure):
|
||||
return titles
|
||||
return outcomes_of(items, short, merged, numstat, titles.splitlines())
|
||||
return results_of(items, label, merged, numstat, titles.splitlines(), landed)
|
||||
|
||||
@@ -1,92 +0,0 @@
|
||||
import dataclasses
|
||||
import statistics
|
||||
import typing
|
||||
|
||||
from comprehension_history import HISTORY
|
||||
from todo_table import Item, items
|
||||
from reading_cost.figures import RECORD
|
||||
from round_titles import round_counts, round_findings
|
||||
|
||||
# Fewest single-item chunks a score needs before its medians print: the 10 figures the reading-cost trend waits for; no published standard sets either.
|
||||
ENOUGH = 10
|
||||
# The plan, and the records tools append to: none of their lines are the chunk's work.
|
||||
NOT_WORK = ("todo.md", HISTORY, RECORD)
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Outcome:
|
||||
"""What the merge that shipped an item measured. findings holds the 🔴 and 🟡 counts, None where a round title lacks them or the branch has no round."""
|
||||
item: Item
|
||||
merge: str
|
||||
merged: str
|
||||
shipped_with: tuple[int, ...]
|
||||
lines: int
|
||||
files: int
|
||||
rounds_past_first: int
|
||||
findings: tuple[int, int] | None
|
||||
|
||||
|
||||
# Each pass takes a first round whatever the change, so only the rounds after it measure how hard the change was to get right.
|
||||
MEASURES: dict[str, tuple[str, typing.Callable[[Outcome], int | None]]] = {
|
||||
"R": ("🔴 findings", lambda outcome: outcome.findings[0] if outcome.findings else None),
|
||||
"S": ("lines changed", lambda outcome: outcome.lines),
|
||||
"C": ("review rounds past each pass's first", lambda outcome: outcome.rounds_past_first),
|
||||
}
|
||||
|
||||
|
||||
def shipped(before: str, after: str) -> list[Item]:
|
||||
"""Each item the todo.md before a change holds and the todo.md after it does not, as scored before; none where either holds no items table it can read."""
|
||||
planned, left = items(before), items(after)
|
||||
if not isinstance(planned, list) or not isinstance(left, list):
|
||||
return []
|
||||
kept = {item.id for item in left}
|
||||
return sorted((item for item in planned if item.id not in kept), key=lambda item: item.id)
|
||||
|
||||
|
||||
def outcomes_of(shipped: list[Item], merge: str, merged: str, numstat: str, titles: list[str]) -> list[Outcome]:
|
||||
"""What one merge measured for each item it shipped, from `git diff --numstat` against its first parent and its branch's commit titles; none where it changed nothing but the plan and the records."""
|
||||
changed = [row.split("\t", 2) for row in numstat.splitlines()]
|
||||
work = [row for row in changed if len(row) == 3 and row[2] not in NOT_WORK]
|
||||
if not work:
|
||||
return []
|
||||
# Git counts a binary file's lines as "-".
|
||||
lines = sum(int(count) for row in work for count in row[:2] if count.isdigit())
|
||||
past_first = sum(max(0, count - 1) for count in round_counts(titles).values())
|
||||
ids = [item.id for item in shipped]
|
||||
return [Outcome(item, merge, merged, tuple(id_ for id_ in ids if id_ != item.id), lines, len(work), past_first, round_findings(titles)) for item in shipped]
|
||||
|
||||
|
||||
def nearest(outcomes: list[Outcome], given: dict[str, int], count: int = 5) -> list[Outcome]:
|
||||
"""The outcomes whose guesses sit closest to the given scores: the least mean squared difference over the scores both hold, the newest first among equals."""
|
||||
def distance(outcome: Outcome) -> float:
|
||||
shared = [name for name in given if name in outcome.item.scores]
|
||||
return sum((given[name] - outcome.item.scores[name]) ** 2 for name in shared) / len(shared)
|
||||
newest_first = sorted(outcomes, key=lambda outcome: outcome.merged, reverse=True)
|
||||
return sorted(newest_first, key=distance)[:count]
|
||||
|
||||
|
||||
def report(outcomes: list[Outcome]) -> list[str]:
|
||||
"""For each score, the median outcome at each value it was guessed at, among chunks that shipped one item: a chunk measures all its items at once."""
|
||||
single = [outcome for outcome in outcomes if not outcome.shipped_with]
|
||||
lines = []
|
||||
for name, (what, measure) in MEASURES.items():
|
||||
held = [(outcome.item.scores[name], value) for outcome in single if name in outcome.item.scores and (value := measure(outcome)) is not None]
|
||||
if len(held) < ENOUGH:
|
||||
chunks = "chunk that shipped one item records" if len(held) == 1 else "chunks that shipped one item record"
|
||||
lines.append(f"- {name}, {what}: {len(held)} {chunks} {name} and its outcome; the report needs {ENOUGH}.")
|
||||
continue
|
||||
medians = [(guess, [value for at, value in held if at == guess]) for guess in sorted({guess for guess, _ in held})]
|
||||
lines.append(f"- {name}, {what}: " + ", ".join(f"{guess} → {statistics.median(found):g} ({plural(len(found), 'chunk')})" for guess, found in medians))
|
||||
return lines
|
||||
|
||||
|
||||
def render(outcome: Outcome) -> str:
|
||||
scores = ", ".join(f"{name} {outcome.item.scores[name]}" for name in MEASURES if name in outcome.item.scores)
|
||||
findings = f"{outcome.findings[0]} 🔴, {outcome.findings[1]} 🟡" if outcome.findings else "findings unknown"
|
||||
others = outcome.shipped_with
|
||||
together = f", with item{'s' if len(others) > 1 else ''} {', '.join(map(str, others))}" if others else ""
|
||||
return f"- Item {outcome.item.id}, {scores}: {plural(outcome.lines, 'line')} in {plural(outcome.files, 'file')}, {plural(outcome.rounds_past_first, 'round')} past each pass's first, {findings}; merged {outcome.merged} in {outcome.merge}{together}. {outcome.item.tagline}"
|
||||
|
||||
|
||||
def plural(count: int, noun: str) -> str:
|
||||
return f"{count} {noun}{'' if count == 1 else 's'}"
|
||||
@@ -0,0 +1,133 @@
|
||||
import dataclasses
|
||||
import statistics
|
||||
import typing
|
||||
|
||||
from comprehension_history import HISTORY
|
||||
from todo_table import Item, items
|
||||
from markdown_text import listed
|
||||
from reading_cost.figures import RECORD
|
||||
from round_titles import round_counts, round_findings
|
||||
|
||||
# Fewest single-item chunks a score needs before its medians print: the 10 figures the reading-cost trend waits for; no published standard sets either.
|
||||
ENOUGH = 10
|
||||
# The plan, and the records tools append to: none of their lines are the chunk's work.
|
||||
NOT_WORK = ("todo.md", HISTORY, RECORD)
|
||||
|
||||
# How a chunk reached the default branch; rebase and push leave no merge commit to bound it.
|
||||
Landing = typing.Literal["merge", "rebase", "push"]
|
||||
# A chunk's first and last commit as short hashes, its commit time, and how it reached the default branch.
|
||||
Chunk = tuple[str, str, int, Landing]
|
||||
|
||||
|
||||
# The tool's name and report call a Result an outcome, a word the code keeps for an entry of a `.outcomes.md` file: docs/decisions.md → `bin/: an outcome is an entry`.
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Result:
|
||||
"""What the chunk that shipped an item measured. findings holds the 🔴 and 🟡 counts, None where a round title lacks them or the branch has no round. landed says how the chunk reached the default branch: by a merge commit, by a rebase that replayed its commits, or by commits never replayed."""
|
||||
item: Item
|
||||
merge: str
|
||||
merged: str
|
||||
shipped_with: tuple[int, ...]
|
||||
lines: int
|
||||
files: int
|
||||
rounds_past_first: int
|
||||
findings: tuple[int, int] | None
|
||||
landed: Landing
|
||||
|
||||
|
||||
# A measure's name and how to read it from a Result, None where the chunk did not record it.
|
||||
Measure = tuple[str, typing.Callable[[Result], int | None]]
|
||||
# The scores whose median result the report gives at each guessed value.
|
||||
MEDIANS: dict[str, Measure] = {"R": ("🔴 findings", lambda result: result.findings[0] if result.findings else None), "S": ("lines changed", lambda result: result.lines)}
|
||||
# The levels R is built from; for each, the report gives how well it orders chunks by review rounds and by 🔴 findings.
|
||||
ORDERED = ("L", "E", "I")
|
||||
# The scores render shows, in this order; C only on an item scored before L, E and I replaced it.
|
||||
SHOWN = ("L", "E", "I", "R", "S", "C")
|
||||
|
||||
|
||||
def shipped(before: str, after: str) -> list[Item]:
|
||||
"""Each item the todo.md before a change holds and the todo.md after it does not, as scored before; none where either holds no items table it can read."""
|
||||
planned, left = items(before), items(after)
|
||||
if not isinstance(planned, list) or not isinstance(left, list):
|
||||
return []
|
||||
kept = {item.id for item in left}
|
||||
return sorted((item for item in planned if item.id not in kept), key=lambda item: item.id)
|
||||
|
||||
|
||||
def results_of(shipped: list[Item], merge: str, merged: str, numstat: str, titles: list[str], landed: Landing) -> list[Result]:
|
||||
"""What one chunk measured for each item it shipped, from `git diff --numstat` against the commit before it and its commit titles; none where it changed nothing but the plan and the records."""
|
||||
changed = [row.split("\t", 2) for row in numstat.splitlines()]
|
||||
work = [row for row in changed if len(row) == 3 and row[2] not in NOT_WORK]
|
||||
if not work:
|
||||
return []
|
||||
# Git counts a binary file's lines as "-".
|
||||
lines = sum(int(count) for row in work for count in row[:2] if count.isdigit())
|
||||
past_first = sum(max(0, count - 1) for count in round_counts(titles).values())
|
||||
ids = [item.id for item in shipped]
|
||||
return [Result(item, merge, merged, tuple(id_ for id_ in ids if id_ != item.id), lines, len(work), past_first, round_findings(titles), landed) for item in shipped]
|
||||
|
||||
|
||||
def nearest(results: list[Result], given: dict[str, int], count: int = 5) -> list[Result]:
|
||||
"""The results whose guesses sit closest to the given scores: the least mean squared difference over the scores both hold, the newest first among equals."""
|
||||
def distance(result: Result) -> float:
|
||||
shared = [name for name in given if name in result.item.scores]
|
||||
return sum((given[name] - result.item.scores[name]) ** 2 for name in shared) / len(shared)
|
||||
newest_first = sorted(results, key=lambda result: result.merged, reverse=True)
|
||||
return sorted(newest_first, key=distance)[:count]
|
||||
|
||||
|
||||
def report(results: list[Result]) -> list[str]:
|
||||
"""Among chunks that shipped one item, since a chunk measures all its items at once, and that were merged or replayed, since a never-replayed one may hold only part of a pull request: for each score in MEDIANS, the median result at each value it was guessed at; for each level in ORDERED, how well it orders chunks by review rounds and by 🔴 findings."""
|
||||
single = [result for result in results if not result.shipped_with and result.landed != "push"]
|
||||
lines = []
|
||||
for name, (what, measure) in MEDIANS.items():
|
||||
held = [(result.item.scores[name], value) for result in single if name in result.item.scores and (value := measure(result)) is not None]
|
||||
if len(held) < ENOUGH:
|
||||
lines.append(f"- {name}, {what}: {too_few(len(held), name, 'its outcome')}")
|
||||
continue
|
||||
medians = [(guess, [value for at, value in held if at == guess]) for guess in sorted({guess for guess, _ in held})]
|
||||
lines.append(f"- {name}, {what}: " + ", ".join(f"{guess} → {statistics.median(found):g} ({plural(len(found), 'chunk')})" for guess, found in medians))
|
||||
for name in ORDERED:
|
||||
# Each pass takes a first round whatever the change, so only the rounds after it measure how hard the change was to get right.
|
||||
rows = [(result.item.scores[name], result.rounds_past_first, result.findings[0]) for result in single if name in result.item.scores and result.findings is not None]
|
||||
opening = f"- {name}, by review rounds past each pass's first and 🔴 findings: "
|
||||
if len(rows) < ENOUGH:
|
||||
lines.append(opening + too_few(len(rows), name, "both outcomes"))
|
||||
continue
|
||||
guesses, rounds, red = ([row[column] for row in rows] for column in range(3))
|
||||
found = [rank_correlation(guesses, rounds), rank_correlation(guesses, red)]
|
||||
undefined = ", since every chunk held one value" if None in found else ""
|
||||
lines.append(opening + f"rank correlation {listed(['none' if value is None else f'{value:+.2f}' for value in found], 'and')}{undefined} ({plural(len(rows), 'chunk')})")
|
||||
return lines
|
||||
|
||||
|
||||
def too_few(held: int, name: str, what: str) -> str:
|
||||
chunks = "such chunk records" if held == 1 else "such chunks record"
|
||||
return f"{held} {chunks} {name} and {what}; the report needs {ENOUGH}."
|
||||
|
||||
|
||||
def rank_correlation(guesses: list[int], results: list[int]) -> float | None:
|
||||
"""Spearman's rank correlation, tied values sharing their mean rank; None where either side holds one value, which no order can rank."""
|
||||
if len(set(guesses)) < 2 or len(set(results)) < 2:
|
||||
return None
|
||||
return statistics.correlation(ranks(guesses), ranks(results))
|
||||
|
||||
|
||||
def ranks(values: list[int]) -> list[float]:
|
||||
"""Each value's rank from 1, tied values sharing their mean rank."""
|
||||
ordered = sorted(values)
|
||||
return [ordered.index(value) + (ordered.count(value) + 1) / 2 for value in values]
|
||||
|
||||
|
||||
def render(result: Result) -> str:
|
||||
scores = ", ".join(f"{name} {result.item.scores[name]}" for name in SHOWN if name in result.item.scores)
|
||||
# Rebase drops a round's commit that changed no file, so history shows such a chunk's rounds and findings short.
|
||||
at_least = "" if result.landed == "merge" else "at least "
|
||||
merged = {"merge": f"merged {result.merged} in {result.merge}", "rebase": f"merged {result.merged} by rebase in {result.merge}", "push": f"committed {result.merged} in {result.merge}, never replayed, so perhaps part of a pull request"}[result.landed]
|
||||
findings = f"{at_least}{result.findings[0]} 🔴, {result.findings[1]} 🟡" if result.findings else "findings unknown"
|
||||
others = result.shipped_with
|
||||
together = f", with item{'s' if len(others) > 1 else ''} {', '.join(map(str, others))}" if others else ""
|
||||
return f"- Item {result.item.id}, {scores}: {plural(result.lines, 'line')} in {plural(result.files, 'file')}, {at_least}{plural(result.rounds_past_first, 'round')} past each pass's first, {findings}; {merged}{together}. {result.item.tagline}"
|
||||
|
||||
|
||||
def plural(count: int, noun: str) -> str:
|
||||
return f"{count} {noun}{'' if count == 1 else 's'}"
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user