Compare commits
672 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| fc5e463594 | |||
| 0447f2e07a | |||
| 155dedcf5c | |||
| 312a8b590d | |||
| e9e130cb77 | |||
| f4a2ea823d | |||
| dd90d109fd | |||
| e68100b35e | |||
| 53459014a4 | |||
| 5ea156a67b | |||
| b1a90abff4 | |||
| e41f4e0979 | |||
| 71e2e0f893 | |||
| 488d9b0eee | |||
| 8602b8a7ee | |||
| 248e46f616 | |||
| d583f8d48c | |||
| f5afc7f6d3 | |||
| 058804bb13 | |||
| 592a6052fe | |||
| 1d2f3d14d2 | |||
| 2d3ec3a636 | |||
| 37df9b7805 | |||
| cde7720750 | |||
| b2aa02eb22 | |||
| 722dd5e451 | |||
| d371869f4a | |||
| 4193165c5d | |||
| 17fb0ac247 | |||
| 6ca9b4a2e7 | |||
| dd4bcbd1c4 | |||
| 084d763412 | |||
| d57727ec39 | |||
| 53e663c8f8 | |||
| d7806d0b16 | |||
| b086e7bf2a | |||
| b6548d32e6 | |||
| 6c059e0545 | |||
| f6f21fc38c | |||
| b7cadb328e | |||
| 14ed4f9cdc | |||
| 7daa3268da | |||
| 83171df2ce | |||
| 9b089d3c30 | |||
| 9d888c9e47 | |||
| 12e3d4ffa6 | |||
| 67e4b36dfd | |||
| c37c80297e | |||
| 69f05a8c3c | |||
| bb3eb4fac6 | |||
| 7c5af45aaf | |||
| 0c1e92943a | |||
| 6917092fd7 | |||
| 499b111071 | |||
| e83ed096c4 | |||
| dac60ccf7b | |||
| d6ff9e26b5 | |||
| 64a7242139 | |||
| 22265be7fd | |||
| 31edfe0c37 | |||
| efa98dae4a | |||
| c31f367771 | |||
| 3af346ef75 | |||
| 9bb27ce493 | |||
| 3833c91bc0 | |||
| d9b4939b99 | |||
| 27e61c4c9d | |||
| ba5fc55539 | |||
| 31e363a469 | |||
| debabc40fd | |||
| 44974bcd02 | |||
| ecff799cb6 | |||
| 15e22a79f3 | |||
| 48f795b1a3 | |||
| 243a9d872d | |||
| 946815a495 | |||
| 51faf71ecc | |||
| c64b3f362d | |||
| 7a7528fba8 | |||
| 8caf92dfbe | |||
| 4bcead0b89 | |||
| 2815b89589 | |||
| f41b549ff7 | |||
| ca6bce76ce | |||
| 0d706c7240 | |||
| 83cf3897a7 | |||
| 9accc68ec3 | |||
| b23bf4f9c3 | |||
| c36d7a2f9c | |||
| b46d5374ff | |||
| 172e72ae07 | |||
| d96e5c35ef | |||
| 34a623e261 | |||
| b569f638ac | |||
| 34c13f97cd | |||
| 2b2e18ec6d | |||
| 9abc5f4781 | |||
| 56b9077e4c | |||
| 78837aabc6 | |||
| 23fbf853d8 | |||
| 14736e8e6e | |||
| f2e239d111 | |||
| aa020f15f7 | |||
| a0458e0a2c | |||
| ea6300a432 | |||
| 5a0c3f47b9 | |||
| d66c0bb317 | |||
| cd76c1f511 | |||
| 4aa8eb9467 | |||
| 3bde9cd6dd | |||
| cf961b55f0 | |||
| 3ac8c79694 | |||
| 3617498f33 | |||
| ed22a48a61 | |||
| 6a2f29635e | |||
| 594b28ff68 | |||
| 055c2d2df0 | |||
| c87e9f19d6 | |||
| e551a2b5a9 | |||
| 487adc2091 | |||
| a12e68fa61 | |||
| 2fa328a406 | |||
| 2eb6fc828f | |||
| 5649331a5e | |||
| 52641079b7 | |||
| 4c1ab3f185 | |||
| eb7b50698c | |||
| 7fb8c61c5e | |||
| f4d25691d6 | |||
| 899e8ed55c | |||
| a622d19280 | |||
| e17ed74fc2 | |||
| e1a67eff2a | |||
| 1ae4018101 | |||
| 951f166c79 | |||
| e2606b8dab | |||
| 196abe18a9 | |||
| 2d219ff6c8 | |||
| 500e2c2947 | |||
| f7ad418b20 | |||
| a292ec4cae | |||
| 7b61fd5b4b | |||
| b6d8fe48af | |||
| fbaa3075c4 | |||
| b6954e5aa7 | |||
| 2135afe8d7 | |||
| 008c187192 | |||
| 4fa114905a | |||
| d1733a2d8d | |||
| 2249655796 | |||
| 686c1dc7a4 | |||
| c70dda6bd9 | |||
| bd00eee3ca | |||
| fc38e80591 | |||
| f94f23a3d7 | |||
| 6ea148bdf4 | |||
| ff3babef74 | |||
| 578de9231f | |||
| 2558a6ad7e | |||
| eb1c302553 | |||
| 1895bbbad5 | |||
| 620590cf24 | |||
| 64d438681e | |||
| 5f54116696 | |||
| 065a0d2d3f | |||
| 83c0f268d4 | |||
| fd60b6da97 | |||
| 91f328e8de | |||
| 5e7e3649c6 | |||
| 2bbfb90936 | |||
| 29715fcd2a | |||
| ff08f496cb | |||
| e05c54aad0 | |||
| 203049f4c3 | |||
| ef392502ba | |||
| 222ee12e09 | |||
| 73b9eec07c | |||
| 9aa174d511 | |||
| 2d2371766d | |||
| 477772d7a5 | |||
| 9d4d6ee401 | |||
| bac9dd54bc | |||
| 13447388a2 | |||
| 779d05886b | |||
| 1e225c4397 | |||
| a68f6a781d | |||
| ef33efd2e4 | |||
| 44305e6f8d | |||
| 1d3b928bdb | |||
| 80cc36e904 | |||
| 4d18b8e125 | |||
| e00eb558c2 | |||
| 4a0ba59210 | |||
| 447668865d | |||
| 27d778ed81 | |||
| 1d00bfd1ef | |||
| 5a56fff040 | |||
| bd64bd59c2 | |||
| dd9dda8f69 | |||
| e3566f694a | |||
| 21d507f0c5 | |||
| 792fa2b8b0 | |||
| dde9caa172 | |||
| c7dbd56f39 | |||
| 504aa31bdb | |||
| 387a5ce506 | |||
| 6725ee4c9d | |||
| 6ff77f7049 | |||
| 66af309e71 | |||
| 8d2a1cf9fd | |||
| 7c05bf414c | |||
| 6c823de29c | |||
| 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 |
@@ -0,0 +1 @@
|
||||
/settings.json filter=settings
|
||||
+16
-3
@@ -4,6 +4,7 @@
|
||||
# un-ignore authored config only.
|
||||
*
|
||||
|
||||
!.gitattributes
|
||||
!.gitignore
|
||||
!AGENTS.md
|
||||
!CHANGELOG.md
|
||||
@@ -18,11 +19,13 @@
|
||||
!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
|
||||
!bin/docker_command.py
|
||||
!bin/failure.py
|
||||
!bin/file_writes.py
|
||||
!bin/git_command.py
|
||||
@@ -37,6 +40,8 @@
|
||||
!bin/loop_claude/
|
||||
!bin/loop_claude/**/
|
||||
!bin/loop_claude/**/*.py
|
||||
!bin/machine_load/
|
||||
!bin/machine_load/*.py
|
||||
!bin/markdown_text.py
|
||||
!bin/metric-bench
|
||||
!bin/metric_bench/
|
||||
@@ -50,6 +55,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,13 +68,16 @@
|
||||
!bin/rule_hook/*.py
|
||||
!bin/rung_replay/
|
||||
!bin/rung_replay/*.py
|
||||
!bin/run-heavy
|
||||
!bin/run_heavy/
|
||||
!bin/run_heavy/*.py
|
||||
!bin/run_heavy/path_entry/
|
||||
!bin/run_heavy/path_entry/docker
|
||||
!bin/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/
|
||||
|
||||
@@ -2,56 +2,65 @@
|
||||
|
||||
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/: the tests rerun themselves on a `uv`-fetched Python at README Install's floor
|
||||
- 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 tools and their tests run on the host's Python, with no container
|
||||
- bin/: the tools support only the latest stable Python, and the tests, written in plain unittest, run on it in four pytest-xdist workers
|
||||
- chunks: a chunk takes every unblocked item of its release that fires the same review passes, whatever its purpose, and an item above R 5 ships alone
|
||||
- comprehension floor: every dimension and the overall at 7.0 or above is the target, and blocks no merge or release
|
||||
- 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, once when an item names the floor and twice on one head when a release's items run out
|
||||
- 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: the principles audit runs on every chunk that changes code, config or tests, and on no other chunk
|
||||
- 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
|
||||
- reading cost: a rise is the last 5 chunks' median above the 5 before them, and files or refreshes one plan item
|
||||
- loop-claude: one session per project, its id derived from the checkout's path relative to `~/code`, or to `/` outside it
|
||||
- loop-claude: the archive keeps the raw transcript, and a failed archive stops the loop
|
||||
- loop-claude: the worker's claude compacts its context before it fills a 200k window, at about 170k tokens, and `CLAUDE.md` → "Compact instructions" says what the summary keeps
|
||||
- machine load: a heavy command waits for one of the machine's heavy slots, one for every 4 CPUs, which every session shares, and loop-claude starts a worker only while at least a quarter of the machine's memory is available
|
||||
- machine load: every container a session starts has a memory limit and a swap limit as large as its work needs; rule-hook's `docker-run-memory` blocks a `docker run` or `docker create` without them outside run-heavy, under which a container that lacks them gets the slot's share of three quarters of the memory; and no daemon-wide cap limits all containers together
|
||||
- principles: about seven things per level, four or five where they act on each other, more where a reader finds them by name; crossing a limit asks for a grouping or a recorded reason
|
||||
- reading cost and `score-outcomes`: each waits for 10 finished chunks before it shows a median
|
||||
- rule-hook: a PreToolUse hook enforces each rule a program can check, a `# rule-override <rule>: <reason>` marker overrides one, and larv-review's overrides pass rules on each override before merge
|
||||
- rules/: `CLAUDE.md` holds the worker's rules that no file path can scope, and each topic's rules for the worker live in a `rules/` file that Claude Code loads by its `paths:` frontmatter
|
||||
- worker: a chunk's worker writes the simplest change that solves its item, test first wherever a test can check the change, and reads a technical principle only where the item, a finding or its own record names it; larv-review's reviewers hold the change to the principles and to the standards in `skills/larv-review/standards/`
|
||||
- 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
|
||||
- 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: a reviewer under `agents/` marks a 🔴 or 🟡 `[misread]` where the implementer misread code that had already shipped, each round title counts the marked findings, and `score-outcomes` lists them per chunk
|
||||
- review: an ask no user answers leaves the PR unmerged
|
||||
- review: each reviewer under `agents/` writes its full report into the chunk's review folder under `~/.local/state/larv-review/` and returns the worker its verdict and one line per finding; rule-hook refuses its Edit and MultiEdit, and any Write outside `~/.local/state/larv-review/`
|
||||
- review: stability and product-owner report only a defect, a broken requirement of the plan or the goals, a breach of a technical principle, or for stability a hard place the change touches; each architect finding names a later change the PR makes harder; prose runs only on a chunk that changes prose
|
||||
- review: the comprehension check records how hard a project is to read and blocks no merge: a paired ruling against the last measured commit where the architecture pass ran, and the four-seat scoring run, once when an item names the floor and twice on one head when a release's items run out
|
||||
- review: the premises chunk's whole review is the human's approval
|
||||
- review: the principles audit runs on every chunk that changes code, config or tests, reads the project whole with one auditor checking the goals and every principles file that applies, and runs on no other chunk
|
||||
- review: the stability pass mutation-tests the lines a chunk changes, in place of measuring test coverage
|
||||
- routing: 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: 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, the seats and the security pass always on the project's
|
||||
- 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
|
||||
- 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: 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, resumes one rung up next cycle, up to two rungs above the rung its item picks
|
||||
- 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: the stability reviewer runs no lower than 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
|
||||
- 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/`
|
||||
- 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 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. 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`.
|
||||
- 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
|
||||
|
||||
|
||||
+56
-2
@@ -2,13 +2,67 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
- rule-hook has a new rule, `repeat-read`, and now runs before each Read call too. It blocks a Read, or a Bash `cat`, `head` or `sed -n '<A>,<B>p'` of one file, when every line it asks for is already in the agent's context, and the block names those lines. The rule takes no override.
|
||||
- A line is in context when an earlier read's result in the agent's own transcript showed it since the last compaction, as the file holds it now. A subagent is judged on its own transcript, not its session's.
|
||||
- A read goes through when it asks for a line no earlier read showed, or one that changed since. A Bash output that Claude Code cut short shows no lines.
|
||||
- A Read also goes through until the agent has read the file with Read or written it with Edit, MultiEdit or Write, and again once the file changed after that. Edit, MultiEdit and Write refuse the file until then, and a Bash read does not count.
|
||||
- Where the context lacks lines the transcript shows, as after Claude Code cleared old tool results, `grep -n '' <file> | sed -n '<A>,<B>p'` reads them.
|
||||
- Install the latest stable Python, today 3.14, as `python3`: the tools and their tests no longer support 3.11 to 3.13. A full test run now takes about 29 s, where it took about 3.3 minutes. It runs once, on that Python, in four pytest-xdist workers, where it used to rerun the whole suite on 3.11.
|
||||
- `routing-figures.md` now reports dollars by project, subagent type, rung and tool, in place of tokens. Cache reads are included; the tokens left them out, though they were about a quarter of the cost. The dollars are what each worker transcript's last `cost-state` entry records for each model, split across the messages of the worker and its subagents in proportion to their cost at list prices. The judge's runs are not counted, since the archive doesn't hold them.
|
||||
- larv-review's principles pass now launches one auditor per round, which checks the README's goals, code health and every principles file that applies, so it reads the project once per round. It used to launch one auditor for the goals with code health and one for each principles file, each reading the whole project. Its report is `principles-round-<n>.md`, like every other pass's.
|
||||
- A session running larv-review now enters the chunk's worktree with `EnterWorktree` before the first review pass, so `/security-review` and the full scan read the branch's diff. Run from the checkout root, they used to find it empty.
|
||||
- `loop-claude` now stops with exit 2 when the judge rules one chunk unfinished 6 cycles running, so a worker and a judge that disagree can no longer cycle unattended without end. Rerunning resumes the chunk and gives it 6 more cycles.
|
||||
- larv-review now launches a round's reviewers in up to three waves, each wave's reviewers in one message, in place of one reviewer at a time: first the architect, then the principles auditor with the security and overrides passes, then the stability, product-owner and prose passes. Each wave now lasts as long as its slowest reviewer, where a round used to last as long as all its reviewers one after another.
|
||||
- loop-claude's worker, and every subagent it launches, now run with a 200k auto-compact window, handed as `CLAUDE_CODE_AUTO_COMPACT_WINDOW`: Claude Code compacts their context at about 170k tokens, where it used to let it grow to about 967k. loop-claude's judge no longer reads a compaction summary as words you typed. `CLAUDE.md` has a new section, "Compact instructions", saying what a summary keeps.
|
||||
- On Linux, `run-heavy` now caps the memory of a container its command makes with `docker run` or `docker create`. A container that sets no limit gets a memory limit and a swap limit, both the slot's share: three quarters of the machine's memory, split across the heavy slots. A container that sets one of the two limits keeps it, and gets the other as large. This covers containers a project's own scripts start, which rule-hook can't see. A `docker compose` service, and a docker named by its full path, get no cap. rule-hook's `docker-run-memory` now lets a `docker run` under run-heavy pass.
|
||||
- rule-hook has a new rule, `docker-run-memory`. It blocks a `docker run` or `docker create` that lacks a memory limit or a swap limit, such as `--memory 4g --memory-swap 4g`, sized to what the work needs. `--memory-swap -1`, unlimited swap, counts as none. `CLAUDE.md` asks for the same limits on a container a script or a compose file starts, which rule-hook can't see. rule-hook's `run-heavy` rule also now reads docker's `--tlscacert`, `--tlscert`, `--tlskey` and buildx's `--builder` as options that take a value, and reads `docker container run` as a run: `docker --tlscacert ca.pem build .` was not blocked outside run-heavy before.
|
||||
- Reviewers now mark a 🔴 or 🟡 `[misread]` where it arose because the implementer misread code that had already shipped. A round's commit title now counts the marked findings, as in `Answer stability round 1: 1 🔴, 2 🟡 (1 misread); …`, and rule-hook's `round-title-counts` blocks a round title without that count. `score-outcomes` shows the count on each finished item, and lists it after the medians for each chunk whose round titles carry it, newest first. A chunk whose round titles predate this change reads as unknown.
|
||||
- Sessions running at once no longer starve the machine. A new tool, `run-heavy <command>`, runs a heavy command, such as a full gate, mutation tests, an e2e run or a `docker build`, once it holds one of the machine's heavy slots: one per 4 CPUs, shared by every session. `CLAUDE.md` has every session run its heavy commands under it, and rule-hook blocks a `docker build` or a mutation run outside it. loop-claude now waits to start a worker while less than a quarter of the machine's memory is available.
|
||||
- larv-review's skill now says a commit answering the external auto-reviewer takes no `Answer <pass> round` title, and that `larv-review round-count` doesn't list the auto-reviewer. A worker who followed the skill used to get a "not a pass" warning.
|
||||
- rule-hook now blocks a larv-review round commit titled past round 3, such as `Answer stability round 4: …`, unless a `round-cap` override quotes the human's yes.
|
||||
- loop-claude's first prompt for a chunk that no plan item routed now also names the rung on which the worker launches its reviews for an item it takes in, as the prompt after a step-up or an unfinished verdict already did.
|
||||
- `loop-claude --help` now describes routing in two short paragraphs for the person running the loop. The rules it used to repeat are now stated once, in the code that enforces them.
|
||||
- loop-claude now archives the route on each `Worker:` line as a JSON record, such as `{"model": "claude-opus-5-5", "effort": "high", "item": 3, "likelihood": 4, "escape_and_impact": 5, "escalated_at": 12}`, and reads it back field by field. The line used to be a sentence, such as `claude-opus-5-5 at high effort, routed by item 3's L of 4 and E + I of 5`, which loop-claude parsed back word for word: rewording the sentence in the code would have made every archived line unreadable, and a rerun would have routed the open chunk afresh. A rerun and the routing figures still read the sentences archived since loop-claude routed on L. A rerun that finds a `Worker:` line it can't read now says so on stderr. The judge's reply now names the levels the worker took in `highest_likelihood_taken_in` and `highest_escape_and_impact_taken_in`, in place of `bundled` and `bundled_escape_and_impact`.
|
||||
- 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:**`, 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 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.
|
||||
- `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 `loop-claude` hands the worker in `LOOP_CLAUDE_REVIEWER_RUNG`. 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.
|
||||
- `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.
|
||||
|
||||
@@ -4,14 +4,14 @@
|
||||
|
||||
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.** 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 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`.
|
||||
- **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. 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.
|
||||
@@ -20,6 +20,17 @@ How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The
|
||||
- **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,6 +65,8 @@ 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.
|
||||
- Give every container you start a memory limit and a swap limit, as large as its work needs: `--memory 4g --memory-swap 4g` on `docker run`, or `mem_limit` and `memswap_limit` in a compose file, scripts included. rule-hook checks only the `docker run` and `docker create` in your Bash commands.
|
||||
- A heavy command loads the machine for minutes: a full gate, mutation tests, an e2e run, a `docker build`. Run each one under `~/.claude/bin/run-heavy`, as in `~/.claude/bin/run-heavy ./ci.sh`. run-heavy waits for one of the heavy slots that every session on the machine shares. It also caps each container the command makes at the slot's share of memory, where the container sets no limits; give a container that needs more its own. Run it in the background, since the wait can outlast the Bash tool's timeout.
|
||||
- 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.
|
||||
@@ -64,7 +79,7 @@ The rules only reviewers apply, for quality, comments, READMEs and prose, live i
|
||||
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.
|
||||
|
||||
@@ -89,20 +104,38 @@ The rules only reviewers apply, for quality, comments, READMEs and prose, live i
|
||||
- **A list or threshold a consumer relies on is sourced.** Deny-lists, defaults, limits: follow a published standard or a widely deployed tool, and cite it in the decision recording the choice; where none exists, ask. Never assemble one from names that seem plausible.
|
||||
- When a page renders client-side and comes back empty/blocked, use the Playwright renderer at `~/code/playwright-for-agents/` — `./pw <url> [options]` (see its README). Don't use claude-in-chrome for this.
|
||||
|
||||
## Compact instructions
|
||||
|
||||
Claude Code reads this section by its heading when it compacts a conversation. Keep in the summary:
|
||||
|
||||
- what remains before the chunk is finished;
|
||||
- the task loop-claude gave, and each `todo.md` item the chunk takes with its L and E + I;
|
||||
- the worktree, branch and PR;
|
||||
- the rung loop-claude named for each review launch, rerun and escalated subagent;
|
||||
- each review pass's rounds so far, each open 🔴 and 🟡, and how the answered ones were answered;
|
||||
- every question the human answered, with the answer;
|
||||
- each escalation trigger that fired;
|
||||
- for a reviewer or comprehension seat, every finding and place it has drafted.
|
||||
|
||||
## Vocabulary
|
||||
|
||||
- **chunk** — the unit of work, shipped as one PR; "Working loop" says what it holds.
|
||||
- **cycle** — in `loop-claude`, worker runs and the judge's verdict on each, until the chunk closes or is left for the next cycle. In between, the human answers any interrupt, or the worker resumes with an answer the judge quoted from `README.md`, `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,9 +45,9 @@ 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:
|
||||
Have the latest stable Python, today 3.14, as `python3` on `PATH`, and for Rust projects `rust-analyzer` on `PATH`, which the `rust-analyzer-lsp` plugin needs. Install every plugin `settings.json` enables:
|
||||
|
||||
```sh
|
||||
claude plugin marketplace add anthropics/claude-plugins-official
|
||||
@@ -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
|
||||
|
||||
@@ -84,33 +97,35 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a
|
||||
|
||||
- `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, and its count of how often seats agree; `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, 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.
|
||||
- `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 Agent, Bash, Edit, MultiEdit, Read and Write call, and `rule-hook --help` states the rules and the override.
|
||||
- `run-heavy <command>` runs a heavy command once it holds one of the machine's heavy slots, one per 4 CPUs, which every session shares; `run-heavy --help` states the slots, and the memory cap it gives a container that sets no limit.
|
||||
- `score-outcomes [L E I S]` lists the finished items whose guessed scores sit nearest the given ones, and the shipped items the project's `docs/score-anchors.md` names for each level of L, E and I, each with what its chunk measured; then the median outcome at each guessed R and S, and how well L, E and I each order the chunks by review rounds and 🔴 findings; then each chunk's 🔴 and 🟡 findings with how many a reviewer marked `[misread]`, code health's counter-signal; `score-outcomes --help` states the measures.
|
||||
- `settings_filter.py` is git's clean filter for `settings.json`: it drops `"model"` and sorts the keys. `.gitattributes` sets the filter `settings` on `settings.json`, and Install's `git config` line makes this script that filter.
|
||||
- `statusline.py` renders Claude Code's status line; `settings.json` → `statusLine` runs it.
|
||||
- `subagent-rung [--plan] <model> <L>` prints the Agent tool's model and effort for a subagent's task, picked by its L from the project's model, and with `--plan` never below the project's rung; `subagent-rung --help` states the rule.
|
||||
|
||||
Test on the host, with `uv` on `PATH` to fetch mypy and the Python version Install names (`docs/decisions.md` → `bin/`): `python3 -m unittest discover -s bin -p 'test_*.py'`. Test the bench's git wrapper with `python3 -m unittest discover -s workflow-bench -p 'test_*.py'`.
|
||||
Test on the host with `uvx --python "$(command -v python3)" --with pytest-xdist==3.8.0 pytest==9.2.0 -n 4 bin`. It needs `uv` on `PATH`, which fetches pytest, pytest-xdist and mypy. pytest-xdist runs the tests in four workers, one heavy slot's CPUs (`docs/decisions.md` → `bin/: the tools support only the latest stable Python, …`). `python3 -m unittest discover -s bin -p 'test_*.py'` runs the same tests one at a time. Test the bench's git wrapper with `python3 -m unittest discover -s workflow-bench -p 'test_*.py'`.
|
||||
|
||||
To mutation-test a changed module, copy `bin/` to a scratch directory (`cp -r bin "$scratch"`): mutmut writes files beside its config. In the copy, name the module and its tests in a `setup.cfg`, as below for `score_outcomes/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
|
||||
not ScoreOutcomesTool
|
||||
```
|
||||
|
||||
Then, in the copy: `uvx --with pytest 'mutmut>=3,<4' run && uvx --with pytest 'mutmut>=3,<4' results`, and `uvx --with pytest 'mutmut>=3,<4' show <mutant>` to see a mutant's change. The config keys are mutmut 3's.
|
||||
Then, in the copy: `uvx --with pytest==9.2.0 'mutmut>=3,<4' run && uvx --with pytest==9.2.0 'mutmut>=3,<4' results`, and `uvx --with pytest==9.2.0 'mutmut>=3,<4' show <mutant>` to see a mutant's change. The config keys are mutmut 3's.
|
||||
|
||||
`bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests; `rank_todo.py` 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, and `loop_claude` runs `chunk-preflight` as a process of its own. `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. `machine_load/` takes the machine's heavy slots, its shared lock files, for `run_heavy`, and reads the memory share that loop-claude waits for. `test_env.py` serves the tests, and `repo_checks/` tests the repo itself.
|
||||
|
||||
## 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,13 +1,14 @@
|
||||
---
|
||||
name: principles-auditor
|
||||
description: "Use this agent for larv-review's principles pass: one yardstick checked against the whole project."
|
||||
tools: Read, Grep, Glob
|
||||
description: "Use this agent for larv-review's principles pass: the project's goals and every principles file handed to it, checked against the whole project."
|
||||
tools: Read, Grep, Glob, Write
|
||||
---
|
||||
|
||||
You check one yardstick against the whole project: every principle in the file you are handed, or every goal under the project's `README.md` → `## Goals`.
|
||||
You check every yardstick you are handed against the whole project, which you read once for all of them. A yardstick is either the project's goals, every goal under its `README.md` → `## Goals` with code health (`~/.claude/CLAUDE.md` → "Shared goal") unless the README voids it, or one principles file, every principle in it.
|
||||
|
||||
Verdict, severities and rounds: ~/.claude/skills/larv-review/review-findings.md. Read the yardstick, `README.md`, `docs/decisions.md` and `todo.md` first, then all of the project's code, config, tests and CI.
|
||||
Verdict, severities and rounds: ~/.claude/skills/larv-review/review-findings.md. Read the yardsticks, `README.md`, `docs/decisions.md` and `todo.md` first, then all of the project's code, config, tests and CI.
|
||||
|
||||
- Per principle or goal: every place the project departs from it, with file:line, the defect in one sentence and its concrete consequence. Then one line: followed, mostly, not followed, or does not apply and why.
|
||||
- A departure a `todo.md` item plans away is named with that item, not raised.
|
||||
- A decision in `docs/decisions.md` working against a goal or a technical principle is a 🔴 on the decision, unless it names the `todo.md` item that ends it. Weigh it hard: that it was decided is no reason.
|
||||
- Report under one heading per yardstick.
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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,8 +12,8 @@ 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.
|
||||
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.
|
||||
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. Run the full suite under `~/.claude/bin/run-heavy`. Run it in the background or with the Bash tool's longest timeout: that timeout includes the wait for a slot. 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 and run-heavy, as in step 4, on a scratch copy: the tools write files. Under run-heavy, a container that sets neither memory limit gets the slot's share, in MiB in `RUN_HEAVY_MEMORY`. Set the tool's concurrency so that its parallel test runs together fit in that share. 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.
|
||||
- *Depth:* trace the riskiest data paths end-to-end (input → logic → persistence/response), the interactions between changed pieces, and between the change and config (timeout hierarchies, retries × idempotency, queue worker counts, env parity).
|
||||
@@ -129,7 +129,7 @@ Every PR gets at least this sweep.
|
||||
|
||||
## 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.
|
||||
|
||||
@@ -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]
|
||||
@@ -1,7 +1,9 @@
|
||||
"""The lines the preflight prints, stated from what it gathered."""
|
||||
from todo_table import bundle_candidates, Item, LastCut, unreleased_entries
|
||||
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, PULLS_LIST, Ran, version
|
||||
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
|
||||
|
||||
|
||||
@@ -64,6 +66,8 @@ def open_pulls(stdout: str, forge: Forge, branch: str) -> list[str]:
|
||||
|
||||
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]
|
||||
|
||||
@@ -1,16 +1,14 @@
|
||||
"""What the preflight gathers, and the pure choices its steps act on; facts.render states it."""
|
||||
"""What the preflight gathers, which facts.render states."""
|
||||
import dataclasses
|
||||
import pathlib
|
||||
import re
|
||||
import typing
|
||||
|
||||
from todo_table import chunk_item, Item, item_details, items, LastCut
|
||||
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"]
|
||||
# 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")}
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -79,72 +77,3 @@ class Gathered:
|
||||
cut: LastCut
|
||||
# What was found or made for the plan's first item; else why the plan names none.
|
||||
item: ItemFacts | NoItem
|
||||
|
||||
|
||||
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, todo_table.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, Failure):
|
||||
return NoItem(f"{where} cannot be read: {found.reason}.")
|
||||
if found is None:
|
||||
return NoItem(f"{where} holds no items table.")
|
||||
earliest = min((item.release for item in found), default=None)
|
||||
stands, first = chunk_item(found, cut)
|
||||
if earliest is not None and stands == "cut":
|
||||
return NoItem(f"{where} files items under release {version(earliest)}, which is not after the last cut, {cut.tag}; ask the human which release they belong to.")
|
||||
gap = f"{where} holds no item for the next release after the last cut, {cut.tag}, and"
|
||||
if stands == "finished":
|
||||
return NoItem(f"{gap} work has landed since, so that release is finished and ready to cut, and the working loop stops here.")
|
||||
if stands == "unplanned":
|
||||
return NoItem(f"{gap} no work has landed since, so that release is to be planned first.")
|
||||
if stands == "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 work landed since then, cannot be read. Find the next release yourself.")
|
||||
if first is None:
|
||||
return NoItem(f"every item of release {version(earliest)} in {where} waits." if earliest 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 version(release: tuple[int, int, int]) -> str:
|
||||
return ".".join(map(str, release))
|
||||
|
||||
|
||||
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]
|
||||
|
||||
@@ -13,9 +13,11 @@ holds it, the plan loop-claude routes on. It prints:
|
||||
- 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; otherwise it is todo.md's earliest release.
|
||||
Where the next release holds no item, it says so: finished and ready to cut where work landed
|
||||
since the tag (the ## Unreleased entries, or else the commits), and else to be planned first.
|
||||
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
|
||||
@@ -24,7 +26,8 @@ holds it, the plan loop-claude routes on. It prints:
|
||||
- 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 and that no item outside the chunk blocks;
|
||||
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
|
||||
@@ -45,9 +48,11 @@ import subprocess
|
||||
import sys
|
||||
import typing
|
||||
|
||||
from git_repo import commit_exists, default_branch, default_plan, file_at, git, top
|
||||
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, forge_of, Gathered, ItemFacts, named_paths, NamedPath, NoItem, Plan, planned, pulls_command, Ran, Worktree, worktree_add, worktree_on
|
||||
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]
|
||||
|
||||
@@ -9,14 +9,15 @@ import unittest
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from failure import Failure
|
||||
from chunk_preflight.gathered import forge_of, Gathered, ItemFacts, named_paths, NamedPath, NoItem, planned, Ran, Worktree, worktree_add
|
||||
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 todo_table import LastCut, unreleased_entries
|
||||
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\n1. **Achieve:** Work.\n\n## Audience\n\nMe.\n"
|
||||
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
|
||||
|
||||
@@ -33,7 +34,7 @@ TODO = """# todo
|
||||
| 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.** | 4 | 2 | 3 | 7 | 3 | 1 by 9 | 56.2 |
|
||||
| 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 |
|
||||
@@ -45,7 +46,7 @@ TODO = """# todo
|
||||
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.** | 4 | 2 | 3 | 7 | 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.")
|
||||
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.
|
||||
@@ -166,6 +167,18 @@ class ChunkPreflightTool(unittest.TestCase):
|
||||
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 = (
|
||||
@@ -247,7 +260,7 @@ class ChunkPreflightTool(unittest.TestCase):
|
||||
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 4, E + I 5", 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):
|
||||
@@ -302,7 +315,7 @@ 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 4, E + I 5", 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)
|
||||
@@ -316,8 +329,13 @@ class Render(unittest.TestCase):
|
||||
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("| 4 | 2 | 3 | 7 | 3 |", "| 7 | 3 |").replace("| 1 | 1 | 1 | 1 | 1 |", "| 1 | 1 |")
|
||||
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):
|
||||
@@ -397,30 +415,34 @@ class Plans(unittest.TestCase):
|
||||
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("| 4 | 2 | 3 |", "| x | 2 | 3 |"), 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, "finished and ready to cut"),
|
||||
(LATER, 0, "planned first"),
|
||||
(EMPTY, 4, "finished and ready to cut"),
|
||||
(EMPTY, 0, "planned first"),
|
||||
(LATER, Failure("count unreadable"), "cannot be read"),
|
||||
(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, fact in cases:
|
||||
with self.subTest(todo=todo, commits=commits):
|
||||
why = planned(todo, LastCut("v0.1.0", "", commits, [TODO]), "origin/main").why
|
||||
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("v0.1.0", 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)
|
||||
@@ -439,11 +461,6 @@ class Plans(unittest.TestCase):
|
||||
|
||||
|
||||
class Gathering(unittest.TestCase):
|
||||
def test_counts_the_top_level_entries_under_unreleased(self):
|
||||
self.assertEqual(unreleased_entries(CHANGELOG), 2)
|
||||
self.assertEqual(unreleased_entries("# Changelog\n\n## Unreleased\n\n## 0.1.0\n\n- Old.\n"), 0)
|
||||
self.assertIsNone(unreleased_entries("# Changelog\n\n## 0.1.0\n\n- Old.\n"))
|
||||
|
||||
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)]),
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"""Entries of Claude Code's transcripts and of its stream-json and json output."""
|
||||
import json
|
||||
import typing
|
||||
|
||||
|
||||
def parse_entry(raw: str | bytes) -> dict | None:
|
||||
@@ -36,8 +37,9 @@ def written_by_human(entry: dict) -> bool:
|
||||
# {"type": "user", "isMeta": true, "message": {"content": "<local-command-caveat>Caveat: ..."}}
|
||||
# {"type": "user", "promptSource": "sdk", "message": {"content": "Continue the task; ..."}}
|
||||
# {"type": "user", "promptSource": "system", "message": {"content": "<task-notification>..."}}
|
||||
# {"type": "user", "isCompactSummary": true, "message": {"content": "This session is being continued from a previous conversation that ran out of context. ..."}}
|
||||
def tagged_as_injected(entry: dict) -> bool:
|
||||
return bool(entry.get("isMeta")) or entry.get("promptSource") in ("sdk", "system")
|
||||
return bool(entry.get("isMeta")) or bool(entry.get("isCompactSummary")) or entry.get("promptSource") in ("sdk", "system")
|
||||
|
||||
|
||||
# {"type": "user", "promptSource": "typed", "message": {"content": "merge it"}}
|
||||
@@ -67,7 +69,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
|
||||
|
||||
@@ -86,11 +88,35 @@ def part_text(part: object) -> str | None:
|
||||
return part["text"] if isinstance(part, dict) and part.get("type") == "text" and isinstance(part.get("text"), str) else None
|
||||
|
||||
|
||||
# {"type": "tool_use", "name": "Bash", "input": {"command": "echo hi"}}
|
||||
# {"type": "tool_use", "id": "toolu_01…", "name": "Bash", "input": {"command": "echo hi"}}
|
||||
def tool_call(part: object) -> tuple[object, object] | None:
|
||||
return (part.get("name"), part.get("input")) if isinstance(part, dict) and part.get("type") == "tool_use" else None
|
||||
|
||||
|
||||
def tool_use_id(part: object) -> str | None:
|
||||
return part["id"] if isinstance(part, dict) and part.get("type") == "tool_use" and isinstance(part.get("id"), str) else None
|
||||
|
||||
|
||||
class ToolResult(typing.NamedTuple):
|
||||
tool_use_id: str
|
||||
text: str
|
||||
failed: bool
|
||||
|
||||
|
||||
# {"type": "tool_result", "tool_use_id": "toolu_01…", "content": "hi"}, its content also as [{"type": "text", "text": "hi"}], and with "is_error": true where the call failed
|
||||
def tool_result(part: object) -> ToolResult | None:
|
||||
if not isinstance(part, dict) or part.get("type") != "tool_result":
|
||||
return None
|
||||
return ToolResult(str(part.get("tool_use_id")), result_text(part.get("content")), bool(part.get("is_error")))
|
||||
|
||||
|
||||
def result_text(content: object) -> str:
|
||||
if isinstance(content, str):
|
||||
return content
|
||||
# Claude Code may split one text across blocks, even inside a line, so the blocks join with nothing between them.
|
||||
return "".join(part_text(part) or "" for part in content) if isinstance(content, list) else ""
|
||||
|
||||
|
||||
# stream-json's last line: {"type": "result", "subtype": "success", ...}
|
||||
def ends_stream(event: dict) -> bool:
|
||||
return event.get("type") == "result"
|
||||
|
||||
@@ -37,6 +37,11 @@ def session_files(transcript: str) -> list[str]:
|
||||
return sorted(glob.glob(glob.escape(transcript.removesuffix(".jsonl")) + "*"))
|
||||
|
||||
|
||||
# <session id>/subagents/agent-<agent id>.jsonl, beside <session id>.jsonl
|
||||
def subagent_transcript(session_transcript: str, agent_id: str) -> str:
|
||||
return os.path.join(session_transcript.removesuffix(".jsonl"), "subagents", f"agent-{agent_id}.jsonl")
|
||||
|
||||
|
||||
def delete_session(session: Session) -> Failure | None:
|
||||
path = transcript_file(session)
|
||||
if path is None:
|
||||
|
||||
@@ -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):
|
||||
@@ -45,6 +54,15 @@ class FirstTimestampedLine(unittest.TestCase):
|
||||
self.assertEqual(transcript.first_timestamped_line(b""), b"")
|
||||
|
||||
|
||||
class CurrentThread(unittest.TestCase):
|
||||
def test_a_parent_cycle_ends_the_thread(self):
|
||||
looped = [{"uuid": "a", "parentUuid": "b"}, {"uuid": "b", "parentUuid": "a"}]
|
||||
self.assertEqual([entry["uuid"] for entry in transcript.current_thread(looped)], ["a", "b"])
|
||||
|
||||
def test_entries_without_a_uuid_make_no_thread(self):
|
||||
self.assertEqual(transcript.current_thread([{"type": "summary"}]), [])
|
||||
|
||||
|
||||
class HumanTurns(unittest.TestCase):
|
||||
def test_counts_typed_turns_and_not_tool_results(self):
|
||||
self.assertEqual(transcript.human_turns([
|
||||
@@ -57,6 +75,7 @@ class HumanTurns(unittest.TestCase):
|
||||
{**human([{"type": "text", "text": "<task-notification>done</task-notification>"}]), "promptSource": "system"},
|
||||
{**human("peer message"), "isMeta": True},
|
||||
{**human("the loop's own prompt"), "promptSource": "sdk"},
|
||||
{**human("This session is being continued from a previous conversation that ran out of context. The summary below covers the earlier portion of the conversation."), "isCompactSummary": True},
|
||||
human([{"type": "text", "text": "[Request interrupted by user]"}]),
|
||||
human([]),
|
||||
queued("typed while claude worked", "human"),
|
||||
@@ -84,12 +103,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:
|
||||
@@ -14,6 +21,21 @@ def read_transcript(path: str) -> list[dict] | Failure:
|
||||
return Failure(f"could not read the transcript {path}: {failure.strerror}")
|
||||
|
||||
|
||||
def current_thread(entries: list[dict]) -> list[dict]:
|
||||
"""The entries of the transcript's current thread since its last compaction, oldest first: the newest entry with a uuid and its ancestors by parentUuid.
|
||||
|
||||
That leaves out a branch the session rewound, and the results of parallel tool calls that Claude Code chains on a side branch."""
|
||||
chained = [entry for entry in entries if isinstance(entry.get("uuid"), str)]
|
||||
by_uuid = {entry["uuid"]: entry for entry in chained}
|
||||
found: list[dict] = []
|
||||
entry = chained[-1] if chained else None
|
||||
# A compaction writes {"type": "system", "subtype": "compact_boundary", "parentUuid": null, ...}, so the thread starts there; the length check stops a parent cycle.
|
||||
while entry is not None and len(found) < len(chained):
|
||||
found.append(entry)
|
||||
entry = by_uuid.get(entry.get("parentUuid"))
|
||||
return found[::-1]
|
||||
|
||||
|
||||
# The lines before it, such as the session's title, are the same for every chunk of a project.
|
||||
def first_timestamped_line(raw: bytes) -> bytes:
|
||||
lines = raw.splitlines()
|
||||
@@ -24,14 +46,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 +66,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"
|
||||
@@ -104,15 +106,61 @@ def entries(history: str) -> list[Entry]:
|
||||
|
||||
|
||||
def latest_places(history: str) -> str | None:
|
||||
"""The places seats found hard from the oldest entry on the commit of 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)
|
||||
scored = [index for index, entry in enumerate(found) if not entry.paired or entry.scored_places]
|
||||
newest_commit = found[scored[-1]].commit if scored else None
|
||||
start = next((index for index in scored if found[index].commit == newest_commit), 0)
|
||||
"""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)
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
"""What a docker command asks of docker: its subcommand, and whether a container it makes has a memory limit and a swap limit. capped adds the limits such a container lacks."""
|
||||
import re
|
||||
import typing
|
||||
|
||||
# The options of docker, docker buildx and docker compose that take a value, so the value is not read as a subcommand.
|
||||
DOCKER_VALUED = frozenset({"--ansi", "--builder", "--config", "--context", "--env-file", "--file", "--host", "--log-level", "--parallel", "--profile", "--progress", "--project-directory", "--project-name", "--tlscacert", "--tlscert", "--tlskey", "-c", "-f", "-H", "-l", "-p"})
|
||||
# The subcommands that make a container, whose memory limits docker reads from the same options.
|
||||
STARTS_CONTAINER = (["container", "create"], ["container", "run"], ["create"], ["run"])
|
||||
# A size as docker reads one, such as 4g, 512M or 1.5GiB, each unit a power of 1024: go-units' RAMInBytes pattern, less a number with two points, such as 1.2.3, which its float parse refuses.
|
||||
SIZE = r"(\d+(?:\.\d+)?)([kKmMgGtTpP]?)[iI]?[bB]?"
|
||||
# Docker's documented floor for --memory, 6m: a smaller value, such as grep -m 1's, belongs to the container's own command.
|
||||
MEMORY_FLOOR = 6 * 1024**2
|
||||
MEMORY_OPTIONS = ("-m", "--memory")
|
||||
SWAP_OPTIONS = ("--memory-swap",)
|
||||
|
||||
|
||||
class Option(typing.NamedTuple):
|
||||
"""An option the arguments give: where it stands, how many words it takes, and its value."""
|
||||
at: int
|
||||
length: int
|
||||
value: str
|
||||
|
||||
|
||||
def size(value: str) -> float | None:
|
||||
"""The bytes a docker size spells; None for a value that is no size."""
|
||||
spelled = re.fullmatch(SIZE, value)
|
||||
return float(spelled.group(1)) * 1024 ** " kmgtp".index(spelled.group(2).lower() or " ") if spelled else None
|
||||
|
||||
|
||||
def memory_limit(value: str) -> bool:
|
||||
return (size(value) or 0) >= MEMORY_FLOOR
|
||||
|
||||
|
||||
def swap_limit(value: str) -> bool:
|
||||
"""Whether a --memory-swap value limits swap: -1 leaves it unlimited, and 0 leaves it unset, which docker reads as twice the memory limit."""
|
||||
return bool(size(value))
|
||||
|
||||
|
||||
def unset_swap(value: str) -> bool:
|
||||
return value == "-1" or size(value) == 0
|
||||
|
||||
|
||||
def zero(value: str) -> bool:
|
||||
return size(value) == 0
|
||||
|
||||
|
||||
def docker_subcommand(arguments: list[str]) -> list[str]:
|
||||
"""The subcommand docker's arguments name, past its options: such as ["build"], ["compose", "run"] or ["buildx", "build"]."""
|
||||
return [arguments[at] for at in subcommand_at(arguments)]
|
||||
|
||||
|
||||
def subcommand_at(arguments: list[str]) -> list[int]:
|
||||
"""Where in docker's arguments each word of its subcommand stands, so a global option's value that spells it, as in --context run, is not taken for it."""
|
||||
positional: list[int] = []
|
||||
skip = False
|
||||
for at, word in enumerate(arguments):
|
||||
if skip:
|
||||
skip = False
|
||||
elif word.startswith("-"):
|
||||
skip = word in DOCKER_VALUED
|
||||
else:
|
||||
positional.append(at)
|
||||
if arguments[positional[0]] not in ("buildx", "compose", "container") or len(positional) == 2:
|
||||
break
|
||||
return positional
|
||||
|
||||
|
||||
def unlimited(arguments: list[str]) -> bool:
|
||||
"""Whether docker's arguments make a container, with docker run or docker create, and leave its memory or its swap without a limit.
|
||||
|
||||
The container's own arguments, past its image, are read too: telling them apart needs every value-taking option of docker run. So a -m 4g there reads as a limit, while python -m pytest and grep -m 1 do not, since neither is a size docker takes.
|
||||
"""
|
||||
subcommand = docker_subcommand(arguments)
|
||||
limited = option_value(arguments, MEMORY_OPTIONS, memory_limit) and option_value(arguments, SWAP_OPTIONS, swap_limit)
|
||||
return subcommand in STARTS_CONTAINER and not limited and not helped(arguments)
|
||||
|
||||
|
||||
def helped(arguments: list[str]) -> bool:
|
||||
"""Whether docker only prints its help: a --help before the subcommand or as the first word after it, not one the container's own command takes."""
|
||||
after = subcommand_at(arguments)[-1] + 1
|
||||
return "--help" in arguments[:after + 1]
|
||||
|
||||
|
||||
def capped(arguments: list[str], share: str) -> list[str]:
|
||||
"""docker's arguments, with each limit a container they make lacks added right after the subcommand.
|
||||
|
||||
A container that sets neither limit gets share for both. One that sets one limit gets the other at the same size, since docker refuses less swap than memory. A --memory-swap of -1 or 0 is dropped; every other word stays. Arguments with a --memory of 0 anywhere come back unchanged.
|
||||
"""
|
||||
# A -m 0 asks docker for unlimited memory, and would override an added limit; it may also be the container's own, as in grep -m 0, so it is neither dropped nor capped.
|
||||
if not unlimited(arguments) or option_value(arguments, MEMORY_OPTIONS, zero):
|
||||
return arguments
|
||||
memory = option_value(arguments, MEMORY_OPTIONS, memory_limit)
|
||||
swap = option_value(arguments, SWAP_OPTIONS, swap_limit)
|
||||
rest = without(arguments, SWAP_OPTIONS, unset_swap)
|
||||
limits = ([] if memory else ["--memory", swap or share]) + ([] if swap else ["--memory-swap", memory or share])
|
||||
after = subcommand_at(rest)[-1] + 1
|
||||
return [*rest[:after], *limits, *rest[after:]]
|
||||
|
||||
|
||||
def option_value(arguments: list[str], options: tuple[str, ...], fits: typing.Callable[[str], bool]) -> str | None:
|
||||
"""The value the arguments give one of the options, where it fits, as its next word or attached, as in -m4g or --memory=4g; None where they give none."""
|
||||
found = option_at(arguments, options, fits)
|
||||
return found.value if found else None
|
||||
|
||||
|
||||
def without(arguments: list[str], options: tuple[str, ...], fits: typing.Callable[[str], bool]) -> list[str]:
|
||||
"""The arguments with each of the options removed, with its value, where the value fits."""
|
||||
while found := option_at(arguments, options, fits):
|
||||
arguments = [*arguments[:found.at], *arguments[found.at + found.length:]]
|
||||
return arguments
|
||||
|
||||
|
||||
def option_at(arguments: list[str], options: tuple[str, ...], fits: typing.Callable[[str], bool]) -> Option | None:
|
||||
"""Where the arguments first give one of the options, with a value that fits."""
|
||||
for at, (word, following) in enumerate(zip(arguments, [*arguments[1:], ""])):
|
||||
for option in options:
|
||||
attached = word.removeprefix(option if len(option) == 2 else option + "=")
|
||||
if attached != word and fits(attached):
|
||||
return Option(at, 1, attached)
|
||||
if word == option and fits(following):
|
||||
return Option(at, 2, following)
|
||||
return None
|
||||
+32
-41
@@ -1,23 +1,45 @@
|
||||
"""Run git, in the current directory or a given one, and read the checkout, its default branch and its files."""
|
||||
import dataclasses
|
||||
"""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
|
||||
from todo_table import LastCut
|
||||
|
||||
# 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, cwd: str | None = None, timeout: float | None = None) -> 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."""
|
||||
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, cwd=cwd, encoding="utf-8", timeout=timeout)
|
||||
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 {' '.join(args)} printed text that is not UTF-8: {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 Failure(f"git {command} could not start: {failure}")
|
||||
except subprocess.TimeoutExpired:
|
||||
return Failure(f"git {' '.join(args)}: stopped after {timeout} s")
|
||||
return ran.stdout if ran.returncode == 0 else Failure(f"git {' '.join(args)}: {ran.stderr.strip()}")
|
||||
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:
|
||||
@@ -62,37 +84,6 @@ def origin_head(cwd: str | None, timeout: float | None) -> str | Failure:
|
||||
return Failure("origin names no default branch; set it with `git remote set-head origin --auto`")
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class DefaultPlan:
|
||||
"""What the default branch, as last fetched, holds for picking the next chunk's item: todo_table.chunk_item's inputs."""
|
||||
# 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:
|
||||
"""todo.md's text at tag and at each later commit on ref that changed it, read in cwd; empty where there is no tag. 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", "--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 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.
|
||||
|
||||
@@ -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, memory=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, "bundled_escape_and_impact": 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"))
|
||||
|
||||
|
||||
@@ -1,17 +1,12 @@
|
||||
import decimal
|
||||
|
||||
from comprehension_history import counted_vote, entries, Entry, table_rows
|
||||
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 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 in a scoring table."""
|
||||
return {name: cells[-1] for name, cells in table_rows(entry.body).items() if cells and cells[-1]}
|
||||
|
||||
|
||||
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
|
||||
@@ -23,7 +18,7 @@ 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 sorted((each for each in found if not each.paired), key=lambda each: each.time):
|
||||
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])})
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
from git_repo import commits_since, file_at, full_history, git, newest_release_tag
|
||||
from failure import Failure
|
||||
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."""
|
||||
newest = newest_release_tag(default)
|
||||
if isinstance(newest, Failure):
|
||||
return newest
|
||||
count = commits_since(newest, default)
|
||||
return count if isinstance(count, Failure) else 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)
|
||||
@@ -2,14 +2,15 @@ import pathlib
|
||||
import time
|
||||
|
||||
from larv_review.agreement import agreement_report
|
||||
from comprehension_history import appended, DIMENSIONS, heading, Heading, HISTORY, latest_places, recorded, ruling_entry, scoring_entry, ScoringRun, vote_text
|
||||
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:
|
||||
@@ -21,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
|
||||
@@ -47,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:
|
||||
@@ -58,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:
|
||||
+50
-23
@@ -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, and its count of how often seats agree.
|
||||
"""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 | agreement
|
||||
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, 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.
|
||||
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,10 @@ 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.
|
||||
@@ -67,7 +70,9 @@ 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 scored commit: the places of each scoring
|
||||
run on it, and,
|
||||
@@ -81,30 +86,34 @@ and the inherited architect vote alike overall in a paired ruling more often tha
|
||||
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 record is appended to the history, created when missing, under a heading of the current UTC
|
||||
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_agreement, 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 | agreement"
|
||||
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:
|
||||
@@ -112,7 +121,9 @@ def main(argv: list[str]) -> int:
|
||||
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)
|
||||
@@ -152,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):
|
||||
|
||||
+45
-19
@@ -1,34 +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):
|
||||
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 {'.'.join(map(str, release))} with no plan item")
|
||||
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:
|
||||
@@ -36,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:
|
||||
@@ -44,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]:
|
||||
|
||||
@@ -13,14 +13,15 @@ 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"
|
||||
@@ -67,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"), [])]
|
||||
@@ -161,6 +167,8 @@ class History(unittest.TestCase):
|
||||
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:
|
||||
@@ -258,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):
|
||||
@@ -352,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"})
|
||||
@@ -387,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")
|
||||
@@ -407,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)
|
||||
@@ -416,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")})
|
||||
@@ -447,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,12 +12,37 @@ 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, env: dict[str, str], 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)
|
||||
|
||||
+78
-101
@@ -3,14 +3,15 @@ import json
|
||||
import re
|
||||
import typing
|
||||
|
||||
from loop_claude.cycle.prompts import ANSWER_DESTINATIONS, ANSWERS_RECORDED
|
||||
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 markdown_text import listed
|
||||
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
|
||||
@@ -18,9 +19,9 @@ from claude_code.entries import structured_output
|
||||
|
||||
# At 3 to 4 characters a token, 100,000 to 133,000 tokens, which leaves a 200,000-token context room for the reply; the largest session rendered here was 364,000 characters on 2026-10-03.
|
||||
JUDGE_PROMPT_CHARS = 400000
|
||||
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 "
|
||||
@@ -30,41 +31,50 @@ 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"{listed(HUMAN_RULE_NAMES, 'or')} 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 L the agent 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 bundled routes the worker.
|
||||
bundled_escape_and_impact: int = dataclasses.field(metadata={"description": "The highest E + I 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)
|
||||
@@ -83,37 +93,14 @@ class Rejected(Failure):
|
||||
reply: str
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Interrupt:
|
||||
evidence: str
|
||||
question: str
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class QuotedAnswer:
|
||||
"""The agent asked a question that README.md or the records answer. The answer field quotes the passage."""
|
||||
evidence: str
|
||||
question: str
|
||||
answer: str
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Finished:
|
||||
evidence: str
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Unfinished:
|
||||
evidence: str
|
||||
# The bundled L 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 = ""
|
||||
# The bundled E + I the judge saw, 0 for none.
|
||||
bundled_escape_and_impact: int = 0
|
||||
|
||||
|
||||
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:
|
||||
@@ -123,30 +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"])
|
||||
# A bundled level off its scale counts as none: holding the rung is safe, and three failures would stop an unattended loop.
|
||||
bundled = output["bundled"] if 0 <= output["bundled"] <= HIGHEST_L else 0
|
||||
bundled_escape_and_impact = output["bundled_escape_and_impact"] if on_its_scale(output["bundled_escape_and_impact"]) else 0
|
||||
return Unfinished(output["evidence"], bundled, output["escalation"], bundled_escape_and_impact)
|
||||
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, keep: typing.Callable[[Rejected], Stop | None]) -> Verdict | Stop:
|
||||
return retried("judge", lambda: judge_once(root, task, premises, records, rendered_transcript, rung, effects), effects, lambda failure: keep(failure) if isinstance(failure, Rejected) else None)
|
||||
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]:
|
||||
@@ -159,13 +147,8 @@ 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
|
||||
@@ -173,27 +156,31 @@ def run_judge(root: str, args: list[str], prompt: str, shown: str, quotable: str
|
||||
replied = json.dumps(reply, ensure_ascii=False)
|
||||
if isinstance(verdict, Failure):
|
||||
return Rejected(verdict.reason, replied)
|
||||
if not grounded(verdict.evidence, shown):
|
||||
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)
|
||||
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 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:
|
||||
@@ -207,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,32 +1,45 @@
|
||||
from model_routing.ladder import climbed, LADDER, position, review_rungs, ReviewKind, Rung
|
||||
from model_routing.route import ESCALATION_MARKER, HIGHEST_ESCAPE_AND_IMPACT, Route
|
||||
"""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 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 = 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"
|
||||
# Each kind of review, as review_launches names those it launches.
|
||||
REVIEWS: tuple[tuple[str, ReviewKind], ...] = (("each reviewer", "reviewer"), ("each comprehension seat", "seat"), ("the security pass's subagent", "security"))
|
||||
# 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, facts: str) -> str:
|
||||
AFTER_CODE_HEALTH = 'which rank after code health (~/.claude/CLAUDE.md → "Shared goal") unless README.md voids it'
|
||||
|
||||
|
||||
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."""
|
||||
escalated = f"{escalation(route, anchor)}{reruns(route, anchor)}".lstrip()
|
||||
routed = f"{routed_by(route, anchor)}{recount(route)}\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}{facts}\n\nThe 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}"
|
||||
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 routed_by(route: Route, anchor: Rung | None) -> str:
|
||||
return f"loop-claude runs you on {route.rung}, routed by item {route.item}'s L of {route.likelihood}. Name each todo.md item this chunk takes, with its L and E + I, whether or not it is item {route.item}.{review_launches(route, anchor)}{escalation(route, anchor)}{reruns(route, anchor)}"
|
||||
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 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."
|
||||
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:
|
||||
@@ -39,87 +52,144 @@ def preflight_failed(reason: str) -> str:
|
||||
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, anchor: Rung | None) -> str:
|
||||
"""Which reviews to launch on a rung other than the worker's, and on which; below the project's rung, anchor, also where to launch a subagent that files or scores todo.md items; then taken_in_launches, the reviewers' rung each higher E + I picks. Empty off the ladder.
|
||||
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, it opens: ` Launch each reviewer with the Agent tool set to model opus, effort high, the rung item 3's E + I of 5 picks. Launch each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium, the project's rung.`
|
||||
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 anchor is None:
|
||||
return ""
|
||||
rungs = review_rungs(anchor, route.rung, route.reviewed_on())
|
||||
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, kind in REVIEWS:
|
||||
if rungs[kind] != route.rung:
|
||||
launched.setdefault(rungs[kind], []).append(reviews)
|
||||
launches = "".join(f" Launch {listed(reviews, 'and')} with the Agent tool set to {rung.agent_args()}, {rung_named(rung, route, anchor)}." for rung, reviews in launched.items())
|
||||
scan = " Run a full scan only from such a subagent, since the scan's agents run on the model that starts them." if rungs["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 {anchor.model} <L>` prints." if position(route.rung) < position(anchor) else ""
|
||||
return f"{launches}{scan}{planning}{taken_in_launches(route, anchor)}"
|
||||
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(route: Route, anchor: Rung) -> str:
|
||||
"""The rung each higher E + I picks for the reviewers, so the worker reviews an item it takes in on that rung in the same run; the judge reports it as the cycle ends, so loop-claude routes on it only from the next cycle. Empty where no higher E + I picks a higher rung.
|
||||
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, 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.`
|
||||
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.`
|
||||
"""
|
||||
reviewers = review_rungs(anchor, route.rung, route.reviewed_on())["reviewer"]
|
||||
higher: dict[Rung, int] = {}
|
||||
for escape_and_impact in range(route.reviewed_on() + 1, HIGHEST_ESCAPE_AND_IMPACT + 1):
|
||||
rung = review_rungs(anchor, route.rung, escape_and_impact)["reviewer"]
|
||||
if position(rung) > position(reviewers):
|
||||
higher.setdefault(rung, escape_and_impact)
|
||||
if not higher:
|
||||
return ""
|
||||
picks = [f"`{rung.agent_args()}` from {escape_and_impact}" for rung, escape_and_impact in higher.items()]
|
||||
return f" Where an item you take into the chunk has an E + I of {min(higher.values())} or more, launch each reviewer with the Agent tool set to {listed(picks, 'and')}."
|
||||
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, anchor: Rung) -> str:
|
||||
"""Why a review runs on rung: it is the project's, anchor, or the one the route's reviewed_on E + I picks, the item's or one taken in."""
|
||||
if rung == anchor:
|
||||
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, 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 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 ""
|
||||
rungs = review_rungs(anchor, route.rung, route.reviewed_on())
|
||||
launched = (("reviewer", rungs["reviewer"]), ("comprehension seat", rungs["seat"]))
|
||||
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 {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()}`."
|
||||
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}{review_launches(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:
|
||||
|
||||
@@ -2,22 +2,24 @@ 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 loop_claude.cycle.worker import AUTO_COMPACT_WINDOW, COMPACT_WINDOW, run_worker, worker_args
|
||||
from claude_code.session import delete_session, Session, session_open, transcript_file
|
||||
from loop_claude.effects import Effects
|
||||
from failure import Failure
|
||||
from loop_claude.cycle.judge import Finished, Interrupt, judge, QuotedAnswer, Rejected, 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
|
||||
|
||||
@@ -37,28 +39,50 @@ 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
|
||||
# A failed archive exits 1 whatever the stop; when the stop was this archive failing, its reason is said once.
|
||||
return archived_stop(cycle.project_archive, cycle.session, cycle.task, cycle.route, stop, why, cycle.effects)
|
||||
|
||||
|
||||
def archived_stop(project_archive: pathlib.Path, session: Session, task: str, route: Route, stop: Stop, why: str, effects: Effects) -> Stop:
|
||||
"""stop, once archived with the route the worker holds. A failed archive exits 1 whatever the stop; when the stop was this archive failing, its reason is said once."""
|
||||
path = transcript_file(session)
|
||||
failure = archive(project_archive, path, task, outcomes.stopped(route.worker_line(), why), effects.now()) if path else None
|
||||
return Stop(1, f"{failure.reason}\n{stop.reason}".rstrip()) if failure and failure.reason != stop.reason else stop
|
||||
|
||||
|
||||
@@ -69,46 +93,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), worker_environment(cycle), 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_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.anchor, cycle.route)
|
||||
"""The rungs the worker's claude is handed, which rule-hook holds its review launches to, and the auto-compact window of its context."""
|
||||
return {**worker_rungs.environment(cycle.project, cycle.route), AUTO_COMPACT_WINDOW: str(COMPACT_WINDOW)}
|
||||
|
||||
|
||||
def worker_start(cycle: Cycle, answered: QuotedAnswer | 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_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, cycle.facts), 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
|
||||
|
||||
@@ -117,8 +149,8 @@ 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, lambda rejected: keep_rejection(cycle, transcript_path, rejected))
|
||||
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 keep_rejection(cycle: Cycle, transcript_path: str, rejected: Rejected) -> Stop | None:
|
||||
@@ -128,12 +160,32 @@ def keep_rejection(cycle: Cycle, transcript_path: str, rejected: Rejected) -> St
|
||||
return None
|
||||
|
||||
|
||||
def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer) -> HumanAnswered | Stop:
|
||||
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, worker_environment(cycle), 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:
|
||||
@@ -143,7 +195,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)
|
||||
|
||||
@@ -1,15 +1,24 @@
|
||||
import sys
|
||||
|
||||
from claude_code.entries import assistant_parts, ends_stream, hit_limit, limit_said, parse_entry, rejected_until
|
||||
from loop_claude.effects import Effects
|
||||
from failure import Failure
|
||||
from claude_code.reply import Limited
|
||||
from claude_code.transcript import part_line
|
||||
from machine_load.memory import ROOM_SHARE
|
||||
from model_routing.ladder import Rung
|
||||
from claude_code.session import Session
|
||||
|
||||
PRINTED_TOOL_INPUT = 160
|
||||
# Seconds between reads of the machine's memory while too little of it is available to start a worker.
|
||||
MEMORY_POLL = 60
|
||||
# The auto-compact window, in tokens, handed to the worker's claude in the environment variable AUTO_COMPACT_WINDOW names. Claude Code compacts before the window fills, at about 170k: docs/decisions.md → `loop-claude: the worker's claude compacts its context before it fills a 200k window`.
|
||||
AUTO_COMPACT_WINDOW = "CLAUDE_CODE_AUTO_COMPACT_WINDOW"
|
||||
COMPACT_WINDOW = 200_000
|
||||
|
||||
|
||||
def run_worker(root: str, args: list[str], env: dict[str, str], effects: Effects) -> Failure | Limited | None:
|
||||
wait_for_memory(effects)
|
||||
try:
|
||||
proc = effects.stream_claude(args, root, env)
|
||||
except OSError as failure:
|
||||
@@ -28,6 +37,16 @@ def run_worker(root: str, args: list[str], env: dict[str, str], effects: Effects
|
||||
return worker_outcome(proc.wait(), result, resets)
|
||||
|
||||
|
||||
def wait_for_memory(effects: Effects) -> None:
|
||||
"""Returns once the machine has room for a worker, or its memory cannot be read, so loops running at once do not push it into swap. While it waits, it says so once on stderr and reads the memory again each MEMORY_POLL seconds."""
|
||||
said = False
|
||||
while (memory := effects.memory()) is not None and not memory.has_room():
|
||||
if not said:
|
||||
print(f"waiting to start the worker until at least {ROOM_SHARE:.0%} of the machine's memory is available; {memory.available // 1024} MiB of {memory.total // 1024} MiB is available now", file=sys.stderr, flush=True)
|
||||
said = True
|
||||
effects.sleep(MEMORY_POLL)
|
||||
|
||||
|
||||
def worker_outcome(code: int, result: dict | None, resets: list[int]) -> Failure | Limited | None:
|
||||
if result is not None and hit_limit(result):
|
||||
return Limited(max(resets, default=None), limit_said(result))
|
||||
@@ -47,6 +66,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,13 +2,24 @@ import dataclasses
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import termios
|
||||
import time
|
||||
import typing
|
||||
|
||||
from failure import Failure
|
||||
import git_repo
|
||||
from machine_load.memory import Memory, read_memory
|
||||
|
||||
# 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."""
|
||||
|
||||
@@ -21,10 +32,14 @@ class Streaming(typing.Protocol):
|
||||
class Effects:
|
||||
claude: typing.Callable[[list[str], str, str], subprocess.CompletedProcess[str]]
|
||||
claude_on_terminal: typing.Callable[[list[str], str, dict[str, str]], int]
|
||||
# Drops what was typed on the terminal and not yet read.
|
||||
discard_typed: typing.Callable[[], None]
|
||||
execv: typing.Callable[[str, list[str]], None]
|
||||
git: typing.Callable[[list[str], str], subprocess.CompletedProcess[str]]
|
||||
git: Git
|
||||
input: typing.Callable[[str], str]
|
||||
local_time: typing.Callable[[float], str]
|
||||
# The machine's memory; None where it cannot be read.
|
||||
memory: typing.Callable[[], Memory | None]
|
||||
now: typing.Callable[[], float]
|
||||
on_terminal: typing.Callable[[], bool]
|
||||
# Runs a Python script in a directory, as run_python does.
|
||||
@@ -49,10 +64,12 @@ 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, 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)),
|
||||
memory=read_memory,
|
||||
now=time.time,
|
||||
on_terminal=lambda: sys.stdin.isatty() and sys.stdout.isatty(),
|
||||
python=lambda args, cwd: run_python(args, cwd, PYTHON_TIMEOUT),
|
||||
|
||||
@@ -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
|
||||
+128
-123
@@ -4,10 +4,11 @@ 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, and the human's
|
||||
~/.claude/CLAUDE.md, ~/.claude/rules/*.md and
|
||||
worker prompt also quotes the premises. They, with code health
|
||||
(~/.claude/CLAUDE.md → "Shared goal") ranked first unless README.md voids it, choose between ways
|
||||
to deliver the chunk's todo.md items, or else the task, and never widen them. A judge then reads
|
||||
the transcript's end, the premises, and the records: the project's AGENTS.md and docs/decisions.md,
|
||||
and the human's ~/.claude/CLAUDE.md, ~/.claude/rules/*.md and
|
||||
~/.claude/skills/larv-review/standards/*.md, where they exist. It rules whether the chunk, the work
|
||||
of one PR, is finished. A chunk stays unfinished until each answer the human typed in it that a
|
||||
later chunk could need is recorded: the premises or the records hold it, or the transcript shows the worker
|
||||
@@ -16,13 +17,19 @@ 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
|
||||
@@ -32,87 +39,45 @@ 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; each judge reply the loop rejected, with the reason and the reply as json;
|
||||
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.
|
||||
|
||||
Before each worker starts, loop-claude waits until at least a quarter of the machine's memory is available
|
||||
(bin/machine_load/memory.py).
|
||||
|
||||
Each worker's claude, the session /talk opens and the subagents either launches run with a 200k
|
||||
auto-compact window (CLAUDE_CODE_AUTO_COMPACT_WINDOW, bin/loop_claude/cycle/worker.py), so each
|
||||
compacts its context at about 170k tokens.
|
||||
|
||||
Every claude loop-claude starts runs the project's model, saved per <key> in
|
||||
~/.claude/loop-claude-models.json and read each cycle, unless routing, below, puts the worker,
|
||||
the 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, it is routed
|
||||
on the item chunk-preflight names, read from todo.md on the default branch as the preflight just
|
||||
fetched it (todo_table.chunk_item). That item is the earliest release's top item that does not wait,
|
||||
but only where that release is the next one: the earliest after the newest vX.Y.Z tag that todo.md
|
||||
has named at that tag or since, or any earliest release where no tag names a version. Otherwise no
|
||||
item routes the chunk. An item waits while it is marked
|
||||
question, or while an item that blocks it is still in the table. The item's L
|
||||
picks the worker's rung, stepping from the model's cheapest rung by WORKER_STEPS in
|
||||
bin/model_routing/ladder.py, below it for a low L; without such an item, or with its L, E or I
|
||||
unscored, the chunk runs on the model's cheapest rung. The
|
||||
item's E + I picks the reviewers' rung, stepping up from the cheapest rung by REVIEW_STEPS there,
|
||||
never below the worker's 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 L and E + I, and to count the item's size again
|
||||
once it has read the code (prompts.recount). The prompt names the rung of each review that runs on
|
||||
a rung other than the worker's: the reviewers' rung for the reviewers, and the cheapest rung for
|
||||
each comprehension seat and the security pass. It also names the reviewers' rung
|
||||
each higher E + I picks, so the worker reviews an item it takes in on that rung in the same run.
|
||||
When the worker runs below the cheapest rung, the prompt has it launch each subagent that files or
|
||||
scores todo.md items on the rung subagent-rung --plan prints. The prompt after
|
||||
each unfinished verdict says this again, since a step-up may have moved the worker. A reviewer or
|
||||
seat that rules the work below standard may ask to rerun one rung up; each prompt names that rung.
|
||||
loop-claude hands the worker's claude its own rung, the project's and the reviewers', in
|
||||
LOOP_CLAUDE_WORKER_RUNG, LOOP_CLAUDE_PROJECT_RUNG and LOOP_CLAUDE_REVIEWER_RUNG, and rule-hook
|
||||
refuses a review launched below the rung named for it. The judge reports the highest L and the
|
||||
highest E + I the worker states for an item it takes in. The next cycle steps the worker up to the
|
||||
rung that L picks, never down, and the reviewers to the rung picked by the higher of two: that
|
||||
E + I, or the routed item's (Route.reviewed_on in bin/model_routing/route.py). A level off its
|
||||
scale counts as none. Every second unfinished verdict on a chunk steps it up one rung
|
||||
(routing.stepped). 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, L and E + I that routed the chunk, and any taken-in E + I that picks a
|
||||
higher review rung, which is archived as a step-up too. A rerun resumes an open chunk on the latest
|
||||
route named there, and counts its unfinished verdicts afresh. A rung no longer on the ladder, or
|
||||
below the one its item's L picks, is dropped, and the chunk is routed afresh from todo.md. So is a
|
||||
chunk whose archived line names an R + C, as loop-claude wrote before it routed on L. 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 that
|
||||
the reviewers' E + I (Route.reviewed_on) picks for a review from that model. It never runs below the
|
||||
model's cheapest rung, and runs on it when no item routed the chunk or was taken in. Its rung stays
|
||||
put when the worker steps up. 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.
|
||||
@@ -141,10 +106,12 @@ Exit 1, saying why, when:
|
||||
more than 2 minutes past. The judge's reply gives its reset time only as text, so the judge is
|
||||
always retried every 10 minutes. stderr says when the next try is due.
|
||||
|
||||
Exit 2, when the human is needed and cannot answer:
|
||||
Exit 2, when the human is needed to go on:
|
||||
- stdin or stdout is not a terminal, when a model must be picked or an interrupt answered
|
||||
- the input ends while a model is picked
|
||||
- an interrupt 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
|
||||
- the judge rules a chunk unfinished 6 cycles running; rerun to give it 6 more
|
||||
Rerunning resumes any open session.
|
||||
|
||||
"""
|
||||
@@ -153,20 +120,22 @@ 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.cycle.run import archived_stop, Concluded, Cycle, run_cycle
|
||||
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.loop.reload import decode_handed, exec_if_edited, fingerprint, LoopRun, RELOAD_FLAG
|
||||
from git_repo import default_plan, default_ref, DefaultPlan
|
||||
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
|
||||
from loop_claude.stop import needs_human, Stop
|
||||
from transcript_archive import outcomes
|
||||
from loop_claude.paths import Paths
|
||||
from project_key import project_key
|
||||
@@ -176,10 +145,11 @@ from loop_claude.project.premises import read_premises
|
||||
from loop_claude.project.records import read_records
|
||||
from model_routing.route import Route, route_from
|
||||
from claude_code.session import Session, session_named, session_open, transcript_file
|
||||
from loop_claude.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
|
||||
# How many unfinished verdicts running end the loop, so a worker and a judge that disagree about a chunk cannot cycle unattended without end. A policy number, not derived from the routing steps: well above the two unfinished verdicts running that archived chunks have reached at most, and low enough that a stuck pair is stopped after six cycles. It counts every unfinished verdict, including those of cycles where the human answered an interrupt: a rerun is cheap, and a chunk that needs that many answers is worth a look. The human confirmed both the number and what it counts.
|
||||
UNFINISHED_LIMIT = 6
|
||||
|
||||
|
||||
def main(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher: pathlib.Path, cwd: pathlib.Path, effects: Effects) -> int:
|
||||
@@ -214,45 +184,71 @@ 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
|
||||
# Before routing, which reads the plan as the preflight's fetch left it; after the reads above, so a loop that stops on one makes no worktree.
|
||||
facts = "" if session_open(session) else chunk_facts(launcher.with_name("chunk-preflight"), loop_run.root, effects)
|
||||
anchor = project_rung(models.worker)
|
||||
root = loop_run.root
|
||||
loop_run = routed(loop_run, anchor, lambda: archived_route(archive_folder, session), lambda: plan_item(fetched_plan(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, facts=facts, 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):
|
||||
return stop
|
||||
if stop := check_routing(archive_root(paths.home, env), anchor or Rung(models.worker), paths, 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
|
||||
closed = closed_cycle(loop_run, project, concluded, archive_folder, session, effects)
|
||||
if isinstance(closed, Stop):
|
||||
return closed
|
||||
loop_run = closed
|
||||
if stop := check_routing(archive_root(paths.home, env), project or Rung(models.worker), paths, effects):
|
||||
return stop
|
||||
|
||||
|
||||
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 L 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 closed_cycle(loop_run: LoopRun, project: Rung | None, concluded: Concluded, archive_folder: pathlib.Path, session: Session, effects: Effects) -> LoopRun | Stop:
|
||||
"""The loop run after a cycle concluded, with the step-up archived; the stop that needs the human, archived, once the chunk has had UNFINISHED_LIMIT unfinished verdicts running."""
|
||||
after = after_verdict(loop_run, project, concluded)
|
||||
if stop := archive_step(archive_folder, session, after.task, concluded.route, after.route, effects):
|
||||
return stop
|
||||
if limit := reached_limit(after):
|
||||
# An unfinished verdict always leaves a route; the `or` only satisfies LoopRun.route's optional type. The stop is archived with that route, the one the next cycle would run on, so a rerun resumes there.
|
||||
return archived_stop(archive_folder, session, after.task, after.route or concluded.route, limit, limit.reason, effects)
|
||||
return after
|
||||
|
||||
|
||||
def reached_limit(loop_run: LoopRun) -> Stop | None:
|
||||
"""The stop that needs the human once the loop run holds UNFINISHED_LIMIT unfinished verdicts running."""
|
||||
if loop_run.unfinished_run < UNFINISHED_LIMIT:
|
||||
return None
|
||||
return needs_human("go on with the chunk", f"the judge ruled it unfinished {loop_run.unfinished_run} cycles running; finish the chunk yourself, or rerun loop-claude to give it {UNFINISHED_LIMIT} more cycles")
|
||||
|
||||
|
||||
def after_verdict(loop_run: LoopRun, project: Rung | None, concluded: Concluded) -> LoopRun:
|
||||
"""The loop run the next cycle starts from. A finished chunk drops its route and its run of unfinished verdicts. An unfinished one takes the route stepped_route makes, the evidence the judge gave for the verdict, and counts the verdict."""
|
||||
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)).taking_in(verdict.bundled_escape_and_impact) 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=None, unfinished_evidence="", unfinished_run=0)
|
||||
route = stepped_route(project, concluded.route, verdict)
|
||||
return dataclasses.replace(loop_run, route=route, unfinished_evidence=verdict.evidence, unfinished_run=loop_run.unfinished_run + 1)
|
||||
|
||||
|
||||
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, or the higher E + I it took in; the verdict itself names the route its cycle ran on."""
|
||||
if not (before and loop_run.route) or str(loop_run.route) == str(before):
|
||||
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
|
||||
|
||||
|
||||
@@ -263,7 +259,16 @@ 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 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:
|
||||
@@ -275,13 +280,13 @@ def chunk_facts(preflight: pathlib.Path, root: str, effects: Effects) -> str:
|
||||
|
||||
|
||||
def fetched_plan(root: str) -> DefaultPlan | Failure:
|
||||
"""What the default branch, as chunk-preflight's fetch left it, holds for routing."""
|
||||
"""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, todo_table.chunk_item's pick from the default branch; None without one, so the chunk runs on the project's rung."""
|
||||
"""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):
|
||||
|
||||
@@ -22,8 +22,10 @@ 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
|
||||
# How many unfinished verdicts the chunk has had running; a finished chunk and a rerun each set it to 0. It stays apart from route and unfinished_evidence, though all three change together at each verdict: merging or renaming a field stops a running loop at its next reload.
|
||||
unfinished_run: int = 0
|
||||
|
||||
|
||||
def decode_handed(handed: str, kind: type[T]) -> T | None:
|
||||
|
||||
@@ -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})
|
||||
|
||||
+68
-36
@@ -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 todo_table import chunk_item, Item, items, LastCut
|
||||
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 loop_claude.verdicts import Interrupt, QuotedAnswer, Unfinished
|
||||
from todo_table import Item, items, NoItemsTable
|
||||
from model_routing.route import Route
|
||||
|
||||
UNFINISHED_PER_STEP = 2
|
||||
@@ -14,69 +25,90 @@ JUDGE_REPLAYED = ("claude-opus-5-5",)
|
||||
|
||||
|
||||
def routed_item(todo: str, cut: LastCut) -> Item | Failure | None:
|
||||
"""The item todo_table.chunk_item picks from todo.md, weighed against the last cut; None when there is none, or it lacks L, E or I."""
|
||||
"""The item 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, NoItemsTable):
|
||||
return None
|
||||
if isinstance(found, Failure):
|
||||
return found
|
||||
_, takes = chunk_item(found or [], cut)
|
||||
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 L 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(worker_rung(anchor, item.likelihood), item.id, item.likelihood, item.escape_and_impact)
|
||||
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 L 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 worker_rung(anchor, route.likelihood) 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. Its rules, in order: the rung never falls below kept_rung; a bundled item lifts it to the rung that item's L picks; every second unfinished verdict steps it up one rung; so does an escalation the judge found, up to escalation_cap, two rungs above item_rung; and both steps on one verdict make one step.
|
||||
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 L the judge saw the worker take into the chunk, 0 for none."""
|
||||
return highest(kept_rung(anchor, route), worker_rung(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:
|
||||
@@ -84,7 +116,7 @@ def judge_rung(judge_model: str, route: Route) -> Rung:
|
||||
|
||||
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 review_floor(anchor, route.reviewed_on())
|
||||
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,
|
||||
@@ -112,6 +116,11 @@ if os.path.basename(sys.argv[0]) == "loop-claude":
|
||||
record({"argv": sys.argv[1:]})
|
||||
pause = time.sleep
|
||||
time.sleep = lambda seconds: record({"sleep": seconds}) if seconds >= 1 else pause(seconds)
|
||||
# The host's own memory doesn't matter: every read finds all of it available.
|
||||
sys.path.insert(0, os.path.dirname(os.path.realpath(sys.argv[0])))
|
||||
import pathlib
|
||||
from machine_load import memory
|
||||
memory.MEMINFO = pathlib.Path(os.environ["FAKE_MEMINFO"])
|
||||
"""
|
||||
|
||||
PREMISES = "# Project\n\n## Goals\n\n1. Work.\n\n## Audience\n\nMe.\n"
|
||||
@@ -121,12 +130,16 @@ TODO = "## Items\n\n| ID | Release | Exempt | Item | L | E | I | R | S | Moves |
|
||||
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, bundled_escape_and_impact=0, escalation="", **step):
|
||||
verdict = {"answer": "", "bundled": bundled, "bundled_escape_and_impact": bundled_escape_and_impact, "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}
|
||||
|
||||
|
||||
@@ -173,8 +186,10 @@ class Checkout:
|
||||
site = self.temp / "site"
|
||||
site.mkdir()
|
||||
(site / "sitecustomize.py").write_text(SITECUSTOMIZE)
|
||||
(self.temp / "meminfo").write_text("MemTotal: 16 kB\nMemAvailable: 16 kB\n")
|
||||
self.env.update({
|
||||
"FAKE_CLAUDE_LOG": str(self.temp / "calls.jsonl"),
|
||||
"FAKE_MEMINFO": str(self.temp / "meminfo"),
|
||||
"FAKE_CLAUDE_SCENARIO": str(self.temp / "scenario.json"),
|
||||
"GIT_CONFIG_GLOBAL": os.devnull,
|
||||
"GIT_CONFIG_NOSYSTEM": "1",
|
||||
@@ -196,7 +211,7 @@ class Checkout:
|
||||
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):
|
||||
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))
|
||||
@@ -206,7 +221,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"])),
|
||||
@@ -217,8 +232,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:
|
||||
@@ -226,12 +241,13 @@ 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())
|
||||
output, deadline = b"", time.monotonic() + 60
|
||||
while time.monotonic() < deadline:
|
||||
if select.select([controller], [], [], 1)[0]:
|
||||
if select.select([controller], [], [], 0.05)[0]:
|
||||
try:
|
||||
chunk = os.read(controller, 4096)
|
||||
except OSError:
|
||||
@@ -322,7 +338,7 @@ 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)
|
||||
@@ -366,7 +382,7 @@ 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"))
|
||||
@@ -381,9 +397,9 @@ 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_l_and_steps_it_up_within_the_chunk(self):
|
||||
@@ -393,7 +409,7 @@ class Cycles(unittest.TestCase):
|
||||
run = checkout.run([
|
||||
worker(say="one"), judge(evidence="one"),
|
||||
worker(say="two"), judge(evidence="two"),
|
||||
worker(say="three"), judge(evidence="three", bundled=4),
|
||||
worker(say="three"), judge(evidence="three", highest_likelihood_taken_in=4),
|
||||
worker(say="four"), judge(finished=True, evidence="four"),
|
||||
worker(say="next chunk"),
|
||||
])
|
||||
@@ -409,8 +425,8 @@ class Cycles(unittest.TestCase):
|
||||
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-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 medium effort, routed by item 4's L of 2 and E + I of 3\n\n<UTC> Stepped up\n\nWorker: claude-opus-5-5 at high effort, routed by item 4's L of 2 and E + I of 3\n", outcomes)
|
||||
self.assertIn("<UTC> Verdict: finished\n\nEvidence:\n> four\n\nJudge: judge-model\nWorker: claude-opus-5-5 at high effort, routed by item 4's L of 2 and E + I of 3\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)
|
||||
@@ -455,8 +471,26 @@ 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 L of 4 and E + I of 5\n\n<UTC> Stepped up\n\nWorker: claude-opus-5-5 at xhigh effort, routed by item 4's L of 4 and E + I of 5\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 L of 4 and E + I of 5\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)
|
||||
@@ -468,7 +502,7 @@ class Cycles(unittest.TestCase):
|
||||
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('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):
|
||||
@@ -476,7 +510,7 @@ class Cycles(unittest.TestCase):
|
||||
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", bundled_escape_and_impact=6),
|
||||
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"),
|
||||
])
|
||||
@@ -486,8 +520,8 @@ class Cycles(unittest.TestCase):
|
||||
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: claude-sonnet-5-5 at high effort, routed by item 4's L of 2 and E + I of 3, taking in an E + I of 6\n", outcomes)
|
||||
self.assertIn("Judge: claude-opus-5-5 at xhigh effort\nWorker: claude-sonnet-5-5 at high effort, routed by item 4's L of 2 and E + I of 3, taking in an E + I of 6\n", outcomes)
|
||||
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)
|
||||
@@ -613,6 +647,36 @@ class Cycles(unittest.TestCase):
|
||||
self.assertEqual((run.code, run.roles()), (1, ["worker"]))
|
||||
self.assertIn("claude left no transcript for session", run.stderr)
|
||||
|
||||
def test_exits_2_after_six_unfinished_verdicts_running_and_a_rerun_gets_six_more(self):
|
||||
checkout = Checkout(self)
|
||||
six = [step for _ in range(6) for step in (worker(), judge())]
|
||||
run = checkout.run(six + [worker()])
|
||||
self.assertEqual((run.code, run.roles()), (2, ["worker", "judge"] * 6))
|
||||
self.assertIn("the judge ruled it unfinished 6 cycles running", run.stderr.strip().splitlines()[-1])
|
||||
self.assertIn("rerun loop-claude to give it 6 more cycles", run.stderr.strip().splitlines()[-1])
|
||||
stops = [outcome for outcome in checkout.archived().values() if "Stopped: " in outcome]
|
||||
self.assertEqual(len(stops), 1)
|
||||
self.assertIn(f"\n\nWorker: {OFF_LADDER}\n", stops[0])
|
||||
run = checkout.run(six[:-2] + [worker()])
|
||||
self.assertEqual((run.code, run.roles()), (130, ["worker", "judge"] * 6))
|
||||
|
||||
def test_archives_the_stop_on_the_route_the_sixth_verdict_stepped_to_and_a_rerun_resumes_there(self):
|
||||
checkout = Checkout(self)
|
||||
checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = "claude-opus-5-5"
|
||||
checkout.commit_plan(CHEAP)
|
||||
run = checkout.run([step for _ in range(6) for step in (worker(), judge())] + [worker()])
|
||||
self.assertEqual(run.code, 2)
|
||||
stepped = '<UTC> Stepped up\n\nWorker: {"model": "claude-opus-5-5", "effort": "xhigh", "item": 4, "likelihood": 2, "escape_and_impact": 3}\n\n<UTC> Stopped: '
|
||||
self.assertEqual(len([outcome for outcome in checkout.archived().values() if stepped in outcome]), 1)
|
||||
run = checkout.run([worker()])
|
||||
self.assertEqual([(argument(call, "--model"), argument(call, "--effort")) for call in run.calls if call["role"] == "worker"], [("claude-opus-5-5", "xhigh")])
|
||||
|
||||
def test_five_unfinished_verdicts_and_a_finished_one_do_not_add_up_to_six(self):
|
||||
checkout = Checkout(self)
|
||||
five = [step for _ in range(5) for step in (worker(), judge())]
|
||||
run = checkout.run(five + [worker(), judge(finished=True)] + five + [worker()])
|
||||
self.assertEqual((run.code, run.roles()), (130, ["worker", "judge"] * 12))
|
||||
|
||||
|
||||
class Interrupt(unittest.TestCase):
|
||||
def test_exits_2_off_a_terminal_and_resumes_on_the_next_run(self):
|
||||
@@ -624,7 +688,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")
|
||||
@@ -637,6 +701,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")
|
||||
@@ -645,7 +720,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"]
|
||||
@@ -663,13 +738,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)
|
||||
@@ -687,14 +762,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)
|
||||
@@ -707,7 +782,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(), "{}")
|
||||
@@ -715,7 +790,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$")
|
||||
|
||||
@@ -823,7 +898,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, "unfinished_run": cycle} for cycle in (2, 3, 4)])
|
||||
self.assertIn("=== cycle 5,", run.stdout)
|
||||
|
||||
outside = checkout.temp / "outside"
|
||||
|
||||
+552
-177
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
|
||||
@@ -0,0 +1,38 @@
|
||||
"""How much of the machine's memory is available, as /proc/meminfo's MemAvailable and MemTotal state it. A worker starts while at least ROOM_SHARE of it is available. The rest is split across the heavy slots, as the memory limit run-heavy gives each container."""
|
||||
import dataclasses
|
||||
import pathlib
|
||||
import re
|
||||
|
||||
MEMINFO = pathlib.Path("/proc/meminfo")
|
||||
# A worker starts only while at least this share of the machine's memory is available; the human chose it, as no standard sets one. The rest is the heavy slots' share, so changing it also changes the memory limit run-heavy gives a container.
|
||||
ROOM_SHARE = 0.25
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Memory:
|
||||
"""The machine's memory, in kB as /proc/meminfo counts it: what a new process can have without swapping, and all of it."""
|
||||
available: int
|
||||
total: int
|
||||
|
||||
def has_room(self) -> bool:
|
||||
return self.available >= ROOM_SHARE * self.total
|
||||
|
||||
def slot_share(self, slots: int) -> int:
|
||||
"""The memory limit, in MiB, that run-heavy gives each container a slot's command makes: what ROOM_SHARE leaves, split evenly across the slots."""
|
||||
return int(self.total * (1 - ROOM_SHARE)) // slots // 1024
|
||||
|
||||
|
||||
def parsed(meminfo: str) -> Memory | None:
|
||||
"""The memory a /proc/meminfo text states; None where it lacks MemAvailable or MemTotal."""
|
||||
fields = dict(re.findall(r"^(MemAvailable|MemTotal):\s+(\d+) kB$", meminfo, re.MULTILINE))
|
||||
if len(fields) != 2:
|
||||
return None
|
||||
return Memory(available=int(fields["MemAvailable"]), total=int(fields["MemTotal"]))
|
||||
|
||||
|
||||
def read_memory(meminfo: pathlib.Path | None = None) -> Memory | None:
|
||||
"""The machine's memory, read from meminfo or else MEMINFO; None where it cannot be read, as off Linux."""
|
||||
try:
|
||||
return parsed((meminfo or MEMINFO).read_text())
|
||||
except OSError:
|
||||
return None
|
||||
@@ -0,0 +1,51 @@
|
||||
"""The machine's heavy slots: one per 4 CPUs, and at least one, each a file locked with flock that every session on the machine shares."""
|
||||
import fcntl
|
||||
import os
|
||||
import pathlib
|
||||
import time
|
||||
import typing
|
||||
|
||||
CPUS_PER_SLOT = 4
|
||||
# Seconds between tries while every slot is held; a slot frees as its command exits.
|
||||
POLL_SECONDS = 1
|
||||
|
||||
|
||||
def usable_cpus() -> int | None:
|
||||
"""The CPUs this process may run on, which an affinity mask can make fewer than the machine's; None where the count is unknown."""
|
||||
return len(os.sched_getaffinity(0)) if hasattr(os, "sched_getaffinity") else os.cpu_count()
|
||||
|
||||
|
||||
def slot_count(cpus: int | None) -> int:
|
||||
return max(1, (cpus or 0) // CPUS_PER_SLOT)
|
||||
|
||||
|
||||
def slot_folder(env: typing.Mapping[str, str]) -> pathlib.Path:
|
||||
state = env.get("XDG_STATE_HOME") or str(pathlib.Path.home() / ".local" / "state")
|
||||
return pathlib.Path(state) / "run-heavy"
|
||||
|
||||
|
||||
def taken_slot(folder: pathlib.Path, slots: int) -> tuple[int, int] | None:
|
||||
"""The number and open file of a slot this call locked; None while every slot is held. Raises OSError where a slot file cannot be opened or locked."""
|
||||
for slot in range(slots):
|
||||
fd = os.open(folder / f"slot-{slot}", os.O_RDWR | os.O_CREAT, 0o644)
|
||||
try:
|
||||
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except BlockingIOError:
|
||||
os.close(fd)
|
||||
continue
|
||||
except OSError:
|
||||
os.close(fd)
|
||||
raise
|
||||
return slot, fd
|
||||
return None
|
||||
|
||||
|
||||
def waited_slot(folder: pathlib.Path, slots: int, say: typing.Callable[[], None], sleep: typing.Callable[[float], None] = time.sleep) -> tuple[int, int]:
|
||||
"""The number and open file of a slot this call locked, once one frees. While every slot is held, it calls say once and tries again each POLL_SECONDS."""
|
||||
said = False
|
||||
while (taken := taken_slot(folder, slots)) is None:
|
||||
if not said:
|
||||
say()
|
||||
said = True
|
||||
sleep(POLL_SECONDS)
|
||||
return taken
|
||||
@@ -0,0 +1,91 @@
|
||||
import errno
|
||||
import fcntl
|
||||
import os
|
||||
import pathlib
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
import unittest.mock
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from machine_load import memory
|
||||
from machine_load.slots import slot_count
|
||||
from machine_load import slots
|
||||
|
||||
|
||||
class SlotCount(unittest.TestCase):
|
||||
def test_one_slot_per_four_cpus_and_never_none(self):
|
||||
for cpus, slots in ((16, 4), (8, 2), (7, 1), (4, 1), (1, 1), (None, 1)):
|
||||
self.assertEqual(slot_count(cpus), slots, cpus)
|
||||
|
||||
|
||||
class MemoryShare(unittest.TestCase):
|
||||
def test_has_room_from_a_quarter_of_memory_available(self):
|
||||
self.assertFalse(memory.Memory(available=3, total=16).has_room())
|
||||
self.assertTrue(memory.Memory(available=4, total=16).has_room())
|
||||
|
||||
def test_reads_available_and_total_memory_from_meminfo(self):
|
||||
meminfo = "MemTotal: 16387072 kB\nMemFree: 981236 kB\nMemAvailable: 4096000 kB\n"
|
||||
self.assertEqual(memory.parsed(meminfo), memory.Memory(available=4096000, total=16387072))
|
||||
for unread in ("MemTotal: 16 kB\n", "MemTotal: x kB\nMemAvailable: 1 kB\n", ""):
|
||||
self.assertIsNone(memory.parsed(unread), unread)
|
||||
|
||||
def test_reads_a_meminfo_file_and_none_where_it_cannot(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
meminfo = pathlib.Path(temp, "meminfo")
|
||||
meminfo.write_text("MemTotal: 8 kB\nMemAvailable: 2 kB\n")
|
||||
self.assertEqual(memory.read_memory(meminfo), memory.Memory(available=2, total=8))
|
||||
self.assertIsNone(memory.read_memory(pathlib.Path(temp, "gone")))
|
||||
|
||||
|
||||
class SlotShare(unittest.TestCase):
|
||||
def test_splits_the_three_quarters_a_worker_leaves_evenly_across_the_slots_in_mib(self):
|
||||
self.assertEqual(memory.Memory(available=0, total=32 * 1024 * 1024).slot_share(4), 6144)
|
||||
self.assertEqual(memory.Memory(available=0, total=8000000).slot_share(2), 2929)
|
||||
|
||||
|
||||
class SlotFolder(unittest.TestCase):
|
||||
def test_every_session_shares_the_slots_under_the_users_state_folder(self):
|
||||
self.assertEqual(slots.slot_folder({}), pathlib.Path.home() / ".local" / "state" / "run-heavy")
|
||||
self.assertEqual(slots.slot_folder({"XDG_STATE_HOME": "/s"}), pathlib.Path("/s/run-heavy"))
|
||||
|
||||
|
||||
class TakenSlot(unittest.TestCase):
|
||||
def test_a_lock_that_fails_for_another_reason_than_a_holder_closes_its_file_and_raises(self):
|
||||
closed = []
|
||||
with tempfile.TemporaryDirectory() as folder, unittest.mock.patch("fcntl.flock", side_effect=OSError(errno.ENOLCK, "No locks available")), unittest.mock.patch("os.close", side_effect=closed.append):
|
||||
with self.assertRaises(OSError):
|
||||
slots.taken_slot(pathlib.Path(folder), 2)
|
||||
self.assertEqual(len(closed), 1)
|
||||
self.assertIsInstance(closed[0], int)
|
||||
os.close(closed[0])
|
||||
|
||||
|
||||
class WaitedSlot(unittest.TestCase):
|
||||
def test_waits_while_every_slot_is_held_saying_so_once_then_takes_the_freed_one(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
held = [open(pathlib.Path(folder, f"slot-{slot}"), "a") for slot in range(2)]
|
||||
for file in held:
|
||||
fcntl.flock(file, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
said, slept = [], []
|
||||
|
||||
def sleep(seconds):
|
||||
slept.append(seconds)
|
||||
if len(slept) == 2:
|
||||
held[1].close()
|
||||
|
||||
slot, fd = slots.waited_slot(pathlib.Path(folder), 2, lambda: said.append(True), sleep)
|
||||
os.close(fd)
|
||||
held[0].close()
|
||||
self.assertEqual((slot, said, slept), (1, [True], [slots.POLL_SECONDS] * 2))
|
||||
|
||||
def test_takes_a_free_slot_at_once(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
slot, fd = slots.waited_slot(pathlib.Path(folder), 2, lambda: self.fail("said it waits"), lambda seconds: self.fail("slept"))
|
||||
os.close(fd)
|
||||
self.assertEqual(slot, 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
+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")))
|
||||
|
||||
+24
-10
@@ -3,10 +3,12 @@ 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: a reviewer, a comprehension seat or the security pass.
|
||||
ReviewKind = typing.Literal["reviewer", "seat", "security"]
|
||||
# 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)
|
||||
@@ -34,7 +36,7 @@ class Rung:
|
||||
return Rung(model, effort)
|
||||
return Rung(family.model, effort) if effort else family
|
||||
|
||||
# The one spelling of a rung. It is persisted, so changing it routes every stored chunk afresh: parse no longer reads their rungs.
|
||||
# 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
|
||||
|
||||
@@ -60,9 +62,11 @@ LADDER = (
|
||||
Rung("claude-fable-5-1", "max"),
|
||||
)
|
||||
# The rungs a task's L steps its worker from the project's rung.
|
||||
WORKER_STEPS = {1: -2, 2: -1, 3: 0, 4: 1}
|
||||
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:
|
||||
@@ -96,14 +100,24 @@ def stepped_up(rung: Rung) -> Rung:
|
||||
|
||||
|
||||
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. The reviewers run on the higher of the worker's rung and review_floor's."""
|
||||
reviewers = highest(worker, review_floor(project, escape_and_impact))
|
||||
return {kind: review_rung(kind, project, reviewers) for kind in typing.get_args(ReviewKind)}
|
||||
"""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 review_rung(kind: ReviewKind, project: Rung, reviewers: Rung) -> Rung:
|
||||
"""The rung a review of kind runs on: a reviewer on the reviewers' rung; a seat or the security pass on the project's, so the seats score every chunk on one rung, and the security pass spends no more than the project chose."""
|
||||
return reviewers if kind == "reviewer" else project
|
||||
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:
|
||||
|
||||
@@ -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)
|
||||
+42
-30
@@ -1,5 +1,6 @@
|
||||
"""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
|
||||
|
||||
@@ -8,17 +9,10 @@ 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"
|
||||
# An archived worker line: the rung, then the item and the levels that routed it, if any, then the E + I taken in, if any. A line an older loop-claude wrote names an R + C in place of L and E + I: archived_worker reads only its rung, for the routing figures; with no levels, route_from returns None and the chunk routes afresh.
|
||||
ROUTED = 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]+))?")
|
||||
|
||||
|
||||
class ArchivedWorker(typing.NamedTuple):
|
||||
"""What an archived worker line names: the worker's rung, the item that routed it, its L and E + I, and the E + I taken in; 0 for each it does not name."""
|
||||
rung: Rung
|
||||
item: int
|
||||
likelihood: int
|
||||
escape_and_impact: int
|
||||
escape_and_impact_taken_in: int
|
||||
# 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"]
|
||||
@@ -46,6 +40,7 @@ class Route:
|
||||
|
||||
unfinished counts the unfinished verdicts towards the next one-rung step; a reload hands it over with the rung.
|
||||
"""
|
||||
# Each field below but rung and unfinished is a key of the archive's worker lines, so renaming one makes the lines already archived unreadable, and their chunks route afresh.
|
||||
# The fields a loop-claude from before L and E + I replaced R + C hands on reload; the reloaded script drops such a route, and the chunk routes afresh.
|
||||
RETIRED: typing.ClassVar[frozenset[str]] = frozenset({"risk_and_complexity"})
|
||||
rung: Rung
|
||||
@@ -55,15 +50,17 @@ class Route:
|
||||
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 __post_init__(self) -> None:
|
||||
# Raises on a programming error only, so nothing catches it: route_from and the reload decoder check levels_fit before they build a route.
|
||||
# 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, as the reload decoder asks of a handed one."""
|
||||
"""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":
|
||||
@@ -74,25 +71,40 @@ class Route:
|
||||
"""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 __str__(self) -> str:
|
||||
"""What the archive records as each verdict's worker; ROUTED reads it back."""
|
||||
routed = f", routed by item {self.item}'s L of {self.likelihood} and E + I of {self.escape_and_impact}" if self.item else ""
|
||||
taken_in = f", taking in an E + I of {self.escape_and_impact_taken_in}" if self.escape_and_impact_taken_in else ""
|
||||
return f"{self.rung}{routed}{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}))
|
||||
|
||||
|
||||
def archived_worker(worker: str) -> ArchivedWorker | None:
|
||||
"""What an archived worker line names; None for a model run off the ladder."""
|
||||
found = ROUTED.fullmatch(worker)
|
||||
rung = Rung.parse(found["rung"]) if found else None
|
||||
if not (found and rung):
|
||||
return None
|
||||
return ArchivedWorker(rung, *(int(found[name] or 0) for name in ("item", "likelihood", "escape_and_impact", "escape_and_impact_taken_in")))
|
||||
# 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, or a route by anything but levels on their scales."""
|
||||
archived = archived_worker(worker)
|
||||
if archived is None or not levels_fit(archived.item, archived.likelihood, archived.escape_and_impact, archived.escape_and_impact_taken_in):
|
||||
"""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(archived.rung, archived.item, archived.likelihood, archived.escape_and_impact, escape_and_impact_taken_in=archived.escape_and_impact_taken_in)
|
||||
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,11 +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 highest, LADDER, lowest_worker_rung, planning_rung, project_rung, review_floor, review_rung, review_rungs, Rung, stepped_up, worker_rung, WORKER_STEPS
|
||||
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")
|
||||
|
||||
@@ -25,7 +28,7 @@ class Ladder(unittest.TestCase):
|
||||
|
||||
def test_steps_a_workers_rung_by_its_l_from_the_projects_rung(self):
|
||||
position = LADDER.index(OPUS)
|
||||
self.assertEqual([LADDER.index(worker_rung(OPUS, likelihood)) - position for likelihood in range(1, 5)], [-2, -1, 0, 1])
|
||||
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)
|
||||
@@ -33,8 +36,8 @@ class Ladder(unittest.TestCase):
|
||||
self.assertEqual(review_floor(OPUS, 0), OPUS)
|
||||
|
||||
def test_a_step_past_either_end_stops_there(self):
|
||||
self.assertEqual(worker_rung(OPUS, 1), Rung("claude-haiku-5-5", "max"))
|
||||
self.assertEqual(worker_rung(LADDER[1], 1), 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"))
|
||||
@@ -43,7 +46,7 @@ class Ladder(unittest.TestCase):
|
||||
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-haiku-5-5", "max"))
|
||||
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)
|
||||
@@ -94,20 +97,32 @@ class Ladder(unittest.TestCase):
|
||||
|
||||
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)["reviewer"], OPUS)
|
||||
self.assertEqual(review_rungs(OPUS, haiku, 5)["reviewer"], Rung("claude-opus-5-5", "high"))
|
||||
self.assertEqual(review_rungs(OPUS, fable, 5)["reviewer"], fable)
|
||||
self.assertEqual(review_rungs(OPUS, Rung("claude-opus-5-5", "high"), 7)["reviewer"], Rung("claude-opus-5-5", "max"))
|
||||
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), {"reviewer": LADDER[-1], "seat": OPUS, "security": OPUS})
|
||||
self.assertEqual(review_rungs(OPUS, LADDER[-1], 8), {**dict.fromkeys(REVIEWERS, LADDER[-1]), "seat": OPUS, "security": OPUS})
|
||||
|
||||
def test_holds_a_reviewer_to_the_reviewers_rung_and_anything_else_to_the_projects(self):
|
||||
fable = LADDER[-1]
|
||||
self.assertEqual(review_rung("reviewer", OPUS, fable), fable)
|
||||
for kind in ("seat", "security"):
|
||||
with self.subTest(kind=kind):
|
||||
self.assertEqual(review_rung(kind, OPUS, fable), 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, {})
|
||||
@@ -9,20 +9,22 @@ class Environment(unittest.TestCase):
|
||||
PROJECT = Rung("claude-opus-5-5", "medium")
|
||||
WORKER = Rung("claude-haiku-5-5", "max")
|
||||
|
||||
def test_the_project_the_worker_and_the_reviewers_rungs_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_REVIEWER_RUNG": "claude-opus-5-5 at high effort"})
|
||||
self.assertEqual(environment(self.PROJECT, Route(self.WORKER))["LOOP_CLAUDE_REVIEWER_RUNG"], "claude-opus-5-5 at medium effort")
|
||||
self.assertEqual(environment(self.PROJECT, Route(Rung("claude-opus-5-5", "xhigh"), 3, 4, 2))["LOOP_CLAUDE_REVIEWER_RUNG"], "claude-opus-5-5 at xhigh effort")
|
||||
self.assertEqual(environment(self.PROJECT, Route(self.WORKER, 3, 1, 5, escape_and_impact_taken_in=6))["LOOP_CLAUDE_REVIEWER_RUNG"], "claude-opus-5-5 at xhigh effort")
|
||||
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_empty_rungs_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_REVIEWER_RUNG": ""})
|
||||
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, Rung("claude-opus-5-5", "high")))
|
||||
self.assertEqual(handed(environment(None, Route(self.WORKER))), (None, self.WORKER, None))
|
||||
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(self):
|
||||
self.assertEqual(handed({}), (None, None, None))
|
||||
self.assertEqual(handed({"LOOP_CLAUDE_WORKER_RUNG": "claude-haiku-5-5 bogus"}), (None, None, None))
|
||||
self.assertEqual(handed({"LOOP_CLAUDE_WORKER_RUNG": "claude-haiku-5-5 at bogus effort"}), (None, None, None))
|
||||
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)
|
||||
|
||||
@@ -1,25 +1,26 @@
|
||||
"""The rungs loop-claude hands a worker's claude in its environment, so rule-hook holds each review launch to them: docs/decisions.md → `routing:`.
|
||||
"""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, review_rungs, Rung
|
||||
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"
|
||||
REVIEWER_RUNG = "LOOP_CLAUDE_REVIEWER_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 empty project and reviewer rungs, so none is inherited from the environment."""
|
||||
reviewers = review_rungs(project, route.rung, route.reviewed_on())["reviewer"] if project else None
|
||||
return {PROJECT_RUNG: str(project) if project else "", WORKER_RUNG: str(route.rung), REVIEWER_RUNG: str(reviewers) if reviewers else ""}
|
||||
"""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, Rung | None]:
|
||||
"""The project's, the worker's and the reviewers' rungs, each None when unset or not on the ladder."""
|
||||
return on_the_ladder(environ.get(PROJECT_RUNG)), on_the_ladder(environ.get(WORKER_RUNG)), on_the_ladder(environ.get(REVIEWER_RUNG))
|
||||
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:
|
||||
|
||||
+124
-60
@@ -1,15 +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. 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.
|
||||
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:
|
||||
|
||||
@@ -37,10 +37,17 @@ A valid todo.md; ## Details and each item's detail are optional:
|
||||
|
||||
- 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 L, E and I are levels that ~/.claude/rules/todo-items.md defines: L from 1 to 4, E from 1
|
||||
@@ -64,24 +71,39 @@ A valid todo.md; ## Details and each item's detail are optional:
|
||||
- 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, DETAILS, HEADER_START, Item, item_details, items_table, MOVES, OLD_SHAPE, parse_row, risk, Shape, 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 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)
|
||||
@@ -99,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]
|
||||
|
||||
|
||||
@@ -109,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]
|
||||
|
||||
|
||||
@@ -126,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]:
|
||||
@@ -165,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:
|
||||
@@ -179,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:
|
||||
@@ -187,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)
|
||||
@@ -201,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
|
||||
@@ -229,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
|
||||
|
||||
|
||||
@@ -261,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))
|
||||
@@ -274,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:
|
||||
@@ -359,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:
|
||||
@@ -388,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))
|
||||
@@ -425,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"}
|
||||
|
||||
@@ -555,25 +608,36 @@ 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
|
||||
for goal, _ in item.moves:
|
||||
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")
|
||||
# R is written here, as the Score is, so --check finds a stale one, and a reader keeps the R the table stored.
|
||||
return dataclasses.replace(item, scores=item.scores | {"R": risk(item.scores["L"], item.scores["E"], item.scores["I"])})
|
||||
|
||||
|
||||
def cited_goals_failure(item: Item, scoring: Scoring) -> Failure | None:
|
||||
"""Why the item may not name one of the goals it names, such as one README.md voids or does not number; None when it may name each. todo_table's parse_moves holds the rules a Moves cell keeps on its own."""
|
||||
if scoring.shape is OLD_SHAPE:
|
||||
unknown = [goal for goal, _ in item.moves if goal not in scoring.weights]
|
||||
return Failure(f"item {item.id} cites goal {', '.join(unknown)}, which the goal weights do not list") if unknown else None
|
||||
for goal, _ in item.moves:
|
||||
if goal == CODE_HEALTH and goal not in scoring.goals:
|
||||
return Failure(f"item {item.id} names {CODE_HEALTH}, which README.md voids; drop it from the item's {MOVES}, or the void from README.md")
|
||||
if goal not in scoring.goals:
|
||||
return Failure(f"item {item.id} cites goal {goal}, which README.md's ## Goals does not number")
|
||||
if scoring.goals[goal] == "Maintain" and item.exempt != "defect":
|
||||
return Failure(f"item {item.id} cites goal {goal}, a maintain goal, which only a defect that restores it may name; name the achieve goals the item moves")
|
||||
return None
|
||||
|
||||
|
||||
def render_item(item: Item, value: float, shape: Shape, columns: tuple[str, ...]) -> str:
|
||||
"""The item's row, each cell under its column."""
|
||||
written = {"ID": str(item.id), "Release": release_name(item), 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}"}
|
||||
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) + " |"
|
||||
|
||||
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
import pathlib
|
||||
|
||||
# The checkout root.
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[2]
|
||||
|
||||
@@ -7,7 +7,7 @@ import unittest
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from loop_claude.project.records import HUMAN_RULE_DIRS
|
||||
from repo_checks.test_python_floor import ROOT
|
||||
from repo_checks import ROOT
|
||||
|
||||
RULE_PATH = rf"(?:{'|'.join(map(re.escape, HUMAN_RULE_DIRS))})/[\w-]+\.md"
|
||||
CITATION = re.compile(rf'`?(?:~/\.claude/)?(CLAUDE\.md|{RULE_PATH})`? → ("[^"]+"(?:,? (?:and )?"[^"]+")*)')
|
||||
|
||||
@@ -5,7 +5,7 @@ import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from repo_checks.test_python_floor import ROOT
|
||||
from repo_checks import ROOT
|
||||
|
||||
PRIVATE = [
|
||||
".claude/settings.local.json",
|
||||
@@ -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)
|
||||
|
||||
@@ -6,7 +6,7 @@ import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from repo_checks.test_python_floor import ROOT
|
||||
from repo_checks import ROOT
|
||||
|
||||
|
||||
def bound(node: ast.Import | ast.ImportFrom) -> list[str]:
|
||||
|
||||
@@ -5,7 +5,7 @@ import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from repo_checks.test_python_floor import ROOT
|
||||
from repo_checks import ROOT
|
||||
|
||||
|
||||
class Install(unittest.TestCase):
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
import pathlib
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[2]
|
||||
FLOOR = re.compile(r"Python 3\.(\d+) or newer")
|
||||
|
||||
|
||||
def readme_floor() -> tuple[int, int] | None:
|
||||
named = FLOOR.search((ROOT / "README.md").read_text(encoding="utf-8"))
|
||||
return (3, int(named.group(1))) if named else None
|
||||
|
||||
|
||||
class PythonFloor(unittest.TestCase):
|
||||
def test_the_suite_passes_on_the_python_the_readme_names_as_floor(self):
|
||||
floor = readme_floor()
|
||||
self.assertIsNotNone(floor, "README.md's Install names `Python 3.N or newer`")
|
||||
if sys.version_info[:2] == floor:
|
||||
self.skipTest("this run is on the floor")
|
||||
if shutil.which("uv") is None:
|
||||
self.fail("uv on PATH fetches the floor interpreter; see README.md's Test line")
|
||||
suite = ["python", "-m", "unittest", "discover", "-s", "bin", "-p", "test_*.py"]
|
||||
ran = subprocess.run(["uv", "run", "--no-project", "--python", "%d.%d" % floor, *suite], capture_output=True, cwd=ROOT, text=True)
|
||||
self.assertEqual(ran.returncode, 0, ran.stderr)
|
||||
@@ -0,0 +1,16 @@
|
||||
import pathlib
|
||||
import re
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from machine_load.slots import CPUS_PER_SLOT
|
||||
from repo_checks import ROOT
|
||||
|
||||
|
||||
class TestLine(unittest.TestCase):
|
||||
def test_the_readme_runs_the_tests_in_one_heavy_slots_cpus(self):
|
||||
workers = re.search(r"pytest==\S+ -n (\d+) bin`", (ROOT / "README.md").read_text(encoding="utf-8"))
|
||||
self.assertIsNotNone(workers, "README.md's Test line runs `pytest==X -n N bin`")
|
||||
self.assertEqual(int(workers.group(1)), CPUS_PER_SLOT)
|
||||
@@ -5,20 +5,25 @@ import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from rule_hook.reviewer_rung import REVIEWERS, SEAT, SECURITY_OPENER
|
||||
from repo_checks.test_python_floor import ROOT
|
||||
from review_passes import PASS_AGENTS, PASSES
|
||||
from repo_checks import ROOT
|
||||
from rule_hook.reviewer_rung import SEAT, SECURITY_OPENER
|
||||
|
||||
OPENING = re.compile(r"^## Opening\n+```\n([^\n]+?\.)(?: |\n)", re.MULTILINE)
|
||||
REVIEWER_NAME = re.compile(r"\b[a-z]+(?:-[a-z]+)*-(?:reviewer|architect|auditor)\b")
|
||||
# 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; these fail when what it recognises drifts from what the skills launch."""
|
||||
"""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_reviewers_are_the_ones_larv_review_s_pass_table_names(self):
|
||||
passes = LARV_REVIEW.split("## 3. Passes", 1)[1].split("A comment is prose", 1)[0]
|
||||
self.assertEqual(set(REVIEWER_NAME.findall(passes)), REVIEWERS)
|
||||
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"))
|
||||
@@ -28,3 +33,6 @@ class ReviewerLaunches(unittest.TestCase):
|
||||
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 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"))
|
||||
@@ -1,4 +1,5 @@
|
||||
import pathlib
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
@@ -6,14 +7,28 @@ import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from repo_checks.test_python_floor import readme_floor, ROOT
|
||||
from repo_checks import ROOT
|
||||
|
||||
SUPPORTED = re.compile(r"the latest stable Python, today (3\.\d+)")
|
||||
|
||||
|
||||
def tools() -> list[str]:
|
||||
"""mypy's arguments naming every package and module under bin/ except `repo_checks`, so a new tool is checked without being listed."""
|
||||
bin_folder = ROOT / "bin"
|
||||
packages = sorted(init.parent.name for init in bin_folder.glob("*/__init__.py") if init.parent.name != "repo_checks")
|
||||
modules = sorted(path.stem for path in bin_folder.glob("*.py") if not path.name.startswith("test_"))
|
||||
return [*(word for package in packages for word in ("-p", package)), *(word for module in modules for word in ("-m", module))]
|
||||
|
||||
|
||||
class Types(unittest.TestCase):
|
||||
def test_mypy_passes_on_the_tools_at_the_floor(self):
|
||||
floor = readme_floor()
|
||||
self.assertIsNotNone(floor, "README.md's Install names `Python 3.N or newer`")
|
||||
def test_mypy_passes_on_the_tools_for_the_python_readme_install_names(self):
|
||||
supported = SUPPORTED.search((ROOT / "README.md").read_text(encoding="utf-8"))
|
||||
self.assertIsNotNone(supported, "README.md's Install names `the latest stable Python, today 3.N`")
|
||||
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", "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", "-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", sys.executable, "mypy==2.3.1", "--python-version", supported.group(1), "--cache-dir=/dev/null", "--check-untyped-defs", "--disallow-untyped-defs", "--exclude", "/test_", *tools()], capture_output=True, cwd=ROOT / "bin", text=True)
|
||||
self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr)
|
||||
|
||||
def test_mypy_checks_run_heavy_and_each_root_module(self):
|
||||
self.assertLessEqual({("-p", "run_heavy"), ("-p", "machine_load"), ("-m", "chunk_pick"), ("-m", "docker_command")}, set(zip(tools()[::2], tools()[1::2])))
|
||||
self.assertNotIn("repo_checks", tools())
|
||||
|
||||
@@ -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 runs no lower than 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-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-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, memory=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__":
|
||||
+41
-13
@@ -1,11 +1,22 @@
|
||||
"""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."""
|
||||
"""The titles of larv-review's round commits, `Answer <pass> round <n>: <k> 🔴, <m> 🟡 (<j> misread); <summary>`: each pass's round count, and the findings the rounds reported. <j> counts the 🔴 and 🟡 findings a reviewer marked `[misread]`."""
|
||||
import dataclasses
|
||||
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", "principles", "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]+) 🟡(?:;|$)")
|
||||
# What follows a round title's colon: the round's 🔴 and 🟡 counts, then how many of them a reviewer marked `[misread]`, a count that titles from before it lack, then `;` and its summary, if any.
|
||||
FINDINGS = re.compile(r" ([0-9]+) 🔴, ([0-9]+) 🟡(?: \(([0-9]+) misread\))?(?:;|$)")
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Findings:
|
||||
"""A round title's findings: its 🔴 and 🟡 counts, and how many of them a reviewer marked `[misread]`, None for a title from before that count."""
|
||||
red: int
|
||||
yellow: int
|
||||
misread: int | None
|
||||
|
||||
|
||||
def round_counts(titles: list[str]) -> dict[str, int]:
|
||||
@@ -21,18 +32,35 @@ def round_counts(titles: list[str]) -> dict[str, int]:
|
||||
|
||||
|
||||
def lacks_counts(title: str) -> bool:
|
||||
"""Whether title is a round title without the counts after its colon."""
|
||||
"""Whether title is a round title without all three counts after its colon, or with more misread findings than 🔴 and 🟡 findings."""
|
||||
return ROUND.match(title) is not None and ((counts := title_counts(title)) is None or counts.misread is None)
|
||||
|
||||
|
||||
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 not FINDINGS.match(title, named.end())
|
||||
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."""
|
||||
def title_counts(title: str) -> Findings | None:
|
||||
"""The counts after a round title's colon; None where title is no round title, lacks the 🔴 and 🟡 counts, or counts more misread findings than both."""
|
||||
named = ROUND.match(title)
|
||||
found = FINDINGS.match(title, named.end()) if named else None
|
||||
if not found:
|
||||
return None
|
||||
counts = Findings(int(found.group(1)), int(found.group(2)), None if found.group(3) is None else int(found.group(3)))
|
||||
return None if counts.misread is not None and counts.misread > counts.red + counts.yellow else counts
|
||||
|
||||
|
||||
def round_findings(titles: list[str]) -> Findings | None:
|
||||
"""The counts summed over the round titles among titles; None where a round title lacks the 🔴 and 🟡 counts, or no title is a round. Its misread is None where a round title lacks that count."""
|
||||
counts = []
|
||||
for title in titles:
|
||||
if named := ROUND.match(title):
|
||||
found = FINDINGS.match(title, named.end())
|
||||
if not found:
|
||||
if ROUND.match(title):
|
||||
if (found := title_counts(title)) is None:
|
||||
return None
|
||||
counts.append((int(found.group(1)), int(found.group(2))))
|
||||
return (sum(red for red, _ in counts), sum(yellow for _, yellow in counts)) if counts else None
|
||||
counts.append(found)
|
||||
if not counts:
|
||||
return None
|
||||
misreads = [found.misread for found in counts if found.misread is not None]
|
||||
return Findings(sum(found.red for found in counts), sum(found.yellow for found in counts), sum(misreads) if len(misreads) == len(counts) else None)
|
||||
|
||||
@@ -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,13 +1,14 @@
|
||||
"""Token spend and routing outcomes of the chunks loop-claude finished, and the routing changes they call for: docs/decisions.md → `routing:`."""
|
||||
"""Dollar 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
|
||||
import statistics
|
||||
import typing
|
||||
|
||||
from model_routing.route import archived_worker, ESCALATION_MARKER
|
||||
from claude_code.entries import assistant_parts, parts, tool_call, usage_count
|
||||
from claude_code.entries import assistant_parts, parts, tool_call, tool_result
|
||||
from git_command import commits
|
||||
from model_routing.route import ESCALATION_MARKER, route_from
|
||||
from routing_figures.prices import listed
|
||||
from model_routing.ladder import position, Rung
|
||||
from round_titles import round_counts
|
||||
from shell_command import simple_commands
|
||||
@@ -18,6 +19,8 @@ MEASURED_AT = re.compile(r"^Measured .+, at cycle ([0-9]+) across", re.MULTILINE
|
||||
# A rung or a subagent type is compared only once this many of its chunks or subagents are measured, so a single odd chunk calls for no change.
|
||||
MEASURED_AT_LEAST = 5
|
||||
DIMENSIONS = ("project", "subagent type", "rung", "tool")
|
||||
# Each of DIMENSIONS to its labels' dollars.
|
||||
Dollars = dict[str, collections.defaultdict[str, float]]
|
||||
# The tool label of a message that follows no tool call, such as the first message after a prompt.
|
||||
PROMPT = "prompt"
|
||||
ESCALATION = re.compile(rf"{ESCALATION_MARKER} ([0-9]+):")
|
||||
@@ -53,32 +56,50 @@ class Reports:
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class ChunkFigures:
|
||||
"""tokens maps each of DIMENSIONS to its labels' tokens; start is the rung a routed chunk started on, None where no item routed it; escalated counts the worker's escalations by trigger."""
|
||||
tokens: dict[str, collections.Counter[str]]
|
||||
"""dollars maps each of DIMENSIONS to its labels' dollars; start is the rung a routed chunk started on, None where no item routed it; escalated counts the worker's escalations by trigger; unattributed is the recorded cost of a model with no priced message in the chunk; lacking counts the Agent calls, the worker's and the subagents', that have no subagent transcript in the archive."""
|
||||
dollars: Dollars
|
||||
start: Rung | None
|
||||
rounds_past_first: int
|
||||
unfinished: int
|
||||
delegated: collections.Counter[str]
|
||||
reports: dict[str, Reports]
|
||||
escalated: collections.Counter[int]
|
||||
unattributed: float
|
||||
lacking: int = 0
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Figures:
|
||||
"""escalated counts every chunk's escalations by trigger, routed or not; skipped names each chunk folder the archive could not read whole."""
|
||||
chunks: int
|
||||
tokens: dict[str, collections.Counter[str]]
|
||||
dollars: Dollars
|
||||
routed: dict[Rung, list[ChunkFigures]]
|
||||
reports: dict[str, Reports]
|
||||
escalated: collections.Counter[int]
|
||||
skipped: tuple[str, ...] = ()
|
||||
unattributed: float = 0.0
|
||||
lacking: int = 0
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Message:
|
||||
"""An assistant message, counted once: when it was written, the tools whose results it took in, the model that wrote it and what its usage costs at list prices."""
|
||||
at: str
|
||||
tools: list[str]
|
||||
model: str
|
||||
list_price: float
|
||||
|
||||
|
||||
class Spent(typing.NamedTuple):
|
||||
"""A message with the subagent type that wrote it, or `worker`, and the rung it ran on."""
|
||||
kind: str
|
||||
rung: str
|
||||
message: Message
|
||||
|
||||
|
||||
def measured(chunk: Chunk, home: str) -> ChunkFigures:
|
||||
cycles = sorted((cycle for kept in chunk.outcomes for cycle in workers(kept)), key=lambda cycle: cycle[0])
|
||||
tokens: dict[str, collections.Counter[str]] = {dimension: collections.Counter() for dimension in DIMENSIONS}
|
||||
for at, tools, spent in spend(chunk.worker):
|
||||
add(tokens, chunk.project, "worker", str(rung_at(cycles, at)), tools, spent)
|
||||
spent = [Spent("worker", str(rung_at(cycles, message.at)), message) for message in messages(chunk.worker)]
|
||||
launches = agent_calls(chunk.worker)
|
||||
reported = results(chunk.worker)
|
||||
delegated: collections.Counter[str] = collections.Counter()
|
||||
@@ -89,17 +110,19 @@ def measured(chunk: Chunk, home: str) -> ChunkFigures:
|
||||
rung = str(subagent_rung(subagent.entries, arguments, rung_at(cycles, launched_at)))
|
||||
delegated[rung] += 1
|
||||
reports[kind] = reports.get(kind, Reports(0, 0, 0)) + Reports(1, len(reported.get(subagent.launched_by, "")), sum(map(len, results(subagent.entries).values())))
|
||||
for _, tools, spent in spend(subagent.entries):
|
||||
add(tokens, chunk.project, kind, rung, tools, spent)
|
||||
start = archived_worker(cycles[0][1]) if cycles else None
|
||||
spent += [Spent(kind, rung, message) for message in messages(subagent.entries)]
|
||||
dollars, unattributed = costed(spent, chunk.project, recorded_costs(chunk.worker))
|
||||
start = route_from(cycles[0][1]) if cycles else None
|
||||
return ChunkFigures(
|
||||
tokens=tokens,
|
||||
dollars=dollars,
|
||||
start=start.rung if start and start.item else None,
|
||||
rounds_past_first=rounds_past_first(chunk.worker, home),
|
||||
unfinished=sum(len(UNFINISHED_AT.findall(kept)) for kept in chunk.outcomes),
|
||||
delegated=delegated,
|
||||
reports=reports,
|
||||
escalated=escalations(launches),
|
||||
unattributed=unattributed,
|
||||
lacking=max(0, len(launches) + sum(len(agent_calls(subagent.entries)) for subagent in chunk.subagents) - len(chunk.subagents)),
|
||||
)
|
||||
|
||||
|
||||
@@ -120,21 +143,38 @@ def agent_calls(worker: list[dict]) -> dict[str, tuple[str, dict]]:
|
||||
return found
|
||||
|
||||
|
||||
def add(tokens: dict[str, collections.Counter[str]], project: str, kind: str, rung: str, tools: list[str], spent: int) -> None:
|
||||
tokens["project"][project] += spent
|
||||
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))
|
||||
# {"type": "cost-state", "totalCostUSD": 40.1, "modelUsage": {"claude-opus-5-5": {"costUSD": 40.1, "outputTokens": 334504, ...}}, ...}
|
||||
def recorded_costs(worker: list[dict]) -> dict[str, float]:
|
||||
"""The cost the worker transcript's last cost-state entry records for each model. Claude Code counts every call of the session in it, the subagents' and the compactions' too."""
|
||||
for entry in reversed(worker):
|
||||
if entry.get("type") == "cost-state" and isinstance(by_model := entry.get("modelUsage"), dict):
|
||||
return {model: cost for model, usage in by_model.items() if isinstance(usage, dict) and isinstance(cost := usage.get("costUSD"), (int, float))}
|
||||
return {}
|
||||
|
||||
|
||||
def costed(spent: list[Spent], project: str, recorded: dict[str, float]) -> tuple[Dollars, float]:
|
||||
"""Each message's dollars by DIMENSIONS, and the recorded cost left over, that of a recorded model with no priced message. A model's recorded cost is split across its messages in proportion to their list prices, so the calls no message records, such as compactions, are counted. A subagent transcript the archive lacks puts its cost on the archived messages of the model that ran it, in the same proportion. A model the record omits keeps its list prices."""
|
||||
listed_by_model: collections.defaultdict[str, float] = collections.defaultdict(float)
|
||||
for _, _, message in spent:
|
||||
listed_by_model[message.model] += message.list_price
|
||||
scale = {model: recorded[model] / total for model, total in listed_by_model.items() if total and model in recorded}
|
||||
dollars: Dollars = {dimension: collections.defaultdict(float) for dimension in DIMENSIONS}
|
||||
for kind, rung, message in spent:
|
||||
cost = message.list_price * scale.get(message.model, 1.0)
|
||||
dollars["project"][project] += cost
|
||||
dollars["subagent type"][kind] += cost
|
||||
dollars["rung"][rung] += cost
|
||||
for tool in message.tools:
|
||||
dollars["tool"][tool] += cost / len(message.tools)
|
||||
return dollars, sum(cost for model, cost in recorded.items() if not listed_by_model[model])
|
||||
|
||||
|
||||
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")
|
||||
archived = archived_worker(found)
|
||||
return archived.rung if archived else found
|
||||
route = route_from(found)
|
||||
return route.rung if route else found
|
||||
|
||||
|
||||
def subagent_rung(entries: list[dict], arguments: dict, worker: Rung | str) -> Rung:
|
||||
@@ -144,39 +184,27 @@ def subagent_rung(entries: list[dict], arguments: dict, worker: Rung | str) -> R
|
||||
return Rung(model, str(effort))
|
||||
|
||||
|
||||
def spend(entries: list[dict]) -> list[tuple[str, list[str], int]]:
|
||||
"""Each message's timestamp, the tools whose results it took in, and its input, cache-written and output tokens, counted once per message, as reading_cost's tokens_in dedupes them, though tokens_in leaves output tokens out."""
|
||||
messages: dict[str, tuple[str, object, list[str]]] = {}
|
||||
def messages(entries: list[dict]) -> list[Message]:
|
||||
"""The assistant messages, counted once each, each with the tools whose results it took in, or `prompt` where it took none in."""
|
||||
# Claude Code writes one entry per content block of a message, each with the message's usage. The usage is the same in every entry (none of 1,681 multi-entry messages in the archive of 2026-10-28 differed), so the first is kept, where reading_cost's tokens_in keeps the last.
|
||||
kept: dict[str, tuple[str, dict, list[str]]] = {}
|
||||
for entry in entries:
|
||||
if entry.get("type") != "assistant" or not isinstance(message := entry.get("message"), dict):
|
||||
continue
|
||||
key = str(message.get("id") or entry.get("uuid"))
|
||||
kept = messages.setdefault(key, (str(entry.get("timestamp", "")), message.get("usage"), []))
|
||||
kept[2].extend(name for part in assistant_parts(entry) if (found := tool_call(part)) and isinstance(name := found[0], str))
|
||||
spent = []
|
||||
found = kept.setdefault(str(message.get("id") or entry.get("uuid")), (str(entry.get("timestamp", "")), message, []))
|
||||
found[2].extend(name for part in assistant_parts(entry) if (call := tool_call(part)) and isinstance(name := call[0], str))
|
||||
counted = []
|
||||
before = [PROMPT]
|
||||
for at, usage, called in messages.values():
|
||||
tokens = sum(usage_count(usage, field) for field in ("input_tokens", "cache_creation_input_tokens", "output_tokens")) if isinstance(usage, dict) else 0
|
||||
spent.append((at, before, tokens))
|
||||
for at, message, called in kept.values():
|
||||
model = str(message.get("model") or "")
|
||||
counted.append(Message(at, before, model, listed(model, message.get("usage"))))
|
||||
before = called or [PROMPT]
|
||||
return spent
|
||||
return counted
|
||||
|
||||
|
||||
def results(entries: list[dict]) -> dict[str, str]:
|
||||
"""Each tool result's text by the id of the call it answers."""
|
||||
found = {}
|
||||
for entry in entries:
|
||||
for part in parts(entry):
|
||||
if isinstance(part, dict) and part.get("type") == "tool_result":
|
||||
found[str(part.get("tool_use_id"))] = result_text(part.get("content"))
|
||||
return found
|
||||
|
||||
|
||||
# {"type": "tool_result", "content": "hi"} or {"type": "tool_result", "content": [{"type": "text", "text": "hi"}]}
|
||||
def result_text(body: object) -> str:
|
||||
if isinstance(body, str):
|
||||
return body
|
||||
return "".join(block["text"] for block in body if isinstance(block, dict) and isinstance(block.get("text"), str)) if isinstance(body, list) else ""
|
||||
return {result.tool_use_id: result.text for entry in entries for part in parts(entry) if (result := tool_result(part))}
|
||||
|
||||
|
||||
def rounds_past_first(worker: list[dict], home: str) -> int:
|
||||
@@ -196,7 +224,11 @@ def due(cycle: int, last_measured: int) -> bool:
|
||||
|
||||
|
||||
def totals(chunks: list[ChunkFigures], skipped: tuple[str, ...] = ()) -> Figures:
|
||||
tokens = {dimension: sum((chunk.tokens.get(dimension, collections.Counter()) for chunk in chunks), collections.Counter()) for dimension in DIMENSIONS}
|
||||
dollars: Dollars = {dimension: collections.defaultdict(float) for dimension in DIMENSIONS}
|
||||
for chunk in chunks:
|
||||
for dimension in DIMENSIONS:
|
||||
for label, amount in chunk.dollars.get(dimension, {}).items():
|
||||
dollars[dimension][label] += amount
|
||||
routed: dict[Rung, list[ChunkFigures]] = {}
|
||||
reports: dict[str, Reports] = {}
|
||||
for chunk in chunks:
|
||||
@@ -204,7 +236,7 @@ def totals(chunks: list[ChunkFigures], skipped: tuple[str, ...] = ()) -> Figures
|
||||
routed.setdefault(chunk.start, []).append(chunk)
|
||||
for kind, found in chunk.reports.items():
|
||||
reports[kind] = reports.get(kind, Reports(0, 0, 0)) + found
|
||||
return Figures(len(chunks), tokens, routed, reports, summed(chunks, lambda chunk: chunk.escalated), skipped)
|
||||
return Figures(len(chunks), dollars, routed, reports, summed(chunks, lambda chunk: chunk.escalated), skipped, sum(chunk.unattributed for chunk in chunks), sum(chunk.lacking for chunk in chunks))
|
||||
|
||||
|
||||
def calls(figures: Figures) -> list[str]:
|
||||
@@ -224,14 +256,24 @@ def mean(chunks: list[ChunkFigures], of: typing.Callable[[ChunkFigures], int]) -
|
||||
return statistics.mean(map(of, chunks))
|
||||
|
||||
|
||||
def basis(figures: Figures) -> str:
|
||||
"""What the dollars are, what they leave out, and where the archive falls short of the recorded cost."""
|
||||
text = "Dollars are what each worker transcript's last `cost-state` entry records for each model, cache reads included. A model's dollars are split across its messages in the archive in proportion to their cost at list prices, so the cost of a compaction, or of a subagent transcript the archive lacks, lands on the archived messages of the model that ran it. A chunk without the entry, or a model it leaves out, keeps the list prices, which may be a little off. A message's dollars count towards the tools whose results it took in, split evenly; a message that took in no tool result counts towards `prompt`. The judge's runs are not archived, so their cost is not counted."
|
||||
if figures.unattributed:
|
||||
text += f" {money(figures.unattributed)} of the recorded cost is left out, since it belongs to a model with no list price or with no priced message in the archive."
|
||||
if figures.lacking:
|
||||
text += f" The archive holds no subagent transcript for {figures.lacking} of the chunks' Agent calls."
|
||||
return text
|
||||
|
||||
|
||||
def render(figures: Figures, found: list[str], at: str, cycle: int, since: str) -> str:
|
||||
"""The figures as markdown; MEASURED_AT reads the cycle back. since is the latest reset's stamp, empty for none."""
|
||||
sections = [
|
||||
"# Routing figures",
|
||||
f"Measured {at}, at cycle {cycle} across loop-claude's archive, from {figures.chunks} finished chunk{'' if figures.chunks == 1 else 's'}{f' that finished after the reset of {since}' if since else ''}. Tokens are input, cache-written and output tokens; cache reads are left out. A message's tokens count towards the tools whose results it took in, split evenly; a message that took in no tool result counts towards `prompt`.",
|
||||
f"Measured {at}, at cycle {cycle} across loop-claude's archive, from {figures.chunks} finished chunk{'' if figures.chunks == 1 else 's'}{f' that finished after the reset of {since}' if since else ''}. {basis(figures)}",
|
||||
"## Calls for a routing change",
|
||||
"".join(f"- {call}\n" for call in found).rstrip("\n") or "None.",
|
||||
*[part for dimension in DIMENSIONS for part in (f"## Tokens by {dimension}", table((dimension.capitalize(), "Tokens"), [(label, str(tokens)) for label, tokens in figures.tokens[dimension].most_common()]))],
|
||||
*[part for dimension in DIMENSIONS for part in (f"## Dollars by {dimension}", table((dimension.capitalize(), "Dollars"), [(label, money(dollars)) for label, dollars in sorted(figures.dollars[dimension].items(), key=lambda spent: -spent[1])]))],
|
||||
"## Routed chunks by the rung they started on",
|
||||
table(("Rung", "Chunks", "Review rounds past each pass's first, mean", "Unfinished verdicts, mean", "Subagent rungs", "Escalations by trigger"), [
|
||||
(str(rung), str(len(chunks)), f"{mean(chunks, lambda chunk: chunk.rounds_past_first):.1f}", f"{mean(chunks, lambda chunk: chunk.unfinished):.1f}", subagent_rungs(chunks), triggers(summed(chunks, lambda chunk: chunk.escalated)))
|
||||
@@ -260,6 +302,10 @@ def triggers(escalated: collections.Counter[int]) -> str:
|
||||
return ", ".join(f"trigger {trigger}: {times}" for trigger, times in sorted(escalated.items()))
|
||||
|
||||
|
||||
def money(dollars: float) -> str:
|
||||
return f"${dollars:,.2f}"
|
||||
|
||||
|
||||
def table(header: tuple[str, ...], rows: list[tuple[str, ...]]) -> str:
|
||||
if not rows:
|
||||
return "None."
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
"""What a message costs at list prices: the weights that split a chunk's recorded cost between its messages."""
|
||||
import dataclasses
|
||||
|
||||
from claude_code.entries import usage_count
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Price:
|
||||
"""Dollars per million tokens. A cache write costs 1.25 times the input for a five-minute cache and 2 times for an hour's, as Opus 5.5's $5 and $8 show."""
|
||||
input: float
|
||||
read: float
|
||||
output: float
|
||||
|
||||
@property
|
||||
def write_5m(self) -> float:
|
||||
return self.input * 1.25
|
||||
|
||||
@property
|
||||
def write_1h(self) -> float:
|
||||
return self.input * 2
|
||||
|
||||
|
||||
# Anthropic's list prices as the claude-api skill lists them (cached 2026-10-06), with Opus 5.5's cache prices from `docs/decisions.md` → `loop-claude: the worker's claude compacts…`. Haiku 5.5's cache read is assumed at a tenth of its input, and its dearer prompts above 200k tokens are left out. Where a chunk records its cost, only the proportions between one model's messages matter, so these may be a little off.
|
||||
PRICES = {
|
||||
"claude-fable-5-1": Price(10, 0.25, 50),
|
||||
"claude-haiku-5-5": Price(0.1, 0.01, 0.5),
|
||||
"claude-opus-5-5": Price(4, 0.2, 20),
|
||||
"claude-sonnet-5-5": Price(2, 0.2, 10),
|
||||
}
|
||||
|
||||
|
||||
# {"input_tokens": 2, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 25919}, "cache_read_input_tokens": 10365, "output_tokens": 193, ...}
|
||||
def listed(model: str, usage: object) -> float:
|
||||
"""The cost of one message's usage at the model's list price; 0 for a model without one."""
|
||||
price = PRICES.get(model)
|
||||
if not price or not isinstance(usage, dict):
|
||||
return 0.0
|
||||
written = usage.get("cache_creation")
|
||||
# A write without the split by lifetime counts as a five-minute one.
|
||||
five, hour = (usage_count(written, "ephemeral_5m_input_tokens"), usage_count(written, "ephemeral_1h_input_tokens")) if isinstance(written, dict) else (usage_count(usage, "cache_creation_input_tokens"), 0)
|
||||
return (
|
||||
usage_count(usage, "input_tokens") * price.input + five * price.write_5m + hour * price.write_1h
|
||||
+ usage_count(usage, "cache_read_input_tokens") * price.read + usage_count(usage, "output_tokens") * price.output
|
||||
) / 1_000_000
|
||||
@@ -1,5 +1,6 @@
|
||||
import collections
|
||||
import contextlib
|
||||
import dataclasses
|
||||
import io
|
||||
import json
|
||||
import pathlib
|
||||
@@ -15,14 +16,20 @@ 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 L of 3 and E + I of 4"
|
||||
LOW_ROUTE = Route(LOW, 7, 3, 4).worker_line()
|
||||
|
||||
|
||||
def message(id_, at, *parts, model="claude-opus-5-5", tokens=(1, 10, 100)):
|
||||
return {"type": "assistant", "timestamp": at, "cwd": "/c", "message": {"id": id_, "model": model, "content": list(parts), "usage": {"input_tokens": tokens[0], "cache_creation_input_tokens": tokens[1], "output_tokens": tokens[2], "cache_read_input_tokens": 5000}}}
|
||||
def message(id_, at, *parts, model="claude-opus-5-5", usage=None):
|
||||
"""Costs $2 on Opus 5.5, whose output is $20 per million tokens, and $1 on Sonnet 5.5, whose output is $10."""
|
||||
return {"type": "assistant", "timestamp": at, "cwd": "/c", "message": {"id": id_, "model": model, "content": list(parts), "usage": usage or {"output_tokens": 100_000}}}
|
||||
|
||||
|
||||
def cost_state(**costs):
|
||||
return {"type": "cost-state", "totalCostUSD": sum(costs.values()), "modelUsage": {model.replace("_", "-"): {"costUSD": cost} for model, cost in costs.items()}}
|
||||
|
||||
|
||||
def call(name, id_="t1", **arguments):
|
||||
@@ -38,23 +45,23 @@ def stamped(at, outcome):
|
||||
|
||||
|
||||
def figures(start=LOW, rounds=0, unfinished=0, reports=None, escalated=None):
|
||||
return ChunkFigures({}, start, rounds, unfinished, collections.Counter(), reports or {}, collections.Counter(escalated or {}))
|
||||
return ChunkFigures({}, start, rounds, unfinished, collections.Counter(), reports or {}, collections.Counter(escalated or {}), 0.0)
|
||||
|
||||
|
||||
class Measured(unittest.TestCase):
|
||||
def test_counts_each_messages_tokens_once_by_project_type_rung_and_the_tool_it_followed(self):
|
||||
def test_prices_each_message_once_by_project_type_rung_and_the_tool_it_followed(self):
|
||||
worker = [
|
||||
message("m1", "2026-10-14T10:00:00.100Z", {"type": "text", "text": "reading"}),
|
||||
message("m1", "2026-10-14T10:00:00.200Z", call("Read", file_path="/c/a")),
|
||||
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})
|
||||
self.assertEqual(found.tokens["rung"], {str(LOW): 222, str(HIGH): 111})
|
||||
self.assertEqual(found.tokens["tool"], {"prompt": 222, "Read": 111})
|
||||
self.assertEqual(found.dollars["project"], {"log": 6.0})
|
||||
self.assertEqual(found.dollars["subagent type"], {"worker": 6.0})
|
||||
self.assertEqual(found.dollars["rung"], {str(LOW): 4.0, str(HIGH): 2.0})
|
||||
self.assertEqual(found.dollars["tool"], {"prompt": 4.0, "Read": 2.0})
|
||||
self.assertEqual((found.start, found.unfinished), (LOW, 1))
|
||||
|
||||
def test_reads_a_subagents_rung_from_its_model_and_the_effort_its_call_set_or_else_the_workers(self):
|
||||
@@ -69,7 +76,7 @@ class Measured(unittest.TestCase):
|
||||
]
|
||||
found = measured(Chunk("log", [stamped("2026-10-14T11:00:00Z", outcomes.finished(LOW_ROUTE, "m", "j"))], worker, subagents), "/h")
|
||||
self.assertEqual(found.delegated, {"claude-sonnet-5-5 at high effort": 1, str(LOW): 1})
|
||||
self.assertEqual(found.tokens["subagent type"], {"worker": 111, "Explore": 222})
|
||||
self.assertEqual(found.dollars["subagent type"], {"worker": 2.0, "Explore": 3.0})
|
||||
self.assertEqual(found.reports, {"Explore": Reports(2, 35, 20)})
|
||||
|
||||
def test_counts_the_workers_escalations_by_the_trigger_each_subagents_prompt_opens_with(self):
|
||||
@@ -84,22 +91,21 @@ 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_rung_of_a_route_an_older_loop_claude_archived_by_r_plus_c(self):
|
||||
older = f"{LOW}, routed by item 7's R + C of 9"
|
||||
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})
|
||||
self.assertEqual(found.dollars["rung"], {str(LOW): 2.0})
|
||||
|
||||
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})
|
||||
|
||||
self.assertEqual(found.dollars["rung"], {str(LOW): 2.0})
|
||||
|
||||
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")),
|
||||
@@ -108,23 +114,72 @@ class Measured(unittest.TestCase):
|
||||
subagents = [Subagent("Explore", "a1", [result("r", "x")]), Subagent("Explore", "a2", [message("s2", "2026-10-14T10:31:01Z", model="claude-opus-5-5")])]
|
||||
found = measured(Chunk("log", [kept], worker, subagents), "/h")
|
||||
self.assertEqual(found.delegated, {"sonnet at high effort": 1, str(HIGH): 1})
|
||||
self.assertEqual(found.tokens["rung"], {str(LOW): 111, str(HIGH): 333})
|
||||
self.assertEqual(found.dollars["rung"], {str(LOW): 2.0, str(HIGH): 6.0})
|
||||
|
||||
def test_names_a_subagent_by_its_meta_or_else_its_call_or_else_unknown(self):
|
||||
worker = [message("m1", "2026-10-14T10:00:00Z", call("Agent", "a1", subagent_type="Explore"), call("Agent", "a2", subagent_type="Plan"))]
|
||||
subagents = [Subagent("stability-reviewer", "a1", []), Subagent("", "a2", []), Subagent("", "", [])]
|
||||
self.assertEqual(measured(Chunk("log", [], worker, subagents), "/h").reports, {"stability-reviewer": Reports(1, 0, 0), "Plan": Reports(1, 0, 0), "unknown": Reports(1, 0, 0)})
|
||||
|
||||
def test_counts_a_message_without_usage_as_nothing_and_splits_tokens_whole_across_tools(self):
|
||||
def test_counts_a_message_without_usage_or_a_priced_model_as_nothing_and_splits_a_cost_evenly_across_tools(self):
|
||||
worker = [
|
||||
{"type": "assistant", "uuid": "u1", "message": {"content": [call("Read"), call("Grep")], "usage": {"input_tokens": 3, "output_tokens": "many"}}},
|
||||
{"type": "assistant", "uuid": "u1", "message": {"model": "claude-opus-5-5", "content": [call("Read"), call("Grep")], "usage": {"input_tokens": 1_000_000, "output_tokens": "many"}}},
|
||||
{"type": "user", "message": {"content": [{"type": "tool_result", "tool_use_id": "t1", "content": "plain"}, "odd"]}},
|
||||
{"type": "assistant", "uuid": "u2", "message": {"content": [], "usage": {"input_tokens": 5}}},
|
||||
{"type": "assistant", "uuid": "u3", "message": {"content": []}},
|
||||
{"type": "assistant", "uuid": "u2", "message": {"model": "claude-opus-5-5", "content": [], "usage": {"input_tokens": 2_000_000}}},
|
||||
{"type": "assistant", "uuid": "u3", "message": {"model": "claude-opus-5-5", "content": []}},
|
||||
{"type": "assistant", "uuid": "u4", "message": {"model": "claude-unheard-of", "content": [], "usage": {"input_tokens": 9_000_000}}},
|
||||
]
|
||||
found = measured(Chunk("log", [], worker, []), "/h")
|
||||
self.assertEqual(found.tokens["tool"], {"prompt": 3, "Read": 3, "Grep": 2})
|
||||
self.assertEqual(found.tokens["project"], {"log": 8})
|
||||
self.assertEqual(found.dollars["tool"], {"prompt": 4.0, "Read": 4.0, "Grep": 4.0})
|
||||
self.assertEqual(found.dollars["project"], {"log": 12.0})
|
||||
|
||||
def test_prices_input_cache_writes_by_their_lifetime_cache_reads_and_output_at_the_models_list_prices(self):
|
||||
usage = {"input_tokens": 1_000_000, "cache_creation_input_tokens": 2_000_000, "cache_creation": {"ephemeral_5m_input_tokens": 1_000_000, "ephemeral_1h_input_tokens": 1_000_000}, "cache_read_input_tokens": 1_000_000, "output_tokens": 1_000_000}
|
||||
opus = measured(Chunk("log", [], [message("m1", "2026-10-14T10:00:00Z", usage=usage)], []), "/h")
|
||||
self.assertAlmostEqual(opus.dollars["project"]["log"], 4 + 5 + 8 + 0.2 + 20)
|
||||
sonnet = measured(Chunk("log", [], [message("m1", "2026-10-14T10:00:00Z", model="claude-sonnet-5-5", usage=usage)], []), "/h")
|
||||
self.assertAlmostEqual(sonnet.dollars["project"]["log"], 2 + 2.5 + 4 + 0.2 + 10)
|
||||
|
||||
def test_counts_a_cache_write_without_a_lifetime_as_a_five_minute_one(self):
|
||||
usage = {"cache_creation_input_tokens": 1_000_000}
|
||||
found = measured(Chunk("log", [], [message("m1", "2026-10-14T10:00:00Z", usage=usage)], []), "/h")
|
||||
self.assertAlmostEqual(found.dollars["project"]["log"], 5)
|
||||
|
||||
def test_splits_the_cost_a_chunks_last_cost_state_records_for_each_model_across_its_messages_by_list_price(self):
|
||||
worker = [
|
||||
message("m1", "2026-10-14T10:00:00Z", call("Agent", "a1", subagent_type="Explore")),
|
||||
message("m2", "2026-10-14T10:01:00Z"),
|
||||
cost_state(claude_opus_5_5=1.0),
|
||||
cost_state(claude_opus_5_5=9.0, claude_haiku_5_5=0.5),
|
||||
]
|
||||
subagents = [Subagent("Explore", "a1", [message("s1", "2026-10-14T10:00:01Z")])]
|
||||
found = measured(Chunk("log", [], worker, subagents), "/h")
|
||||
self.assertEqual(found.dollars["subagent type"], {"worker": 6.0, "Explore": 3.0})
|
||||
self.assertEqual(found.dollars["project"], {"log": 9.0})
|
||||
self.assertEqual(found.unattributed, 0.5)
|
||||
|
||||
def test_counts_the_subagents_the_worker_launched_that_have_no_transcript(self):
|
||||
worker = [message("m1", "2026-10-14T10:00:00Z", call("Agent", "a1", subagent_type="Explore"), call("Agent", "a2", subagent_type="Explore"), call("Read", "r1", file_path="/c/a"))]
|
||||
found = measured(Chunk("log", [], worker, [Subagent("Explore", "a1", [message("s1", "2026-10-14T10:00:01Z")])]), "/h")
|
||||
self.assertEqual(found.lacking, 1)
|
||||
unnamed = measured(Chunk("log", [], worker, [Subagent("", "", [message("s1", "2026-10-14T10:00:01Z")]), Subagent("", "", [message("s2", "2026-10-14T10:00:02Z")])]), "/h")
|
||||
self.assertEqual(unnamed.lacking, 0)
|
||||
nested = [message("s1", "2026-10-14T10:00:01Z", call("Agent", "n1", subagent_type="Explore"))]
|
||||
launched = measured(Chunk("log", [], worker, [Subagent("Explore", "a1", nested), Subagent("Explore", "a2", [message("s2", "2026-10-14T10:00:02Z")]), Subagent("Explore", "n1", [message("s3", "2026-10-14T10:00:03Z")])]), "/h")
|
||||
self.assertEqual(launched.lacking, 0)
|
||||
self.assertEqual(measured(Chunk("log", [], worker, [Subagent("Explore", "a1", nested), Subagent("Explore", "a2", [])]), "/h").lacking, 1)
|
||||
|
||||
def test_charges_a_message_without_a_timestamp_to_the_rung_of_the_last_outcome(self):
|
||||
undated = message("m1", "")
|
||||
del undated["timestamp"]
|
||||
kept = stamped("2026-10-14T10:30:00Z", outcomes.unfinished(LOW_ROUTE, "e", "j", "")) + stamped("2026-10-14T12:00:00Z", outcomes.finished(Route(HIGH).worker_line(), "merged", "j"))
|
||||
self.assertEqual(measured(Chunk("log", [kept], [undated], []), "/h").dollars["rung"], {str(HIGH): 2.0})
|
||||
|
||||
def test_keeps_list_prices_for_a_model_the_cost_state_does_not_name(self):
|
||||
worker = [message("m1", "2026-10-14T10:00:00Z"), message("m2", "2026-10-14T10:01:00Z", model="claude-sonnet-5-5"), cost_state(claude_opus_5_5=3.0)]
|
||||
found = measured(Chunk("log", [], worker, []), "/h")
|
||||
self.assertEqual(found.dollars["project"], {"log": 4.0})
|
||||
self.assertEqual(found.unattributed, 0.0)
|
||||
|
||||
|
||||
class Calls(unittest.TestCase):
|
||||
@@ -153,13 +208,20 @@ class Calls(unittest.TestCase):
|
||||
self.assertEqual(calls(totals([figures(reports={"Explore": Reports(1, 20, 30)})] * 5)), [])
|
||||
|
||||
def test_renders_each_dimension_largest_first_and_the_calls(self):
|
||||
chunk = ChunkFigures({"project": collections.Counter({"a": 2, "b": 20})}, LOW, 1, 0, collections.Counter({str(HIGH): 2}), {"Explore": Reports(2, 3, 4)}, collections.Counter())
|
||||
chunk = ChunkFigures({"project": collections.Counter({"a": 2.5, "b": 1234.5})}, LOW, 1, 0, collections.Counter({str(HIGH): 2}), {"Explore": Reports(2, 3, 4)}, collections.Counter(), 0.0)
|
||||
text = render(totals([chunk]), ["Call."], "2026-10-15T00:00:00Z", 40, "")
|
||||
self.assertIn("Measured 2026-10-15T00:00:00Z, at cycle 40 across loop-claude's archive, from 1 finished chunk.", text)
|
||||
self.assertIn("## Calls for a routing change\n\n- Call.\n", text)
|
||||
self.assertIn("| b | 20 |\n| a | 2 |", text)
|
||||
self.assertIn("## Dollars by project", text)
|
||||
self.assertIn("| b | $1,234.50 |\n| a | $2.50 |", text)
|
||||
self.assertIn("cache reads included", text)
|
||||
self.assertIn("The judge's runs are not archived, so their cost is not counted.", text)
|
||||
self.assertNotIn("left out", text)
|
||||
self.assertNotIn("no transcript", text)
|
||||
self.assertIn("The archive holds no subagent transcript for 2 of the chunks' Agent calls.", render(totals([dataclasses.replace(chunk, lacking=1)] * 2), [], "2026-10-15T00:00:00Z", 40, ""))
|
||||
self.assertIn("$0.50 of the recorded cost is left out", render(totals([ChunkFigures({}, LOW, 0, 0, collections.Counter(), {}, collections.Counter(), 0.5), chunk]), [], "2026-10-15T00:00:00Z", 40, ""))
|
||||
self.assertIn(f"| {LOW} | 1 | 1.0 | 0.0 | {HIGH} 2 | |", text)
|
||||
two = ChunkFigures({}, HIGH, 0, 1, collections.Counter({str(HIGH): 2, str(LOW): 1}), {}, collections.Counter())
|
||||
two = ChunkFigures({}, HIGH, 0, 1, collections.Counter({str(HIGH): 2, str(LOW): 1}), {}, collections.Counter(), 0.0)
|
||||
self.assertIn(f"| {LOW} | 1 | 1.0 | 0.0 | {HIGH} 2 | |\n| {HIGH} | 1 | 0.0 | 1.0 | {HIGH} 2, {LOW} 1 | |", render(totals([two, chunk]), [], "2026-10-15T00:00:00Z", 40, ""))
|
||||
self.assertIn("| Explore | 2 | 3 | 4 |", text)
|
||||
escalated = render(totals([figures(escalated={2: 2}), figures(escalated={2: 1, 10: 1}), figures(start=None, escalated={3: 1})]), [], "2026-10-15T00:00:00Z", 40, "")
|
||||
@@ -191,7 +253,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)
|
||||
|
||||
@@ -199,8 +261,8 @@ class Archive(unittest.TestCase):
|
||||
self.chunk("home/x", "c1", stamped("2026-10-14T10:00:00Z", outcomes.finished(LOW_ROUTE, "m", "j")), [message("m1", "2026-10-14T09:00:00Z", call("Agent", "a1", subagent_type="Explore"))], ({"agentType": "Explore", "toolUseId": "a1"}, [message("s1", "2026-10-14T09:00:01Z")]))
|
||||
self.chunk("log", "c2", stamped("2026-10-14T10:00:00Z", outcomes.unfinished(LOW_ROUTE, "e", "j", "")), [message("m1", "2026-10-14T09:00:00Z")])
|
||||
found = archive.measure_archive(self.root, "/h", "")
|
||||
self.assertEqual([chunk.tokens["project"] for chunk in found.chunks], [{"home/x": 222}])
|
||||
self.assertEqual(found.chunks[0].tokens["subagent type"], {"worker": 111, "Explore": 111})
|
||||
self.assertEqual([chunk.dollars["project"] for chunk in found.chunks], [{"home/x": 4.0}])
|
||||
self.assertEqual(found.chunks[0].dollars["subagent type"], {"worker": 2.0, "Explore": 2.0})
|
||||
self.assertEqual(archive.measure_archive(self.root, "/h", "2026-10-14T10:00:00Z"), archive.Measured([], ()))
|
||||
|
||||
def test_reads_each_cycles_route_from_its_own_outcomes_file(self):
|
||||
@@ -211,10 +273,10 @@ 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})
|
||||
self.assertEqual(found.dollars["rung"], {str(LOW): 2.0, str(HIGH): 2.0})
|
||||
|
||||
def test_skips_a_chunk_it_cannot_read_and_names_it(self):
|
||||
self.chunk("log", "c1", stamped("2026-10-14T10:00:00Z", outcomes.finished(LOW_ROUTE, "m", "j")), [])
|
||||
|
||||
+11
-1
@@ -2,6 +2,7 @@ import dataclasses
|
||||
import typing
|
||||
|
||||
from failure import Failure
|
||||
from claude_code.session import subagent_transcript
|
||||
|
||||
FILE_TOOLS = ("Edit", "MultiEdit", "Write")
|
||||
|
||||
@@ -11,6 +12,10 @@ 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 = ""
|
||||
# The transcript of the agent that makes the call: a subagent's own, not its session's.
|
||||
transcript: str = ""
|
||||
|
||||
|
||||
def parsed_call(hook_input: object) -> Call | Failure:
|
||||
@@ -19,7 +24,12 @@ 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, agent_id, transcript = hook_input.get("agent_type"), hook_input.get("agent_id"), hook_input.get("transcript_path")
|
||||
transcript = transcript if isinstance(transcript, str) else ""
|
||||
if isinstance(agent_id, str) and transcript:
|
||||
# Inside a subagent, transcript_path still names the session's transcript.
|
||||
transcript = subagent_transcript(transcript, agent_id)
|
||||
return Call(tool, given, cwd, agent if isinstance(agent, str) else "", transcript)
|
||||
|
||||
|
||||
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:
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
"""Whether a simple command is a heavy one, for the `run-heavy` rule: a docker build, or a run of a mutation tool."""
|
||||
from docker_command import docker_subcommand
|
||||
from shell_command import launched, tool_name
|
||||
|
||||
# Each mutation tool, and the words that make its call a mutation run when one of them follows it within two words; where the set is empty, every call is one.
|
||||
MUTATORS = {"cargo": {"mutants"}, "infection": set(), "mutmut": {"run"}, "stryker": {"run"}}
|
||||
# Flags with which a tool only prints its help, version or list, so a call that carries one is light. Not -h, which docker run reads as the container's hostname.
|
||||
LIGHT_FLAGS = frozenset({"--help", "--list", "--version"})
|
||||
BUILDS = (["build"], ["buildx", "build"], ["compose", "build"])
|
||||
|
||||
|
||||
def heavy(words: list[str]) -> bool:
|
||||
"""Whether the simple command, run directly or through a launcher, is a docker build or a mutation run, or runs one in a container, and is not under run-heavy."""
|
||||
launch = launched(words, {"docker", *MUTATORS})
|
||||
if launch is None or "run-heavy" in launch.launchers or LIGHT_FLAGS & set(words):
|
||||
return False
|
||||
if launch.tool == "docker":
|
||||
subcommand = docker_subcommand(launch.arguments)
|
||||
return subcommand in BUILDS or (subcommand[-1:] in (["run"], ["exec"]) and mutation_run([tool_name(word) for word in launch.arguments]))
|
||||
return mutation_run([launch.tool, *(tool_name(word) for word in launch.arguments)])
|
||||
|
||||
|
||||
def mutation_run(names: list[str]) -> bool:
|
||||
return any(name in MUTATORS and (not MUTATORS[name] or MUTATORS[name] & set(names[i + 1:i + 3])) for i, name in enumerate(names))
|
||||
+49
-11
@@ -3,12 +3,12 @@
|
||||
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, Write and Agent call, in every session and
|
||||
settings.json runs it before each Agent, Bash, Edit, MultiEdit, Read and Write call, in every session and
|
||||
subagent. The rules:
|
||||
|
||||
{rules}
|
||||
|
||||
A file a Bash command writes, such as through `cat > Dockerfile`, is not checked. The reviewer-rung rule takes no override.
|
||||
A file a Bash command writes, such as through `cat > Dockerfile`, is not checked.
|
||||
|
||||
A call overrides a rule with `# rule-override <rule>: <reason>`:
|
||||
|
||||
@@ -24,23 +24,29 @@ 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.
|
||||
"""
|
||||
import datetime
|
||||
import itertools
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import stat
|
||||
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.repeat_read import asked_lines, repeat_breaches, shown_lines
|
||||
from rule_hook.rules import Breach, check, Checked, command_breaches, file_breaches, rules_help
|
||||
from git_command import commits
|
||||
from claude_code.transcript import current_thread, read_transcript
|
||||
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
|
||||
@@ -66,7 +72,7 @@ def main(argv: list[str], stdin: str) -> int:
|
||||
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, environ: typing.Mapping[str, str]) -> tuple[str, str, list[Breach]] | None:
|
||||
@@ -75,21 +81,23 @@ def breaches_of(call: Call, home: str, environ: typing.Mapping[str, str]) -> tup
|
||||
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)
|
||||
return command, command.split("\n", 1)[0], bash_breaches(command, call.cwd, home) + read_breaches(call, home)
|
||||
if call.tool == "Read":
|
||||
return "", text(call.given, "file_path"), read_breaches(call, home)
|
||||
path = text(call.given, "file_path")
|
||||
if call.tool not in FILE_TOOLS or not path:
|
||||
return None
|
||||
before = read(path)
|
||||
added, after = applied(call, before)
|
||||
return added, path, file_breaches(path, before, added, after)
|
||||
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:
|
||||
@@ -106,6 +114,36 @@ def bash_breaches(command: str, cwd: str, home: str) -> list[Breach]:
|
||||
return command_breaches(command, simples, home) + [breach for commit in commits(simples, home) for breach in todo_breaches(commit.directory)]
|
||||
|
||||
|
||||
def read_breaches(call: Call, home: str) -> list[Breach]:
|
||||
"""The repeat-read breaches of a call, read from the calling agent's transcript and the asked file; none where either cannot be read, or the file is not a regular file."""
|
||||
asked = asked_lines(call.tool, call.given, call.cwd, home)
|
||||
changed = modified(asked.path) if asked else None
|
||||
entries = read_transcript(call.transcript) if changed and call.transcript else []
|
||||
if asked is None or changed is None or isinstance(entries, Failure):
|
||||
return []
|
||||
shown = shown_lines(current_thread(entries), call.tool, asked.path, changed, home)
|
||||
# No line past the last one shown is in context, so the file's lines through one past it tell as much as all of them, and a long file is not read whole.
|
||||
return repeat_breaches(asked, first_lines(asked.path, max(shown) + 1), shown, call.cwd) if shown else []
|
||||
|
||||
|
||||
def modified(path: str) -> str | None:
|
||||
"""When a regular file last changed, stamped as a transcript entry is; None for any other path, such as a FIFO, whose read could hang."""
|
||||
try:
|
||||
status = os.stat(path)
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
return datetime.datetime.fromtimestamp(status.st_mtime, datetime.UTC).isoformat(timespec="milliseconds").replace("+00:00", "Z") if stat.S_ISREG(status.st_mode) else None
|
||||
|
||||
|
||||
def first_lines(path: str, count: int) -> list[str]:
|
||||
"""The file's first count lines, without their line ends; none where it cannot be read as UTF-8."""
|
||||
try:
|
||||
with open(path, encoding="utf-8") as file:
|
||||
return [line.removesuffix("\n") for line in itertools.islice(file, count)]
|
||||
except (OSError, UnicodeDecodeError):
|
||||
return []
|
||||
|
||||
|
||||
def read(path: str) -> str:
|
||||
try:
|
||||
return pathlib.Path(path).read_text(encoding="utf-8")
|
||||
|
||||
@@ -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,115 @@
|
||||
"""Whether a read asks for lines of a file already in the agent's context, for the `repeat-read` rule.
|
||||
|
||||
A line is in context when a read since the transcript thread's last compaction showed it at its line number, as the file holds it now.
|
||||
Against a Read, no line is in context when the file changed after the agent last read it with Read or wrote it with Edit, MultiEdit or Write, or when it never did."""
|
||||
import dataclasses
|
||||
import re
|
||||
|
||||
from rule_hook.rules import Breach
|
||||
from rule_hook.call import FILE_TOOLS, text
|
||||
from claude_code.entries import parts, tool_call, tool_result, tool_use_id
|
||||
from shell_command import resolved, simple_commands
|
||||
|
||||
# The lines a Read without a limit returns.
|
||||
READ_LIMIT = 2000
|
||||
# A line of a Read result: its number, then a tab, or an arrow in older Claude Code versions.
|
||||
NUMBERED = re.compile(r" *(\d+)[\t→](.*)", re.DOTALL)
|
||||
HEAD_COUNT = re.compile(r"-(?:n ?)?(\d+)")
|
||||
SED_RANGE = re.compile(r"(\d+)(?:,(\d+|\$))?p")
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Asked:
|
||||
path: str
|
||||
first: int
|
||||
# None: to the file's end.
|
||||
last: int | None
|
||||
|
||||
|
||||
def repeat_breaches(asked: Asked, lines: list[str], shown: dict[int, str], cwd: str) -> list[Breach]:
|
||||
"""shown is what shown_lines found, and lines the asked file's lines now, read at least through one past the last shown line."""
|
||||
last = len(lines) if asked.last is None else min(asked.last, len(lines))
|
||||
if not in_context(asked.first, last, lines, shown):
|
||||
return []
|
||||
named = f"line {last} of {asked.path} is" if asked.first == last else f"lines {asked.first}-{last} of {asked.path} are"
|
||||
return [Breach("repeat-read", f"{named} in your context, unchanged since your last read of it", cwd)]
|
||||
|
||||
|
||||
def in_context(first: int, last: int, lines: list[str], shown: dict[int, str]) -> bool:
|
||||
return first <= last and all(shown.get(number) == lines[number - 1] for number in range(first, last + 1))
|
||||
|
||||
|
||||
def asked_lines(tool: object, given: object, cwd: str, home: str) -> Asked | None:
|
||||
"""The lines a tool call reads; None for any call but a Read and the Bash reads the rule names, such as one whose output goes elsewhere."""
|
||||
if not isinstance(given, dict):
|
||||
return None
|
||||
return read_asked(given, cwd, home) if tool == "Read" else shell_asked(text(given, "command"), cwd, home) if tool == "Bash" else None
|
||||
|
||||
|
||||
def read_asked(given: dict, cwd: str, home: str) -> Asked | None:
|
||||
path, offset, limit = text(given, "file_path"), given.get("offset"), given.get("limit")
|
||||
first = offset if isinstance(offset, int) and offset > 0 else 1
|
||||
return Asked(resolved(cwd, path, home), first, first + (limit if isinstance(limit, int) and limit > 0 else READ_LIMIT) - 1) if path else None
|
||||
|
||||
|
||||
# reading_cost/shell_reads.py parses a shell read too, loosely: a measure of reading counts any file a reader names, while a rule that blocks must match only a read whose lines it knows exactly.
|
||||
def shell_asked(command: str, cwd: str, home: str) -> Asked | None:
|
||||
simples = simple_commands(command, cwd, home) if not set("|<>") & set(command) else []
|
||||
if len(simples) != 1 or len(simples[0].words) < 2 or simples[0].words[-1].startswith("-"):
|
||||
return None
|
||||
(name, *options, path), directory = simples[0].words, simples[0].directory
|
||||
path = resolved(directory, path, home)
|
||||
if name == "cat" and not options:
|
||||
return Asked(path, 1, None)
|
||||
if name == "head" and (counted := HEAD_COUNT.fullmatch(" ".join(options) or "-10")):
|
||||
return Asked(path, 1, int(counted.group(1)))
|
||||
if name == "sed" and len(options) == 2 and options[0] == "-n" and (ranged := SED_RANGE.fullmatch(options[1])):
|
||||
start, end = ranged.groups()
|
||||
return Asked(path, int(start), None if end == "$" else int(end or start))
|
||||
return None
|
||||
|
||||
|
||||
def shown_lines(thread: list[dict], asker: str, path: str, changed: str, home: str) -> dict[int, str]:
|
||||
"""Each line number of path that a successful read in the thread showed, with the line its latest read showed; none against a Read when the file changed after the agent last read it with Read or wrote it with Edit, MultiEdit or Write, or when it never did.
|
||||
|
||||
changed is when the file last changed, stamped as the transcript stamps its entries, so the two compare as text."""
|
||||
used = results_on(thread, path, home)
|
||||
# Claude Code's Edit and Write refuse such a file until a Read, and a Bash read does not count as one.
|
||||
touched = max((stamp for tool, _, _, stamp in used if tool == "Read" or tool in FILE_TOOLS), default="")
|
||||
if asker == "Read" and changed > touched:
|
||||
return {}
|
||||
shown: dict[int, str] = {}
|
||||
for tool, asked, result, _ in used:
|
||||
shown |= result_lines(tool, asked, result) if asked else {}
|
||||
return shown
|
||||
|
||||
|
||||
def results_on(thread: list[dict], path: str, home: str) -> list[tuple[object, Asked | None, str, str]]:
|
||||
"""Each successful result in the thread of a call that read lines of path or wrote it: the call's tool, the lines it read (None for a write), the result's text and its entry's timestamp."""
|
||||
calls: dict[str, tuple[object, Asked | None]] = {}
|
||||
found: list[tuple[object, Asked | None, str, str]] = []
|
||||
for entry in thread:
|
||||
cwd = str(entry.get("cwd", ""))
|
||||
for part in parts(entry):
|
||||
if (call := tool_call(part)) and (called := tool_use_id(part)):
|
||||
asked = asked_lines(*call, cwd, home)
|
||||
if (asked.path if asked else written(*call, cwd, home)) == path:
|
||||
calls[called] = (call[0], asked)
|
||||
elif (result := tool_result(part)) and not result.failed and (use := calls.get(result.tool_use_id)):
|
||||
found.append((use[0], use[1], result.text, text(entry, "timestamp")))
|
||||
return found
|
||||
|
||||
|
||||
def written(tool: object, given: object, cwd: str, home: str) -> str:
|
||||
"""The file an Edit, MultiEdit or Write call writes; empty for any other call."""
|
||||
return resolved(cwd, path, home) if tool in FILE_TOOLS and isinstance(given, dict) and (path := text(given, "file_path")) else ""
|
||||
|
||||
|
||||
def result_lines(tool: object, asked: Asked, result: str) -> dict[int, str]:
|
||||
if tool == "Read":
|
||||
return {int(numbered.group(1)): numbered.group(2) for line in result.split("\n") if (numbered := NUMBERED.fullmatch(line))}
|
||||
# Claude Code cuts a long Bash output short with a note: before the output, "<persisted-output>\n" or "<truncated-output>\n" and a few more lines, or after it, "\n\n... [N lines truncated] ...".
|
||||
# The note's lines would take the numbers of the file's, so such an output shows no lines.
|
||||
if result.startswith(("<persisted-output>\n", "<truncated-output>\n")) or result.endswith(" lines truncated] ..."):
|
||||
return {}
|
||||
return {number: line for number, line in enumerate(result.split("\n"), asked.first) if asked.last is None or number <= asked.last}
|
||||
@@ -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)]
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user