Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
test(pixel-draw): the grid a model answers is read strictly, broken rows are asked for alone and spliced, one redraw at most, gates G2-G6, the pick, batches and --resume, byte-reproducible PNGs
Soohong Kimaa32d058d146
diff --git a/tests/fixtures/pixel_draw/fourdir-16-pass.txt b/tests/fixtures/pixel_draw/fourdir-16-pass.txtnew file mode 100644index 0000000..893e99a--- /dev/null+++ b/tests/fixtures/pixel_draw/fourdir-16-pass.txt@@ -0,0 +1,85 @@+```pixels+PALETTE+. transparent+o #2a1f2e+s #c8d0d8+S #8a96a4+d #5a6472+r #d83a3a+R #8a1e28+p #f4c49a+P #c88a64+b #4a7ad8+B #2a4a9a+n #7a4a28+N #4a2a18+FRAME down+......orro......+....ooorRooo....+...osssSSSSdo...+...ossSSSSSdo...+...ospppppPdo...+...ospoppoPdo...+...osppppPPdo...+...odSSSSSSdo...+..oSbbbbbbbBdo..+..oSbbbbbbbBdo..+..oSnnnnnnnNdo..+..opbbbbbbbBPo..+...obbbBobbBo...+....oSdooSdo....+...onnNoonnNo...+...oooo..oooo...+FRAME up+......orro......+....ooorRooo....+...osssSSSSdo...+...ossSSSSSdo...+...osSSSSSddo...+...osSSSSSddo...+...odSSSSdddo...+...oddddddddo...+..oSbbbbbbbBdo..+..oSbbbbbbbBdo..+..oSnnnnnnnNdo..+..opbbbbbbbBPo..+...obbbBobbBo...+....oSdooSdo....+...onnNoonnNo...+...oooo..oooo...+FRAME left+.......orro.....+.....ooorRoo....+....osssSSSdo...+....ossSSSSdo...+...opppSSSSdo...+...opopSSSSdo...+...opPPSSSddo...+....odSSSSdo....+....obbSSdBo....+....obbSSdBo....+....onnSSdNo....+....obbpPbBo....+....obbbbbBo....+....oSdoSdo.....+...onnNonnNo....+...oooo.oooo....+FRAME right+.....orro.......+....ooRrooo.....+...odSSSssso....+...odSSSSsso....+...odSSSSpppo...+...odSSSSpopo...+...oddSSSPPpo...+....odSSSSdo....+....oBdSSbbo....+....oBdSSbbo....+....oNdSSnno....+....oBbPpbbo....+....oBbbbbbo....+.....odSodSo....+....oNnnoNnno...+....oooo.oooo...+END+```\ No newline at end of filediff --git a/tests/fixtures/pixel_draw/fourdir-16-unknown-symbol.repair.txt b/tests/fixtures/pixel_draw/fourdir-16-unknown-symbol.repair.txtnew file mode 100644index 0000000..b43a079--- /dev/null+++ b/tests/fixtures/pixel_draw/fourdir-16-unknown-symbol.repair.txt@@ -0,0 +1 @@+ROW up 8: ...oSssssssso...\ No newline at end of filediff --git a/tests/fixtures/pixel_draw/fourdir-16-unknown-symbol.txt b/tests/fixtures/pixel_draw/fourdir-16-unknown-symbol.txtnew file mode 100644index 0000000..b98ad96--- /dev/null+++ b/tests/fixtures/pixel_draw/fourdir-16-unknown-symbol.txt@@ -0,0 +1,87 @@+```pixels+PALETTE+. transparent+o #22202e+W #e4e8ee+S #a4acba+s #646c7e+R #e04040+r #9a2434+P #f4c8a0+p #cc9070+B #3c6cd0+L #6c9cf0+b #284890+N #8a5530+n #5a3420+K #e8c050+FRAME down+......oooo......+.....oRRRro.....+....ooRrrroo....+...oWWSSSSsso...+...oWSSSSSSso...+...oWppppppso...+...oSPoPPoPso...+...oSsPPPpsso...+..oSooooooooso..+..oSLBBssBBbso..+..oSLBBBBBBbso..+..oPNNNKKNNNPo..+...oLBBBBBBbo...+....oSsooSso....+...oNnnooNnno...+...oooo..oooo...+FRAME up+......oooo......+.....oRRRro.....+....ooRrrroo....+...oWWSRrSsso...+...oWSSRrSSso...+...oWSSSSSSso...+...oSSSSSSsso...+...oSsssssssо...+..oSooooooooso..+..oSLBBBBBBbso..+..oSLBBBBBBbso..+..oPNNNNNNNNPo..+...oLBBBBBBbo...+....oSsooSso....+...oNnnooNnno...+...oooo..oooo...+FRAME left+.......oooo.....+......oRRRro....+....ooRRrrroo...+...oWWSSSSsso...+...oWSSSSSSso...+...opppSSSSso...+...oPoPSSSSso...+....oPpSSssso...+....oooooooo....+....oLBSsBbo....+....oLBSsBbo....+....oNNPpNNo....+....oLBBBBbo....+....oSsosso.....+...oNNNnnno.....+...oooooooo.....+FRAME right+.....oooo.......+....oRRRro......+...ooRRrrroo....+...oWWSSSSsso...+...oWSSSSSSso...+...oWSSSSpppo...+...oSSSSSPoPo...+...oSssssPPo....+....oooooooo....+....oLBSsBbo....+....oLBSsBbo....+....oNNPpNNo....+....oLBBBBbo....+.....ossoSso....+.....onnnNNNo...+.....oooooooo...+END+```\ No newline at end of filediff --git a/tests/fixtures/pixel_draw/icon-16-json-pass.txt b/tests/fixtures/pixel_draw/icon-16-json-pass.txtnew file mode 100644index 0000000..71e03e6--- /dev/null+++ b/tests/fixtures/pixel_draw/icon-16-json-pass.txt@@ -0,0 +1,20 @@+```json+{"palette": ["transparent", "#2b1b2e", "#6b3f22", "#9a6234", "#c98f52", "#9cc3d6", "#5f8aa3", "#7a0f1e", "#c41e2e", "#ec4f4a", "#ffffff", "#d6ecf5"], "frames": {"icon": [+[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],+[0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0],+[0,0,0,0,1,4,4,3,3,3,2,1,0,0,0,0],+[0,0,0,0,1,3,3,3,3,2,2,1,0,0,0,0],+[0,0,0,0,1,1,1,1,1,1,1,1,0,0,0,0],+[0,0,0,0,0,1,11,5,5,6,1,0,0,0,0,0],+[0,0,0,1,1,11,5,5,5,6,6,1,1,0,0,0],+[0,0,1,9,9,9,9,9,9,9,8,8,7,1,0,0],+[0,0,1,9,10,10,9,8,8,8,8,8,7,1,0,0],+[0,0,1,9,10,9,8,8,8,8,8,7,7,1,0,0],+[0,0,1,9,8,8,8,8,8,8,8,7,7,1,0,0],+[0,0,1,8,8,8,8,8,8,8,7,7,7,1,0,0],+[0,0,1,7,7,8,8,8,8,7,7,7,7,1,0,0],+[0,0,0,1,1,7,7,7,7,7,7,1,1,0,0,0],+[0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0],+[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]+]}}+```\ No newline at end of filediff --git a/tests/fixtures/pixel_draw/icon-32-pass.txt b/tests/fixtures/pixel_draw/icon-32-pass.txtnew file mode 100644index 0000000..1a76b21--- /dev/null+++ b/tests/fixtures/pixel_draw/icon-32-pass.txt@@ -0,0 +1,50 @@+```pixels+PALETTE+. transparent+o #2a1a2e+c #d49a62+d #9a6438+e #6b3f22+r #ff5a5a+R #d42a3a+D #8a1530+p #ffa0a0+w #ffffff+g #cfe8f0+G #8fb5c8+H #5a7890+FRAME icon+................................+............oooooooo............+...........occcccddeo...........+...........occcdcddeo...........+...........occccdddeo...........+...........odddddeeeo...........+..........ogggGGGGGHHo..........+..........oooooooooooo..........+............ogGGGGHo............+............ogGGGGHo............+............ogGGGGHo............+...........ogGGGGGGHo...........+..........oggGGGGGGGHo..........+........oogggGGGGGGGHHoo........+.......oGpppprrrrrrrrrRHo.......+.......orrwwrrrRRRRRRRRDo.......+......orwwrrrRRRRRRRRRRDDo......+......orwrrrRRRRRRRRRRRDDo......+.....orrrrrRRRRRRRRRRRRRDDo.....+.....orrrrRRRRRRRRRRRRRRDDo.....+.....orrrRRRRRRRRRRRRRRDDDo.....+.....orrRRRRRRRRRRRRRRRDDDo.....+.....orRRRRRRRRRRRRRRRDDDDo.....+.....oRRRRRRRRRRRRRRRDDDDDo.....+......oRRRRRRRRRRRRRDDDDDo......+......oDRRRRRRRRRRRDDDDDDo......+.......oDRRRRRRRRRDDDDDDo.......+.......oDDRRRRRRRDDDDDDDo.......+........ooDDRRRRDDDDDDoo........+..........oDDDDDDDDDDo..........+...........oooooooooo...........+................................+END+```\ No newline at end of filediff --git a/tests/fixtures/pixel_draw/icon-32-row-width.repair.txt b/tests/fixtures/pixel_draw/icon-32-row-width.repair.txtnew file mode 100644index 0000000..72c30a4--- /dev/null+++ b/tests/fixtures/pixel_draw/icon-32-row-width.repair.txt@@ -0,0 +1 @@+ROW icon 16: .ooooooooooooGGooGgoooooooooooo.\ No newline at end of filediff --git a/tests/fixtures/pixel_draw/icon-32-row-width.txt b/tests/fixtures/pixel_draw/icon-32-row-width.txtnew file mode 100644index 0000000..e1bc706--- /dev/null+++ b/tests/fixtures/pixel_draw/icon-32-row-width.txt@@ -0,0 +1,49 @@+```pixels+PALETTE+. transparent+o #2a1a14+d #5c3520+m #8a5530+l #b0743c+h #d39a58+i #33333d+j #5b5b69+k #9496a6+g #9c6b14+G #e2ad2c+y #fff0a0+FRAME icon+................................+................................+....oooooooooooooooooooooooo....+..oohkjihhhhhhhhhhhhhhhhkjiloo..+.ohhhkjihhhhhhhhhhhhhhhhkjihhlo.+.ohllkjilllllllllmmmllllkjillmo.+.odddkjiddddddddddddddddkjidddo.+.ohllkjillllllllllllllllkjillmo.+.ohllkjilmmmllllllllllllkjillmo.+.olmmkjimmmmmmmmmmmdddmmkjimmdo.+.odddkjiddddddddddddddddkjidddo.+.ohllkjillllllllllllllllkjillmo.+.olmmkjimmmmoooooooommmmkjimmdo.+.okkkkkkkkkkoyyGGGgokkkkkkkkkjo.+.ojjjjjjjjjjoyGGGGgojjjjjjjjjio.+.ooooooooooooGGooGgooooooooooooo.+.odddkjiddddoGGooGgoddddkjidddo.+.ohllkjilllloGGooGgollllkjillmo.+.olmmkjimmmmoGGGGGgommmmkjimmdo.+.olmmkjimmmmoggggggommmmkjimmdo.+.olmmkjimmmmoooooooommmmkjimmdo.+.odddkjiddddddddddddddddkjidddo.+.ohllkjillllllllllllllllkjillmo.+.olmmkjimmmmdddmmmmmmmmmkjimmdo.+.olmmkjimmmmmmmmmmmddddmkjimmdo.+.olmmkjimmmmmmmmmmmmmmmmkjimmdo.+.odddkjiddddddddddddddddkjidddo.+.okkkkkkkkkkkkkkkkkkkkkkkkkkkjo.+.ojjjjjjjjjjjjjjjjjjjjjjjjjjjio.+.oiiiiiiiiiiiiiiiiiiiiiiiiiiiio.+.oooooooooooooooooooooooooooooo.+................................+END+```\ No newline at end of filediff --git a/tests/fixtures/pixel_draw/icon-32-space-in-row.repair.txt b/tests/fixtures/pixel_draw/icon-32-space-in-row.repair.txtnew file mode 100644index 0000000..b4dac5d--- /dev/null+++ b/tests/fixtures/pixel_draw/icon-32-space-in-row.repair.txt@@ -0,0 +1,9 @@+ROW icon 5: ......oohhhllddddddmmmmmoo......+ROW icon 15: .olldmmmhdlllllllllldddmmmmlddo.+ROW icon 20: .ollmdmmmmmhlllddlllldmmmmmlddo.+ROW icon 21: ..ommdmmmmhllddmmhdlldmmmmlddo..+ROW icon 24: ...ommmdmmmmmmmmmmmmmmmmldddo...+ROW icon 25: ....ommmlmmmmmmmmmmmmmmldddo....+ROW icon 26: ....ommmmlmmmmmmmmmmmmldddddo....+ROW icon 27: .....ommmmlllmmmmmmlllddddo.....+ROW icon 30: .........oooddddddddooo.........\ No newline at end of filediff --git a/tests/fixtures/pixel_draw/icon-32-space-in-row.txt b/tests/fixtures/pixel_draw/icon-32-space-in-row.txtnew file mode 100644index 0000000..64a949a--- /dev/null+++ b/tests/fixtures/pixel_draw/icon-32-space-in-row.txt@@ -0,0 +1,89 @@+```pixels+PALETTE+. transparent+o #3d240e+d #9a6414+m #d49a24+l #f2c94a+h #fff1a8+FRAME icon+................................+............oooooooo............+.........ooohllllllllooo........+........ohhhllllllllmmmo........+......oohhhlldddddddmmmmmoo......+.....ohhhhdddmmmmmmdddmmmmo.....+....ohhhhdmmmmmmmmmmmmdmmmmo....+....ohhhdmmmmmmmmmmmmmmdmmmo....+...ohhhdmmmmmmmmmmmmmmmmlmmmo...+..ohhhdmmmmmmmmhdmmmmmmmmlmmmo..+..ohhdmmmmmmmmmhdmmmmmmmmmlmmo..+..ohldmmmmmmmmhlldmmmmmmmmlmmo..+.ohlldmmmmmmmmhlldmmmmmmmmlmddo.+.olldmmmhhhhhhllllhhhhhdmmmlddo.+.olldmmmmhdlllllllllldddmmmmlddo.+.olldmmmmmmhlllllllldmmmmmmlddo.+.olldmmmmmmmhlllllldmmmmmmmlddo.+.olldmmmmmmmhlllllldmmmmmmmlddo.+.olldmmmmmmhlllllllldmmmmmmlddo.+.ollmdmmmmmhllldd lllldmmmmmlddo.+..ommdmmmmhllddmmhdlldmmmmldd o..+..ommdmmmmhddmmmmmmhddmmmmlddo..+..ommmdmmhdmmmmmmmmmmhdmmldddo..+...ommmdmmmmmmmmmmmmmmmmlddd o...+....ommmlmmmmmmmmmmmmmmlddd o....+....ommmmlmmmmmmmmmmmmldddd o....+.....ommmmlllmmmmmmllldddd o.....+......oommmmmlllllldddddoo......+........ommmdddddddddddo........+.........ooodddddddd ooo.........+............oooooooo............+................................+END+```++Wait — I need to verify row lengths; several rows above contain errors (stray spaces and miscounts). Corrected version:++```pixels+PALETTE+. transparent+o #3d240e+d #9a6414+m #d49a24+l #f2c94a+h #fff1a8+FRAME icon+................................+............oooooooo............+.........ooohllllllllooo.........+........ohhhllllllllmmmo........+......oohhhlldddddddmmmmmoo......+.....ohhhhdddmmmmmmdddmmmmo.....+....ohhhhdmmmmmmmmmmmmdmmmmo....+....ohhhdmmmmmmmmmmmmmmdmmmo....+...ohhhdmmmmmmmmmmmmmmmmlmmmo...+..ohhhdmmmmmmmmhdmmmmmmmmlmmmo..+..ohhdmmmmmmmmmhdmmmmmmmmmlmmo..+..ohldmmmmmmmmhlldmmmmmmmmlmmo..+.ohlldmmmmmmmmhlldmmmmmmmmlmddo.+.olldmmmhhhhhhllllhhhhhdmmmlddo.+.olldmmmmhdllllllllllddmmmmlddo.+.olldmmmmmmhlllllllldmmmmmmlddo.+.olldmmmmmmmhlllllldmmmmmmmlddo.+.olldmmmmmmmhlllllldmmmmmmmlddo.+.olldmmmmmmhlllllllldmmmmmmlddo.+.ollmdmmmmmhllldd llldmmmmmlddo.+..ommdmmmmhllddmmhdlldmmmmlddo..+..ommdmmmmhddmmmmmmhddmmmmlddo..+..ommmdmmhdmmmmmmmmmmhdmmldddo..+...ommmdmmmmmmmmmmmmmmmmlddd o...+....ommmlmmmmmmmmmmmmmmlddd o....+....ommmmlmmmmmmmmmmmmldddd o....+.....ommmmlllmmmmmmllldddd o.....+......oommmmmlllllldddddoo......+........ommmdddddddddddo........+.........ooodddddddddooo.........+............oooooooo............+................................+END+```\ No newline at end of filediff --git a/tests/fixtures/pixel_draw/pick-verdict.json b/tests/fixtures/pixel_draw/pick-verdict.jsonnew file mode 100644index 0000000..dac59f2--- /dev/null+++ b/tests/fixtures/pixel_draw/pick-verdict.json@@ -0,0 +1,22 @@+{+ "candidates": [+ {+ "label": "A",+ "subject_read": 5,+ "craft": 4,+ "consistency": 0,+ "verdict": "ship",+ "note": "Clean dark outline, consistent top-left lighting and clear highlight; reads instantly as a glossy slime."+ },+ {+ "label": "B",+ "subject_read": 5,+ "craft": 4,+ "consistency": 0,+ "verdict": "ship",+ "note": "Nice glossy rim highlight and subtle base bulge, though the jagged right edge is slightly less clean than A."+ }+ ],+ "best": "A",+ "any_shippable": true+}diff --git a/tests/fixtures/pixel_draw/sprite-16-pass.txt b/tests/fixtures/pixel_draw/sprite-16-pass.txtnew file mode 100644index 0000000..acfd006--- /dev/null+++ b/tests/fixtures/pixel_draw/sprite-16-pass.txt@@ -0,0 +1,35 @@+```pixels+PALETTE+. transparent+o #2a1f2e+r #d84040+R #8a2030+s #d0d8e0+m #8a94a0+d #5a6270+p #f0c098+P #c88a68+b #3a6ad0+B #26408a+l #6a9ae8+n #7a4a28+N #4a2c18+FRAME front+......oooo......+.....orrrRo.....+....ossrRmdo....+...ossmmmmddo...+..osmmmmmmmddo..+..oddddddddddo..+..ompppppppPdo..+..ompoppppoPdo..+..omppppppPPdo..+...omPPPPPPdo...+.osmlbbbbbbBmdo.+.osmlbbbbbBBmdo.+.oppnnnssnnnPPo.+..oolbbbbbBBoo..+...onnNoonnNo...+...oooooooooo...+END+```\ No newline at end of filediff --git a/tests/fixtures/pixel_draw/sprite-32-frame-header-missing.txt b/tests/fixtures/pixel_draw/sprite-32-frame-header-missing.txtnew file mode 100644index 0000000..91bc618--- /dev/null+++ b/tests/fixtures/pixel_draw/sprite-32-frame-header-missing.txt@@ -0,0 +1,51 @@+```pixels+PALETTE+. transparent+o #2a1e2e+r #d84848+R #8a2430+s #d0d8e0+m #9aa4b0+d #5c6470+p #f2c6a0+P #d09a78+b #3c64c8+B #26408a+L #6a90e0+n #8a5632+N #4e2e1c+y #e0c050+................................+..............oooo..............+.............orrrRo.............+............orrrrrRo............+...........oooRRRRooo...........+..........ossmmmmmmddo..........+.........ossmmmmmmmmddo.........+.........osmooooooooddo.........+.........osmpppppppPddo.........+.........osmpoppppoPddo.........+.........osmpoppppoPddo.........+.........osmppppppPPddo.........+.........odmmpppPPPmddo.........+..........ooddoPPoddoo..........+.......osmmoLbbddbbBomddo.......+.......osmmoLbbbbbbBomddo.......+.......osmmoLbbbbbbBomddo.......+.......osmmoLbbbbbbBomddo.......+.......osmdonnnyynnNomddo.......+.......osmdoLbbbbbbBomddo.......+.......opPPoLbbbbbbBopPPo.......+........oooobbbbbbBBoooo........+...........oooooooooo...........+...........osmdoosmdo...........+...........osmdoosmdo...........+...........osmdoosmdo...........+..........onnnNoonnnNo..........+..........onnnNoonnnNo..........+..........onnnNoonnnNo..........+..........oNNNNooNNNNo..........+..........oooooooooooo..........+................................+END+```\ No newline at end of filediff --git a/tests/fixtures/pixel_draw/tile-16-pass.txt b/tests/fixtures/pixel_draw/tile-16-pass.txtnew file mode 100644index 0000000..c30db34--- /dev/null+++ b/tests/fixtures/pixel_draw/tile-16-pass.txt@@ -0,0 +1,26 @@+```pixels+PALETTE+. transparent+a #2a5fa8+b #3a78c4+c #5b98dc+d #a8d4f4+FRAME tile+bbbbbbbbbbbbbbbb+bbbbbbbbbbbbbbbb+bbbddddbbbbbbbbb+bbcbbbbcbbbbbbbb+bbbaaaabbbbbbbbb+bbbbbbbbbbbbbbbb+bbbbbbbbbbbbbbbb+bbbbbbbbbbddddbb+bbbbbbbbbcbbbbcb+bbbbbbbbbbaaaabb+bbbbbbbbbbbbbbbb+bbbbbbbbbbbbbbbb+ddbbbbbbbbbbbbdd+bbcbbbbbbbbbbcbb+aabbbbbbbbbbbbaa+bbbbbbcccbbbbbbb+END+```\ No newline at end of filediff --git a/tests/fixtures/pixel_draw/tile-32-truncated.repair.txt b/tests/fixtures/pixel_draw/tile-32-truncated.repair.txtnew file mode 100644index 0000000..66ec793--- /dev/null+++ b/tests/fixtures/pixel_draw/tile-32-truncated.repair.txt@@ -0,0 +1,17 @@+ROW tile 16: gdgglghggggggggggggggggggggggggg+ROW tile 17: gdggglgggggggggggggmmmmmmggggggg+ROW tile 18: ggggggggggggggggggmmmmmmmmgggggg+ROW tile 19: gggggggdgdggggggggmmmmmmmmmgggdg+ROW tile 20: gggggggdgdgggggggggmmmmmmmggggdg+ROW tile 21: ggggggggdgggggggggggmmmmgggggggg+ROW tile 22: gghggggggggggggdggggggggggghgggg+ROW tile 23: gglhgggggggggggdgggggggggglghggg+ROW tile 24: ggglgggggggggdgdgdggggggggglgggg+ROW tile 25: ggggggggggggggdkdgggggggggggggggg+ROW tile 26: gggggmmmmmgggggggggggggdgggggggg+ROW tile 27: ggggmmmmmmmgggggggghgggdgggggggh+ROW tile 28: gggmmmmmmmmgggggggglhggggggggggl+ROW tile 29: dggggmmmmmggggggggggggggggdggggg+ROW tile 30: dgggggggggggdggggggggggggdgdgggg+ROW tile 31: ggggggghgggdgdgggggggggggggggggg+ROW tile 32: ggggdgglggggggggggggmmmmmmgggggg\ No newline at end of filediff --git a/tests/fixtures/pixel_draw/tile-32-truncated.txt b/tests/fixtures/pixel_draw/tile-32-truncated.txtnew file mode 100644index 0000000..fb8d2e6--- /dev/null+++ b/tests/fixtures/pixel_draw/tile-32-truncated.txt@@ -0,0 +1,27 @@+```pixels+PALETTE+. transparent+k #2e5a26+d #3e7530+g #4e9038+m #5c9e42+l #7cbc52+h #a4d670+FRAME tile+ggggdggggggmmmmmmmmggggggggggggg+ggggggggdggggmmmmggggggggghggggg+ggggggggdggggggggggggggggglghggg+gggggggggggggggggggggggggglglggg+ggggmmmmggggggggggdgdgdggggglggg+hggmmmmmmmggggggggdgdgdggggggggg+lgmmmmmmmmgggggggggdkdgggggdgggg+gggmmmmmmgggghgggggggggggggdgggg+gggggmmmggggglghgggggggggggggggg+ggggggggggggglglgggggggghggggggg+gdggggggggggggglgggggggglggggdgd+gdgggggggggggggggggggggggggggdgd+dgggggggggdgdgggggggggdgggggggdk+ggggggggggdgdgggggggggdggggggggg+gggghggggggdgggggggggggggggggggg+gdgglghggggggggg官+```\ No newline at end of filediff --git a/tests/fixtures/pixel_draw/walk-16-pass.txt b/tests/fixtures/pixel_draw/walk-16-pass.txtnew file mode 100644index 0000000..e2bcf06--- /dev/null+++ b/tests/fixtures/pixel_draw/walk-16-pass.txt@@ -0,0 +1,85 @@+```pixels+PALETTE+. transparent+o #2a1e2e+s #c8d0dc+m #8a94a6+d #555e70+r #d83a3a+R #8e1f2a+p #f4c49a+P #c98a66+b #4a7ad8+B #2c4a94+n #7a4a2a+N #4e2e1a+FRAME walk1+................+....oooo........+...orrrRo.......+...osssssmo.....+...osmppppPo....+...osmpopopo....+...odmppPPo.....+...oBbbbbbo.....+...oBbmmbbo.....+...onnnpnno.....+...oBbbbbbbo....+...oddooomdo....+..oddo..omdo....+..oddo...omdo...+.oNNNNo..onnnNo.+.oooooo..oooooo.+FRAME walk2+....oooo........+...orrrRo.......+...osssssmo.....+...osmppppPo....+...osmpopopo....+...odmppPPo.....+...oBbbbbbo.....+...oBbmmbbo.....+...onnnpnno.....+...oBbbbbbbo....+...oomdmdoo.....+....oddmdo......+....oddmdo......+....oddmdo......+....onnnnNo.....+....ooooooo.....+FRAME walk3+................+....oooo........+...orrrRo.......+...osssssmo.....+...osmppppPo....+...osmpopopo....+...odmppPPo.....+...oBbbbbbo.....+...oBbmmbbo.....+...onnnpnno.....+...oBbbbbbbo....+...omdoooddo....+..omdo..oddo....+..omdo...oddo...+.onnnNo..oNNNNo.+.oooooo..oooooo.+FRAME walk4+....oooo........+...orrrRo.......+...osssssmo.....+...osmppppPo....+...osmpopopo....+...odmppPPo.....+...oBbbbbbo.....+...oBbmmbbo.....+...onnnpnno.....+...oBbbbbbbo....+...oomdddoo.....+....omdddo......+....omdddo......+....omdddo......+....onnnnNo.....+....ooooooo.....+END+```\ No newline at end of filediff --git a/tests/gen/test_anthropic_api.py b/tests/gen/test_anthropic_api.pynew file mode 100644index 0000000..0363b51--- /dev/null+++ b/tests/gen/test_anthropic_api.py@@ -0,0 +1,205 @@+# SPDX-License-Identifier: Apache-2.0+"""The Anthropic transport of `pixel-draw`, over a real local socket: the streamed message read+event by event, what is asked again (a refused request made nothing) and what never is (a stream+that broke after it began), Message Batches, and the price of a call. No key, no network."""+from __future__ import annotations++import http.server+import json+import threading++import pytest++from sprite_gen.gen import anthropic_api as api++KEY = "sk-ant-api03-" + "Synthetic0Key1For2Tests" * 2+++class Script(http.server.BaseHTTPRequestHandler):+ """Answers each request with the next scripted response and records what was asked."""++ def log_message(self, *args):+ pass++ def _answer(self):+ length = int(self.headers.get("Content-Length") or 0)+ body = self.rfile.read(length) if length else b""+ self.server.asked.append({"method": self.command, "path": self.path,+ "headers": {k.lower(): v for k, v in self.headers.items()},+ "body": json.loads(body) if body else None})+ kind, status, headers, payload = self.server.script.pop(0)+ self.send_response(status)+ for name, value in headers.items():+ self.send_header(name, value)+ if kind == "sse":+ self.send_header("Content-Type", "text/event-stream")+ self.end_headers()+ for event in payload:+ self.wfile.write(f"event: {event['type']}\ndata: {json.dumps(event)}\n\n".encode())+ self.wfile.flush()+ else:+ data = payload if isinstance(payload, bytes) else json.dumps(payload).encode()+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(data)))+ self.end_headers()+ self.wfile.write(data)++ do_GET = do_POST = _answer+++def server(monkeypatch):+ srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Script)+ srv.script, srv.asked = [], []+ thread = threading.Thread(target=srv.serve_forever, daemon=True)+ thread.start()+ monkeypatch.setattr(api, "API_BASE", f"http://127.0.0.1:{srv.server_address[1]}/v1")+ yield srv+ srv.shutdown()+ srv.server_close()+++def events(text="```pixels\n...\n```", thinking="Planning the rows.", stop="end_turn", details=None, end=True):+ usage_end = {"output_tokens": 8294, "output_tokens_details": {"thinking_tokens": 7564}}+ out = [+ {"type": "message_start", "message": {"id": "msg_01", "type": "message", "role": "assistant", "model": api.MODEL,+ "content": [], "stop_reason": None,+ "usage": {"input_tokens": 509, "output_tokens": 1,+ "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0}}},+ {"type": "ping"},+ {"type": "content_block_start", "index": 0, "content_block": {"type": "thinking", "thinking": ""}},+ {"type": "content_block_delta", "index": 0, "delta": {"type": "thinking_delta", "thinking": thinking}},+ {"type": "content_block_delta", "index": 0, "delta": {"type": "signature_delta", "signature": "c2ln"}},+ {"type": "content_block_stop", "index": 0},+ {"type": "content_block_start", "index": 1, "content_block": {"type": "text", "text": ""}},+ {"type": "content_block_delta", "index": 1, "delta": {"type": "text_delta", "text": text[:5]}},+ {"type": "content_block_delta", "index": 1, "delta": {"type": "text_delta", "text": text[5:]}},+ {"type": "content_block_stop", "index": 1},+ {"type": "message_delta", "delta": {"stop_reason": stop, "stop_sequence": None,+ **({"stop_details": details} if details else {})}, "usage": usage_end},+ ]+ return out + ([{"type": "message_stop"}] if end else [])+++def body(effort="high"):+ return api.message_body(system="sys", content="Draw: a slime", effort=effort, max_tokens=32000)+++def test_a_streamed_message_is_read_event_by_event(server):+ server.script.append(("sse", 200, {"request-id": "req_011abc"}, events()))+ reply = api.stream_message(KEY, body(), sleep=lambda s: pytest.fail("nothing to wait for"))+ assert (reply.text, reply.thinking, reply.stop_reason) == ("```pixels\n...\n```", "Planning the rows.", "end_turn")+ assert (reply.request_id, reply.message_id, reply.model, reply.mode) == ("req_011abc", "msg_01", api.MODEL, "realtime")+ assert reply.usage["input_tokens"] == 509 and reply.usage["output_tokens"] == 8294 # message_delta is cumulative+ assert api.thinking_tokens(reply.usage) == 7564+ (asked,) = server.asked+ assert asked["path"] == "/v1/messages" and asked["headers"]["x-api-key"] == KEY+ assert asked["headers"]["anthropic-version"] == "2023-06-01"+ sent = asked["body"]+ assert sent["stream"] is True and sent["model"] == "claude-opus-5-5" and sent["max_tokens"] == 32000+ assert sent["thinking"] == {"type": "adaptive", "display": "summarized"} and sent["output_config"] == {"effort": "high"}+++def test_a_refused_request_is_asked_again_and_said(server, capsys):+ server.script.append(("json", 529, {}, {"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}}))+ server.script.append(("json", 429, {"retry-after": "3"}, {"type": "error", "error": {"type": "rate_limit_error"}}))+ server.script.append(("sse", 200, {"request-id": "req_2"}, events()))+ waits = []+ reply = api.stream_message(KEY, body(), sleep=waits.append, label="pixel-draw c1-gen1")+ assert reply.request_id == "req_2" and len(server.asked) == 3+ assert waits == [10.0, 3.0] # the schedule, then the server's retry-after+ err = capsys.readouterr().err+ assert "[pixel-draw c1-gen1] claude refused the request (529 overloaded_error); nothing was made" in err+ assert "(1 of 2)" in err and "(2 of 2)" in err+++def test_refusals_past_the_retries_end_the_call(server):+ server.script += [("json", 503, {}, {"type": "error", "error": {"type": "api_error"}})] * 3+ with pytest.raises(api.ApiError) as caught:+ api.stream_message(KEY, body(), sleep=lambda s: None)+ assert caught.value.status == 503 and caught.value.billed is False and len(server.asked) == 3+++def test_a_bad_request_is_not_asked_again_and_the_key_is_masked(server):+ server.script.append(("json", 400, {"request-id": "req_bad"},+ {"type": "error", "error": {"type": "invalid_request_error", "message": f"bad key {KEY}"}}))+ with pytest.raises(api.ApiError) as caught:+ api.stream_message(KEY, body(), sleep=lambda s: pytest.fail("a 400 is not asked again"))+ line = caught.value.line+ assert line.startswith("pixel-draw: claude request failed (HTTP 400) code=invalid_request_error; not asked again: ")+ assert "Synthetic0Key1For2Tests" not in line and caught.value.request_id == "req_bad"+ assert len(server.asked) == 1+++def test_a_rejected_key_names_the_variable(server):+ server.script.append(("json", 401, {}, {"type": "error", "error": {"type": "authentication_error"}}))+ with pytest.raises(api.ApiError, match=r"credential ANTHROPIC_API_KEY rejected \(HTTP 401\) code=authentication_error"):+ api.stream_message(KEY, body(), sleep=lambda s: None)+++def test_an_error_event_mid_stream_is_not_asked_again(server):+ cut = events()[:8] + [{"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}}]+ server.script.append(("sse", 200, {"request-id": "req_cut"}, cut))+ with pytest.raises(api.ApiError) as caught:+ api.stream_message(KEY, body(), sleep=lambda s: pytest.fail("never asked again"))+ error = caught.value+ assert "ended in an error code=overloaded_error" in error.line and "may be billed" in error.line+ assert error.partial.text == "```pi" and error.partial.usage["input_tokens"] == 509+ assert error.request_id == "req_cut" and len(server.asked) == 1+++def test_a_stream_that_stops_before_message_stop_is_an_error(server):+ server.script.append(("sse", 200, {}, events(end=False)[:9]))+ with pytest.raises(api.ApiError, match="ended before message_stop"):+ api.stream_message(KEY, body(), sleep=lambda s: None)+++def test_a_refusal_comes_back_as_a_reply_with_its_details(server):+ server.script.append(("sse", 200, {}, events(text="", stop="refusal",+ details={"type": "refusal", "category": "cyber", "explanation": "x"})))+ reply = api.stream_message(KEY, body(), sleep=lambda s: None)+ assert reply.stop_reason == "refusal" and reply.stop_details["category"] == "cyber"+++def test_message_batches(server):+ server.script.append(("json", 200, {}, {"id": "msgbatch_01", "processing_status": "in_progress"}))+ batch = api.submit_batch(KEY, [("c1-gen1", body()), ("c2-gen1", body("medium"))], sleep=lambda s: None)+ sent = server.asked[0]+ assert sent["path"] == "/v1/messages/batches"+ assert [r["custom_id"] for r in sent["body"]["requests"]] == ["c1-gen1", "c2-gen1"]+ assert all("stream" not in r["params"] for r in sent["body"]["requests"])+ results_url = api.API_BASE + "/messages/batches/msgbatch_01/results"+ server.script.append(("json", 200, {}, {"id": "msgbatch_01", "processing_status": "ended", "results_url": results_url}))+ status = api.get_batch(KEY, batch["id"], sleep=lambda s: None)+ message = {"id": "msg_b1", "model": api.MODEL, "stop_reason": "end_turn", "content": [+ {"type": "thinking", "thinking": "rows", "signature": "x"}, {"type": "text", "text": "```pixels\n```"}],+ "usage": {"input_tokens": 500, "output_tokens": 9000}}+ lines = [{"custom_id": "c1-gen1", "result": {"type": "succeeded", "message": message}},+ {"custom_id": "c2-gen1", "result": {"type": "errored", "error": {"type": "error", "error": {+ "type": "invalid_request_error", "message": "nope"}}}},+ {"custom_id": "c3-gen1", "result": {"type": "expired"}}]+ server.script.append(("raw", 200, {}, "\n".join(json.dumps(l) for l in lines).encode() + b"\n"))+ results = api.batch_results(KEY, status, sleep=lambda s: None)+ assert server.asked[-1]["path"] == "/v1/messages/batches/msgbatch_01/results"+ ok = results["c1-gen1"]+ assert (ok.text, ok.thinking, ok.mode, ok.batch_id, ok.message_id) == ("```pixels\n```", "rows", "batch", "msgbatch_01", "msg_b1")+ assert isinstance(results["c2-gen1"], api.ApiError) and "code=invalid_request_error" in results["c2-gen1"].line+ assert results["c2-gen1"].billed is False and "expired" in results["c3-gen1"].line+++def test_price_of_a_call():+ usage = {"input_tokens": 509, "output_tokens": 8294, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0,+ "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 0}}+ assert api.cost_usd(usage, batch=False) == 0.167916 # 509 x $4 + 8294 x $20 per million+ assert api.cost_usd(usage, batch=True) == 0.083958+ cached = {"input_tokens": 0, "output_tokens": 0, "cache_read_input_tokens": 1_000_000,+ "cache_creation": {"ephemeral_5m_input_tokens": 1_000_000, "ephemeral_1h_input_tokens": 1_000_000}}+ assert api.cost_usd(cached, batch=False) == pytest.approx(0.20 + 5.00 + 8.00)+++def test_credential():+ with pytest.raises(SystemExit, match="ANTHROPIC_API_KEY is not set"):+ api.resolve_credential({})+ with pytest.raises(SystemExit, match="set but empty"):+ api.resolve_credential({"ANTHROPIC_API_KEY": " "})+ assert api.resolve_credential({"ANTHROPIC_API_KEY": KEY}) == KEYdiff --git a/tests/gen/test_pixel_draw.py b/tests/gen/test_pixel_draw.pynew file mode 100644index 0000000..919ce73--- /dev/null+++ b/tests/gen/test_pixel_draw.py@@ -0,0 +1,536 @@+# SPDX-License-Identifier: Apache-2.0+"""`sprite-gen pixel-draw` end to end against a fake Claude at the transport seam: what is asked+and in what order, the row repair, the one redraw (G1 still broken, or no answer at max_tokens one+effort lower), refusals and failed calls reported as they came, the G7 pick, Message Batches and+`--resume`, the run folder and its report, and `--grid`. No key, no network: the answers are the+model's own recorded ones (tests/fixtures/pixel_draw)."""+from __future__ import annotations++import base64+import io+import json+from dataclasses import replace+from pathlib import Path++import pytest+from PIL import Image++from conftest import help_options+from sprite_gen.gen import anthropic_api as api+from sprite_gen.gen import pixel_draw, refusal+from sprite_gen.gen import pixel_grid as pg+from sprite_gen.gen.anthropic_api import ApiError, Reply++KEY = "sk-ant-api03-" + "Synthetic0Key1For2Tests" * 2+FIXTURES = Path(__file__).resolve().parents[1] / "fixtures" / "pixel_draw"+++def fixture(name: str) -> str:+ return (FIXTURES / name).read_text(encoding="utf-8")+++SPRITE16 = fixture("sprite-16-pass.txt")+ICON32 = fixture("icon-32-pass.txt")+ICON_ROW = fixture("icon-32-row-width.txt")+ICON_ROW_FIX = fixture("icon-32-row-width.repair.txt")+TILE_CUT = fixture("tile-32-truncated.txt")+TILE_CUT_FIX = fixture("tile-32-truncated.repair.txt")+WALK16 = fixture("walk-16-pass.txt")+FOURDIR16 = fixture("fourdir-16-pass.txt")+VERDICT = fixture("pick-verdict.json") # best: "A"+++def tile_text(size: int) -> str:+ return "```pixels\nPALETTE\n. transparent\ng #4e9038\nFRAME tile\n" + "\n".join(["g" * size] * size) + "\nEND\n```"+++def reply(text: str, *, stop: str = "end_turn", output: int = 1200, thinking: int = 1000, details=None) -> Reply:+ return Reply(text=text, thinking="summary", stop_reason=stop, stop_details=details, model=api.MODEL,+ usage={"input_tokens": 500, "output_tokens": output, "output_tokens_details": {"thinking_tokens": thinking},+ "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0},+ message_id="msg_x", seconds=1.5)+++class FakeClaude:+ """Answers by call id (realtime: the label names it; batches: the custom_id)."""++ def __init__(self, script, polls=None, known=None):+ self.script = dict(script)+ self.asked: list[tuple[str, dict]] = []+ self.submitted: list[tuple[str, list]] = []+ self.polls = dict(polls or {})+ self.batch_ids = dict(known or {})++ def stream(self, token, body, *, sleep, label, timeout=None):+ assert token == KEY+ call_id = label.split()[-1]+ self.asked.append((call_id, body))+ if call_id not in self.script:+ pytest.fail(f"unexpected call {call_id}")+ outcome = self.script[call_id]+ if isinstance(outcome, ApiError):+ raise outcome+ return replace(outcome, request_id=f"req_{call_id}")++ def submit(self, token, requests, *, sleep, label):+ batch_id = f"msgbatch_{len(self.submitted) + 1}"+ self.submitted.append((batch_id, requests))+ self.batch_ids[batch_id] = [cid for cid, _ in requests]+ return {"id": batch_id, "processing_status": "in_progress"}++ def get(self, token, batch_id, *, sleep, label):+ states = self.polls.setdefault(batch_id, ["ended"])+ state = states.pop(0) if len(states) > 1 else states[0]+ return {"id": batch_id, "processing_status": state, "results_url": f"https://results.invalid/{batch_id}",+ "ended_at": "2026-10-12T00:00:00Z" if state == "ended" else None}++ def results(self, token, batch, *, sleep, label):+ return {cid: replace(self.script[cid], mode="batch", batch_id=batch["id"], seconds=None)+ for cid in self.batch_ids[batch["id"]]}+++def claude(monkeypatch):+ monkeypatch.setenv("ANTHROPIC_API_KEY", KEY)+ monkeypatch.setattr(pixel_draw, "BATCH_POLL_SECONDS", 0)++ def make(script, **kwargs) -> FakeClaude:+ fake = FakeClaude(script, **kwargs)+ monkeypatch.setattr(api, "stream_message", fake.stream)+ monkeypatch.setattr(api, "submit_batch", fake.submit)+ monkeypatch.setattr(api, "get_batch", fake.get)+ monkeypatch.setattr(api, "batch_results", fake.results)+ return fake++ return make+++def draw(out: Path, *args: str) -> int:+ return pixel_draw.main(["--out-dir", str(out), *args])+++def report_of(out: Path) -> dict:+ return json.loads((out / "report.json").read_text(encoding="utf-8"))+++def asked(fake: FakeClaude) -> list[str]:+ return [call_id for call_id, _ in fake.asked]+++def test_one_candidate_is_drawn_checked_and_written(tmp_path, claude, capsys):+ fake = claude({"c1-gen1": reply(SPRITE16, output=2515, thinking=2300)})+ out = tmp_path / "run"+ assert draw(out, "--subject", "a knight", "--size", "16", "--frames", "front", "--candidates", "1") == 0+ report = report_of(out)+ captured = capsys.readouterr()+ assert json.loads(captured.out) == report+ assert "[gen] claude: running on ANTHROPIC_API_KEY — this is a per-call API charge" in captured.err+ assert report["status"] == "ok" and report["chosen"] == "c1" and report["pick"] == {"by": "only", "best": "c1"}+ assert sorted(p.name for p in out.iterdir()) == sorted([+ "report.json", "request.json", "calls", "candidates", "grid.txt", "palette.json", "frame-front.png",+ "preview-x16.png"])+ assert report["files"] == {"grid": "grid.txt", "palette": "palette.json", "frames": {"front": "frame-front.png"},+ "preview": "preview-x16.png"}+ (call,) = report["calls"]+ assert {k: call[k] for k in ("id", "purpose", "candidate", "outcome", "mode", "model", "effort", "max_tokens",+ "request_id", "stop_reason", "thinking_tokens")} == {+ "id": "c1-gen1", "purpose": "generate", "candidate": "c1", "outcome": "reply", "mode": "realtime",+ "model": "claude-opus-5-5", "effort": "high", "max_tokens": 32000, "request_id": "req_c1-gen1",+ "stop_reason": "end_turn", "thinking_tokens": 2300}+ assert call["cost_usd"] == api.cost_usd(call["usage"], batch=False) == report["cost_usd"]+ assert report["usage"]["output_tokens"] == 2515 and report["usage"]["thinking_tokens"] == 2300+ assert report["seconds"] >= 0+ (candidate,) = report["candidates"]+ assert candidate["status"] == "passed" and candidate["G1"] == {"ok": True, "issues": [], "recovered": []}+ assert candidate["gates"]["ok"] and candidate["files"]["grid"] == "candidates/c1/grid.txt"+ grid, _ = pg.parse_answer(SPRITE16, "chargrid", 16, 16, ("front",))+ assert (out / "grid.txt").read_text(encoding="utf-8") == pg.to_text(grid)+ assert (out / "frame-front.png").read_bytes() == pg.png_bytes(pg.frame_pixels(grid, "front"))+ assert (out / "frame-front.png").read_bytes() == (out / "candidates" / "c1" / "frame-front.png").read_bytes()+ record = json.loads((out / "calls" / "c1-gen1.json").read_text(encoding="utf-8"))+ assert record["reply"]["text"] == SPRITE16 and record["prompt"].startswith("Draw: a knight\nCanvas: exactly 16x16")+ body = fake.asked[0][1]+ assert body["model"] == "claude-opus-5-5" and body["system"] == pixel_draw.SYSTEM+ assert body["thinking"] == {"type": "adaptive", "display": "summarized"} and body["output_config"] == {"effort": "high"}+ request = json.loads((out / "request.json").read_text(encoding="utf-8"))+ assert request["palette"] == {"name": "free:16", "limit": 16, "colors": []} and request["frames"] == ["front"]+++def test_a_broken_row_is_asked_for_alone_and_spliced(tmp_path, claude):+ fake = claude({"c1-gen1": reply(ICON_ROW), "c1-gen1-fix1": reply(ICON_ROW_FIX, output=336, thinking=318)})+ out = tmp_path / "run"+ assert draw(out, "--subject", "a wooden chest", "--kind", "icon", "--candidates", "1") == 0+ assert asked(fake) == ["c1-gen1", "c1-gen1-fix1"]+ (candidate,) = report_of(out)["candidates"]+ assert candidate["repairs"] == [{"call": "c1-gen1-fix1", "rows_asked": ["icon 16"], "rows_answered": ["icon 16"],+ "ignored": [], "rows_still_broken": []}]+ assert candidate["G1"]["ok"] and candidate["generations"] == ["c1-gen1"]+ body = fake.asked[1][1]+ assert body["output_config"] == {"effort": "medium"} and body["max_tokens"] == 16000+ prompt = body["messages"][0]["content"]+ lines = prompt.splitlines()+ broken = next(line for line in lines if "BROKEN" in line)+ assert broken == " row 16 (BROKEN, 33 characters): .ooooooooooooGGooGgooooooooooooo."+ ruler = lines[lines.index(broken) + 1]+ assert ruler.startswith(" ruler") and ruler.index("123456789") == broken.index(".oooo")+ assert "Rows to write: icon 16" in prompt and "`ROW <frame> <row number>: <exactly 32 characters>`" in prompt+ rows = (out / "grid.txt").read_text(encoding="utf-8").splitlines()+ assert rows[rows.index("FRAME icon") + 16] == ".ooooooooooooGGooGgoooooooooooo."+++def test_a_row_left_broken_goes_back_in_a_second_round(tmp_path, claude):+ row25 = "ggggggggggggggdkdggggggggggggggg"+ fake = claude({"c1-gen1": reply(TILE_CUT), "c1-gen1-fix1": reply(TILE_CUT_FIX),+ "c1-gen1-fix2": reply(f"ROW tile 25: {row25}")})+ out = tmp_path / "run"+ assert draw(out, "--subject", "grass", "--kind", "tile", "--candidates", "1") == 0+ (candidate,) = report_of(out)["candidates"]+ first, second = candidate["repairs"]+ assert first["rows_asked"] == [f"tile {n}" for n in range(16, 33)] and first["rows_still_broken"] == ["tile 25"]+ assert second["rows_asked"] == ["tile 25"] and second["rows_still_broken"] == []+ assert candidate["G1"] == {"ok": True, "issues": [], "recovered": [{"code": "no_end"}]}+ assert "rows 17-32 are MISSING" in fake.asked[1][1]["messages"][0]["content"]+ assert (out / "tiled-3x3.png").is_file()+++def test_still_broken_after_two_rounds_is_drawn_once_more(tmp_path, claude, capsys):+ fake = claude({"c1-gen1": reply(TILE_CUT), "c1-gen1-fix1": reply(TILE_CUT_FIX),+ "c1-gen1-fix2": reply("ROW tile 25: " + "g" * 33), "c1-gen2": reply(tile_text(32))})+ out = tmp_path / "run"+ assert draw(out, "--subject", "grass", "--kind", "tile", "--candidates", "1") == 0+ assert asked(fake) == ["c1-gen1", "c1-gen1-fix1", "c1-gen1-fix2", "c1-gen2"]+ (candidate,) = report_of(out)["candidates"]+ assert candidate["generations"] == ["c1-gen1", "c1-gen2"]+ assert candidate["redraws"] == [{"after": "c1-gen1", "why": "G1", "effort": "high"}]+ assert candidate["status"] == "passed" and "drawing c1 once more" in capsys.readouterr().err+++def test_a_structural_failure_is_drawn_again_without_repair_and_a_second_one_ends_it(tmp_path, claude):+ broken = FOURDIR16.replace("FRAME up\n", "")+ fake = claude({"c1-gen1": reply(broken), "c1-gen2": reply(broken)})+ out = tmp_path / "run"+ with pytest.raises(SystemExit) as caught:+ draw(out, "--subject", "a knight", "--size", "16", "--frames", "down,up,left,right", "--candidates", "1")+ assert "no candidate passed the gates (c1: G1: frame_missing up, row_count_over down)" in str(caught.value)+ assert asked(fake) == ["c1-gen1", "c1-gen2"]+ report = report_of(out)+ assert report["status"] == "failed" and report["candidates"][0]["files"] == {}+ assert report["chosen"] is None and not (out / "grid.txt").exists()+++def test_no_answer_at_max_tokens_is_drawn_once_more_one_effort_lower(tmp_path, claude, capsys):+ fake = claude({"c1-gen1": reply("", stop="max_tokens", output=32000, thinking=32000), "c1-gen2": reply(SPRITE16)})+ out = tmp_path / "run"+ assert draw(out, "--subject", "a knight", "--size", "16", "--frames", "front", "--candidates", "1",+ "--effort", "xhigh") == 0+ assert [body["output_config"]["effort"] for _, body in fake.asked] == ["xhigh", "high"]+ report = report_of(out)+ (candidate,) = report["candidates"]+ assert candidate["redraws"] == [{"after": "c1-gen1", "why": "max_tokens", "effort": "high"}]+ assert candidate["effort"] == "high" and candidate["status"] == "passed"+ assert report["cost_usd"] == pytest.approx(sum(c["cost_usd"] for c in report["calls"]))+ assert "drawing c1 once more at effort high" in capsys.readouterr().err+++def test_an_answer_cut_off_at_max_tokens_keeps_its_rows_and_is_repaired(tmp_path, claude):+ rows = SPRITE16.split("FRAME front\n")[1].split("\nEND")[0].splitlines()+ cut = SPRITE16[:SPRITE16.index("FRAME front\n")] + "FRAME front\n" + "\n".join(rows[:10])+ fix = "\n".join(f"ROW front {n}: {rows[n - 1]}" for n in range(11, 17))+ fake = claude({"c1-gen1": reply(cut, stop="max_tokens", output=32000, thinking=31000), "c1-gen1-fix1": reply(fix)})+ out = tmp_path / "run"+ assert draw(out, "--subject", "a knight", "--size", "16", "--frames", "front", "--candidates", "1") == 0+ assert asked(fake) == ["c1-gen1", "c1-gen1-fix1"]+ (candidate,) = report_of(out)["candidates"]+ assert candidate["redraws"] == [] and candidate["repairs"][0]["rows_asked"] == [f"front {n}" for n in range(11, 17)]+ assert [r["code"] for r in candidate["G1"]["recovered"]] == ["block_unclosed", "no_end"]+ grid, _ = pg.parse_answer(SPRITE16, "chargrid", 16, 16, ("front",))+ assert (out / "grid.txt").read_text(encoding="utf-8") == pg.to_text(grid)+++def test_no_answer_twice_ends_the_candidate(tmp_path, claude):+ empty = reply("", stop="max_tokens", output=32000, thinking=32000)+ fake = claude({"c1-gen1": empty, "c1-gen2": empty})+ out = tmp_path / "run"+ with pytest.raises(SystemExit) as caught:+ draw(out, "--subject", "stones", "--kind", "tile", "--candidates", "1", "--effort", "medium")+ assert "c1: max_tokens: c1-gen2 used all 32000 tokens at effort low and wrote nothing" in str(caught.value)+ assert [body["output_config"]["effort"] for _, body in fake.asked] == ["medium", "low"]+++def test_a_candidate_is_drawn_twice_at_most(tmp_path, claude):+ fake = claude({"c1-gen1": reply("", stop="max_tokens"), "c1-gen2": reply("no grid here")})+ with pytest.raises(SystemExit, match=r"c1: G1: no_block"):+ draw(tmp_path / "run", "--subject", "a knight", "--candidates", "1")+ assert asked(fake) == ["c1-gen1", "c1-gen2"]+++def test_a_refusal_is_reported_as_it_came(tmp_path, claude):+ fake = claude({"c1-gen1": reply("", stop="refusal", details={"type": "refusal", "category": "cyber", "explanation": "x"})})+ out = tmp_path / "run"+ with pytest.raises(SystemExit) as caught:+ draw(out, "--subject", "something", "--candidates", "1")+ assert str(caught.value).startswith(+ f"pixel-draw: {refusal.CONTENT_POLICY} (stop_reason=refusal category=cyber); every candidate was refused")+ assert asked(fake) == ["c1-gen1"]+ report = report_of(out)+ assert report["status"] == "refused" and report["candidates"][0]["status"] == "refused"+++def test_a_failed_call_is_not_asked_again(tmp_path, claude):+ error = ApiError("pixel-draw: claude request failed (HTTP 400) code=invalid_request_error; not asked again",+ status=400, request_id="req_400", billed=False)+ fake = claude({"c1-gen1": error})+ out = tmp_path / "run"+ with pytest.raises(SystemExit, match=r"c1: pixel-draw: claude request failed \(HTTP 400\)"):+ draw(out, "--subject", "a knight", "--candidates", "1")+ assert asked(fake) == ["c1-gen1"]+ (call,) = report_of(out)["calls"]+ assert call["outcome"] == "error" and call["request_id"] == "req_400" and call["cost_usd"] == 0.0+ assert call["error"] == error.line and call["billed"] is False+++def test_the_vision_pick_chooses_between_two_that_passed(tmp_path, claude):+ variant = SPRITE16.replace("r #d84040", "r #c03030")+ fake = claude({"c1-gen1": reply(SPRITE16), "c2-gen1": reply(variant), "pick": reply(VERDICT, output=300, thinking=90)})+ out = tmp_path / "run"+ assert draw(out, "--subject", "a knight", "--size", "16", "--frames", "front") == 0+ report = report_of(out)+ pick = report["pick"]+ assert pick["by"] == "vision" and sorted(pick["labels"]) == ["A", "B"] and sorted(pick["labels"].values()) == ["c1", "c2"]+ assert pick["best"] == pick["labels"]["A"] == report["chosen"] and pick["verdict"]["best"] == "A"+ body = dict(fake.asked)["pick"]+ image, text = body["messages"][0]["content"]+ assert image["source"]["media_type"] == "image/png"+ assert base64.standard_b64decode(image["source"]["data"]) == (out / "pick-sheet.png").read_bytes()+ assert text["text"].startswith("You are judging pixel-art game assets") and "candidates labelled A, B" in text["text"]+ assert body["output_config"] == {"effort": "low", "format": {"type": "json_schema", "schema": pixel_draw.PICK_SCHEMA}}+ assert "system" not in body+ chosen = out / "candidates" / report["chosen"]+ assert (out / "grid.txt").read_bytes() == (chosen / "grid.txt").read_bytes()+ assert (out / "frame-front.png").read_bytes() == (chosen / "frame-front.png").read_bytes()+ assert [c["id"] for c in report["calls"]] == ["c1-gen1", "c2-gen1", "pick"]+++def test_a_person_picks_when_asked(tmp_path, claude):+ fake = claude({"c1-gen1": reply(SPRITE16), "c2-gen1": reply(SPRITE16.replace("r #d84040", "r #c03030"))})+ out = tmp_path / "run"+ assert draw(out, "--subject", "a knight", "--size", "16", "--frames", "front", "--pick", "human") == 0+ report = report_of(out)+ assert report["pick"] == {"by": "human", "best": None, "candidates": ["c1", "c2"]}+ assert report["status"] == "ok" and report["chosen"] is None and not (out / "grid.txt").exists()+ assert "pick" not in asked(fake)+++def test_a_pick_that_names_no_candidate_fails_the_run(tmp_path, claude):+ verdict = json.loads(VERDICT)+ verdict["best"] = "Z"+ claude({"c1-gen1": reply(SPRITE16), "c2-gen1": reply(SPRITE16.replace("r #d84040", "r #c03030")),+ "pick": reply(json.dumps(verdict))})+ out = tmp_path / "run"+ with pytest.raises(SystemExit, match=r"2 candidates passed but the pick failed \(the pick named 'Z', not one of A, B\)"):+ draw(out, "--subject", "a knight", "--size", "16", "--frames", "front")+ assert report_of(out)["status"] == "pick_failed" and not (out / "grid.txt").exists()+++def test_one_that_passed_alone_is_the_pick(tmp_path, claude):+ fake = claude({"c1-gen1": reply(SPRITE16), "c2-gen1": reply(""), "c2-gen2": reply("")})+ out = tmp_path / "run"+ assert draw(out, "--subject", "a knight", "--size", "16", "--frames", "front") == 0+ report = report_of(out)+ assert report["pick"] == {"by": "only", "best": "c1"} and "pick" not in asked(fake)+ assert [c["status"] for c in report["candidates"]] == ["passed", "failed"]+++def test_batches_draw_at_half_price_and_repairs_stay_realtime(tmp_path, claude):+ fake = claude({"c1-gen1": reply(ICON_ROW), "c2-gen1": reply(""), "c1-gen1-fix1": reply(ICON_ROW_FIX),+ "c2-gen2": reply(ICON32), "pick": reply(VERDICT)},+ polls={"msgbatch_1": ["in_progress", "ended"]})+ out = tmp_path / "run"+ assert draw(out, "--subject", "a chest", "--kind", "icon", "--batch") == 0+ assert [(b, [cid for cid, _ in requests]) for b, requests in fake.submitted] == [+ ("msgbatch_1", ["c1-gen1", "c2-gen1"]), ("msgbatch_2", ["c2-gen2"])]+ assert all("stream" not in params for _, requests in fake.submitted for _, params in requests)+ assert asked(fake) == ["c1-gen1-fix1", "pick"]+ report = report_of(out)+ calls = {c["id"]: c for c in report["calls"]}+ assert calls["c1-gen1"]["mode"] == "batch" and calls["c1-gen1"]["batch_id"] == "msgbatch_1"+ assert calls["c1-gen1"]["cost_usd"] == api.cost_usd(calls["c1-gen1"]["usage"], batch=True)+ assert calls["c1-gen1-fix1"]["mode"] == "realtime"+ assert [(b["id"], b["collected"]) for b in report["batches"]] == [("msgbatch_1", True), ("msgbatch_2", True)]+++def test_a_batch_cut_short_is_collected_on_resume_and_not_bought_twice(tmp_path, claude):+ script = {"c1-gen1": reply(SPRITE16)}+ claude(script, polls={"msgbatch_1": ["in_progress"]})+ out = tmp_path / "run"+ with pytest.raises(SystemExit) as caught:+ draw(out, "--subject", "a knight", "--size", "16", "--frames", "front", "--candidates", "1", "--batch",+ "--batch-wait", "0")+ message = str(caught.value)+ assert "batch msgbatch_1 has not ended after 0s; nothing is asked twice" in message+ assert f"`sprite-gen pixel-draw --out-dir {out.resolve()} --resume`" in message+ report = report_of(out)+ assert report["status"] == "unfinished" and report["unfinished"]["batch_id"] == "msgbatch_1"+ record = json.loads((out / "batches" / "msgbatch_1.json").read_text(encoding="utf-8"))+ assert record["collected"] is False and record["custom_ids"] == ["c1-gen1"]+ second = claude(script, known={"msgbatch_1": ["c1-gen1"]})+ assert pixel_draw.main(["--out-dir", str(out), "--resume"]) == 0+ assert second.submitted == [] and second.asked == []+ report = report_of(out)+ assert report["status"] == "ok" and report["batches"][0]["collected"] is True+++def test_resume_reads_answered_calls_back(tmp_path, claude):+ claude({"c1-gen1": reply(ICON_ROW), "c1-gen1-fix1": reply(ICON_ROW_FIX)})+ out = tmp_path / "run"+ assert draw(out, "--subject", "a chest", "--kind", "icon", "--candidates", "1") == 0+ before = {name: (out / name).read_bytes() for name in ("grid.txt", "frame-icon.png")}+ again = claude({})+ assert pixel_draw.main(["--out-dir", str(out), "--resume"]) == 0+ assert again.asked == [] and {name: (out / name).read_bytes() for name in before} == before+ assert [c["id"] for c in report_of(out)["calls"]] == ["c1-gen1", "c1-gen1-fix1"]+++def test_resume_takes_the_request_from_the_run(tmp_path, claude):+ claude({"c1-gen1": reply(SPRITE16)})+ out = tmp_path / "run"+ assert draw(out, "--subject", "a knight", "--size", "16", "--frames", "front", "--candidates", "1") == 0+ with pytest.raises(SystemExit, match=r"--resume reads the request from .*request.json; drop --size"):+ pixel_draw.main(["--out-dir", str(out), "--resume", "--size", "16"])+ request = json.loads((out / "request.json").read_text(encoding="utf-8"))+ (out / "request.json").write_text(json.dumps({**request, "subject": "a wizard"}), encoding="utf-8")+ with pytest.raises(SystemExit, match="was asked with another request"):+ pixel_draw.main(["--out-dir", str(out), "--resume"])+++def test_a_used_folder_is_refused(tmp_path, claude):+ out = tmp_path / "run"+ out.mkdir()+ (out / "notes.txt").write_text("mine", encoding="utf-8")+ claude({})+ with pytest.raises(SystemExit, match="exists and is not an empty folder"):+ draw(out, "--subject", "a knight")++[email protected]("args,message", [+ (["--size", "7"], "--size is 8..48 pixels, got 7"),+ (["--size", "49"], "--size is 8..48 pixels, got 49"),+ (["--frames", "a,b,c,d,e"], "at most 4 frames in one call, got 5"),+ (["--frames", "a b"], "frame names are letters, digits"),+ (["--frames", "a,a"], "frame names must differ"),+ (["--frames", "a,b", "--walk-cycle"], "--walk-cycle is four frames"),+ (["--candidates", "0"], "--candidates is 1..6, got 0"),+ (["--candidates", "7"], "--candidates is 1..6, got 7"),+ (["--max-tokens", "100"], "--max-tokens is 1024..128000, got 100"),+ (["--max-tokens", "200000"], "--max-tokens is 1024..128000, got 200000"),+ (["--palette", "free:99"], "free:N takes 1..62 colours"),+])+def test_requests_refused_before_anything_is_asked(tmp_path, claude, args, message):+ fake = claude({})+ out = tmp_path / "run"+ with pytest.raises(SystemExit) as caught:+ draw(out, "--subject", "a knight", *args)+ assert message in str(caught.value) and fake.asked == [] and not out.exists()+++def test_a_spec_file_holds_the_drawing(tmp_path, claude):+ spec = tmp_path / "spec.json"+ spec.write_text(json.dumps({"subject": "a slime", "size": 16, "frames": ["front"], "palette": ["#112233", "#445566"]}),+ encoding="utf-8")+ claude({})+ with pytest.raises(SystemExit, match=r"--size given both as a flag and in --spec"):+ draw(tmp_path / "a", "--spec", str(spec), "--size", "16")+ bad = tmp_path / "bad.json"+ bad.write_text(json.dumps({"subject": "x", "effort": "high"}), encoding="utf-8")+ with pytest.raises(SystemExit, match=r"unknown key\(s\) effort"):+ draw(tmp_path / "b", "--spec", str(bad))+ with pytest.raises(SystemExit, match="nothing to draw"):+ draw(tmp_path / "c")+ two_colors = "```pixels\nPALETTE\n. transparent\na #112233\nb #445566\nFRAME front\n" + "\n".join(+ ["." * 16] + [".." + "ab" * 6 + ".."] * 14 + ["." * 16]) + "\nEND\n```"+ fake = claude({"c1-gen1": reply(two_colors)})+ assert draw(tmp_path / "d", "--spec", str(spec), "--candidates", "1") == 0+ prompt = fake.asked[0][1]["messages"][0]["content"]+ assert "Palette: use only these 2 colors and transparent, no others: #112233 #445566." in prompt+ assert report_of(tmp_path / "d")["candidates"][0]["gates"]["G2"]["ok"]+++def test_a_json_answer_is_kept_as_a_chargrid(tmp_path, claude):+ fake = claude({"c1-gen1": reply(fixture("icon-16-json-pass.txt"))})+ out = tmp_path / "run"+ assert draw(out, "--subject", "a potion", "--kind", "icon", "--size", "16", "--format", "json", "--candidates", "1") == 0+ assert '{"palette": ["transparent", "#RRGGBB", ...]' in fake.asked[0][1]["messages"][0]["content"]+ lines = (out / "grid.txt").read_text(encoding="utf-8").splitlines()+ assert lines[:3] == ["PALETTE", ". transparent", "a #2b1b2e"]+ with Image.open(out / "frame-icon.png") as image:+ assert image.getpixel((5, 1)) == (0x2B, 0x1B, 0x2E, 255)+++def test_a_walk_cycle_is_one_call_of_four_frames(tmp_path, claude):+ fake = claude({"c1-gen1": reply(WALK16)})+ out = tmp_path / "run"+ assert draw(out, "--subject", "a knight walking right", "--size", "16", "--frames", "walk1,walk2,walk3,walk4",+ "--walk-cycle", "--candidates", "1") == 0+ body = fake.asked[0][1]+ assert body["max_tokens"] == 64000+ assert ("The frames are one looping walk cycle: walk1 = contact pose with the front leg forward"+ in body["messages"][0]["content"])+ report = report_of(out)+ assert any(w.startswith("G6 weak leg alternation") for w in report["warnings"])+ assert report["files"]["gif"] == "anim.gif"+ with Image.open(out / "anim.gif") as gif:+ assert gif.n_frames == 4+ with Image.open(out / "preview-x16.png") as preview:+ assert preview.size == (4 * 256 + 3 * 32, 256)+++def test_prompts_say_the_kind_and_the_format():+ def request(**changes):+ base = dict(subject="grass", size=32, kind="tile", frames=("tile",), walk_cycle=False,+ palette=pg.palette_rule("free:8"), candidates=1, effort="high", answer_format="chargrid",+ batch=False, max_tokens=32000, pick="vision")+ return pixel_draw.PixelRequest(**{**base, **changes})+ tile = pixel_draw.generation_prompt(request())+ assert "This is a tile: fill every pixel (no transparency) and make it repeat seamlessly" in tile+ assert "Palette: at most 8 colors plus transparent." in tile and "Background: transparent" not in tile+ assert "```pixels\nPALETTE\n. transparent" in tile and "exactly 32 lines of exactly 32 characters" in tile+ sprite = pixel_draw.generation_prompt(request(kind="sprite", frames=("down", "up"), subject="a knight"))+ assert "the feet stand on the same bottom row in every frame." in sprite and "Background: transparent." in sprite+ assert "Frames in this order: down, up." in sprite+++def test_an_edited_grid_is_checked_and_rendered_without_a_call(tmp_path, claude, monkeypatch):+ claude({"c1-gen1": reply(SPRITE16)})+ first = tmp_path / "first"+ assert draw(first, "--subject", "a knight", "--size", "16", "--frames", "front", "--candidates", "1") == 0+ monkeypatch.delenv("ANTHROPIC_API_KEY")+ edited = tmp_path / "edited.txt"+ edited.write_text((first / "grid.txt").read_text(encoding="utf-8").replace(+ "FRAME front\n......oooo......", "FRAME front\n......oooo....o."), encoding="utf-8")+ second = tmp_path / "second"+ assert pixel_draw.main(["--grid", str(edited), "--out-dir", str(second)]) == 0+ report = report_of(second)+ assert report["source"] == "grid" and report["calls"] == [] and report["cost_usd"] == 0.0+ assert report["status"] == "ok" and report["warnings"] == ["G5 1 stray pixel(s) with no opaque neighbour"]+ grid, issues = pg.read_grid_text(edited.read_text(encoding="utf-8"))+ assert (second / "frame-front.png").read_bytes() == pg.png_bytes(pg.frame_pixels(grid, "front"))+ broken = tmp_path / "broken.txt"+ broken.write_text(edited.read_text(encoding="utf-8").replace("......oooo....o.\n", "......oooo....o\n"), encoding="utf-8")+ with pytest.raises(SystemExit, match=r"does not parse whole: row_width front row 1"):+ pixel_draw.main(["--grid", str(broken), "--out-dir", str(tmp_path / "third")])+ with pytest.raises(SystemExit, match=r"--grid checks and renders a grid as it is; drop --candidates"):+ pixel_draw.main(["--grid", str(edited), "--out-dir", str(tmp_path / "fourth"), "--candidates", "2"])+++def test_no_key_is_refused_before_the_folder_is_made(tmp_path, monkeypatch):+ monkeypatch.delenv("ANTHROPIC_API_KEY", raising=False)+ out = tmp_path / "run"+ with pytest.raises(SystemExit, match="ANTHROPIC_API_KEY is not set"):+ draw(out, "--subject", "a knight")+ assert not out.exists()+++def test_the_cli_names_the_verb_and_its_flags():+ flags = help_options("-m", "sprite_gen.cli", "pixel-draw")+ assert {"--subject", "--spec", "--grid", "--size", "--kind", "--frames", "--walk-cycle", "--palette", "--candidates",+ "--effort", "--format", "--batch", "--batch-wait", "--max-tokens", "--pick", "--out-dir", "--resume"} <= flagsdiff --git a/tests/gen/test_pixel_gates.py b/tests/gen/test_pixel_gates.pynew file mode 100644index 0000000..55f5161--- /dev/null+++ b/tests/gen/test_pixel_gates.py@@ -0,0 +1,110 @@+# SPDX-License-Identifier: Apache-2.0+"""Gates G2..G6 of `pixel-draw` on recorded answers (tests/fixtures/pixel_draw) and on grids made+to break exactly one rule. G2, G3 and G6 fail a candidate; G4, G5 and the walk check only warn."""+from __future__ import annotations++from pathlib import Path++import pytest++from sprite_gen.gen import pixel_grid as pg+from sprite_gen.gen.pixel_gates import evaluate, g6_frames, seam_ratio++FIXTURES = Path(__file__).resolve().parents[1] / "fixtures" / "pixel_draw"+WALK = ("walk1", "walk2", "walk3", "walk4")+FOURDIR = ("down", "up", "left", "right")+FREE16 = pg.palette_rule("free")++INK, SKIN, GRASS, MOSS = (40, 30, 46, 255), (240, 192, 152, 255), (78, 144, 56, 255), (92, 158, 66, 255)+CLEAR = (0, 0, 0, 0)+++def frames_of(name: str, size: int, frames: tuple[str, ...]):+ grid, issues = pg.parse_answer((FIXTURES / name).read_text(encoding="utf-8"), "chargrid", size, size, frames)+ assert issues == []+ return {f: pg.frame_pixels(grid, f) for f in frames}+++def blob(size: int = 8, top: int = 2, bottom: int = 5, fill=INK):+ """A transparent square with an opaque block rows top..bottom, columns 2..size-3."""+ return [[fill if top <= y <= bottom and 2 <= x <= size - 3 else CLEAR for x in range(size)] for y in range(size)]+++def test_recorded_sprite_passes_every_gate():+ gates = evaluate(frames_of("sprite-16-pass.txt", 16, ("front",)), kind="sprite", rule=FREE16, walk_cycle=False)+ assert gates["ok"] and gates["failed"] == [] and gates["warnings"] == []+ assert gates["G2"]["colors_used"] <= 16+ assert gates["G3"]["frames"]["front"]["corners_transparent"]+ assert gates["G5"]["isolated_pixels"] == 0 and "G6" not in gates and "G4" not in gates+++def test_recorded_tile_is_opaque_and_repeats():+ gates = evaluate(frames_of("tile-16-pass.txt", 16, ("tile",)), kind="tile", rule=FREE16, walk_cycle=False)+ assert gates["ok"] and gates["G3"]["frames"]["tile"]["opaque_fraction"] == 1.0+ assert gates["G4"]["seam_ratio"] <= 1.5 and not gates["G4"]["warn"]+++def test_g2_counts_colours_against_the_limit_and_the_fixed_set():+ frames = frames_of("sprite-16-pass.txt", 16, ("front",))+ used = evaluate(frames, kind="sprite", rule=FREE16, walk_cycle=False)["G2"]["colors_used"]+ few = evaluate(frames, kind="sprite", rule=pg.palette_rule("free:4"), walk_cycle=False)+ assert not few["ok"] and few["failed"] == ["G2"] and few["G2"]["colors_used"] == used+ pico = evaluate(frames, kind="sprite", rule=pg.palette_rule("pico8"), walk_cycle=False)+ assert not pico["ok"] and pico["G2"]["off_palette"]+ exact = pg.palette_rule(",".join(sorted({"#{:02X}{:02X}{:02X}".format(*p[:3])+ for row in frames["front"] for p in row if p[3]})))+ assert evaluate(frames, kind="sprite", rule=exact, walk_cycle=False)["G2"]["ok"]++[email protected]("frame,kind", [+ ([[INK] + [CLEAR] * 7] + [[CLEAR] * 8 for _ in range(7)], "sprite"), # an opaque corner+ ([[INK] * 8 for _ in range(3)] + blob()[3:], "icon"), # border mostly opaque+ ([[CLEAR] * 8 for _ in range(8)], "sprite"), # nothing drawn+ ([[GRASS] * 8 for _ in range(7)] + [[GRASS] * 7 + [CLEAR]], "tile"), # one hole in a tile+])+def test_g3_alpha_failures(frame, kind):+ gates = evaluate({"f": frame}, kind=kind, rule=FREE16, walk_cycle=False)+ assert not gates["ok"] and "G3" in gates["failed"]+++def test_g4_seam_only_warns():+ striped = [[GRASS if x < 2 or x >= 6 else MOSS for x in range(8)] for _ in range(8)] # wraps cleanly+ seam = [[GRASS if x < 7 else INK for x in range(8)] for _ in range(8)]+ assert seam_ratio(striped) <= 1.5+ gates = evaluate({"tile": seam}, kind="tile", rule=FREE16, walk_cycle=False)+ assert gates["G4"]["warn"] and gates["G4"]["seam_ratio"] > 1.5+ assert gates["ok"] and any(w.startswith("G4 tile seam") for w in gates["warnings"])+++def test_g5_stray_pixels_only_warn():+ frame = blob()+ frame[7][7] = CLEAR+ frame[0][4] = INK # a speck above the block, touching nothing+ gates = evaluate({"f": frame}, kind="sprite", rule=FREE16, walk_cycle=False)+ assert gates["G5"]["isolated_pixels"] == 1 and gates["ok"]+ assert gates["warnings"] == ["G5 1 stray pixel(s) with no opaque neighbour"]+++def test_recorded_four_directions_stand_on_one_line():+ gates = evaluate(frames_of("fourdir-16-pass.txt", 16, FOURDIR), kind="sprite", rule=FREE16, walk_cycle=False)+ assert gates["ok"] and gates["G6"]["ok"] and gates["G6"]["identical_pairs"] == []+ assert len(set(gates["G6"]["baselines"].values())) == 1 and "walk" not in gates["G6"]+++def test_recorded_walk_passes_with_the_weak_leg_warning():+ gates = evaluate(frames_of("walk-16-pass.txt", 16, WALK), kind="sprite", rule=FREE16, walk_cycle=True)+ g6 = gates["G6"]+ assert gates["ok"] and g6["ok"] and g6["height_spread"] == 1 # the passing pose is a pixel higher+ assert g6["walk"]["warn"] and g6["walk"]["ratio"] < 0.4+ assert any(w.startswith("G6 weak leg alternation") for w in gates["warnings"])+++def test_g6_failures():+ low, high, tall = blob(), blob(top=1, bottom=4), blob(top=0, bottom=5)+ assert not g6_frames({"a": low, "b": [row[:] for row in low]}, walk_cycle=False)["ok"] # the same frame twice+ shifted = g6_frames({"a": low, "b": high}, walk_cycle=False)+ assert not shifted["ok"] and shifted["baselines"] == {"a": 5, "b": 4}+ spread = g6_frames({"a": low, "b": [r[:] for r in tall]}, walk_cycle=False)+ assert spread["height_spread"] == 2 and not spread["ok"]+ gates = evaluate({"a": low, "b": [row[:] for row in low]}, kind="sprite", rule=FREE16, walk_cycle=False)+ assert gates["failed"] == ["G6"]diff --git a/tests/gen/test_pixel_grid.py b/tests/gen/test_pixel_grid.pynew file mode 100644index 0000000..987c0f2--- /dev/null+++ b/tests/gen/test_pixel_grid.py@@ -0,0 +1,248 @@+# SPDX-License-Identifier: Apache-2.0+"""The pixel grid of `pixel-draw`: both answer formats, the issues G1 tells apart, row splicing,+the canonical grid.txt, the palette rules and the byte-reproducible PNG.++The answers under tests/fixtures/pixel_draw are claude-opus-5-5's own, recorded 2026-10-12 from the+prompts this verb sends: six that parse whole, and the failure shapes it actually wrote — a row one+key too long, a Cyrillic 'о' for an 'o', a single frame with no FRAME line, output cut off at row+16 after a stray CJK character, spaces inside rows — with the row-repair answers it gave for four+of them (`*.repair.txt`).+"""+from __future__ import annotations++import io+import json+from pathlib import Path++import pytest+from PIL import Image++from sprite_gen.gen import pixel_grid as pg++FIXTURES = Path(__file__).resolve().parents[1] / "fixtures" / "pixel_draw"+WALK = ("walk1", "walk2", "walk3", "walk4")+FOURDIR = ("down", "up", "left", "right")+++def fixture(name: str) -> str:+ return (FIXTURES / name).read_text(encoding="utf-8")+++def codes(issues):+ return sorted({i.code for i in issues})+++PASSING = [+ ("sprite-16-pass.txt", "chargrid", 16, ("front",)),+ ("icon-32-pass.txt", "chargrid", 32, ("icon",)),+ ("tile-16-pass.txt", "chargrid", 16, ("tile",)),+ ("walk-16-pass.txt", "chargrid", 16, WALK),+ ("fourdir-16-pass.txt", "chargrid", 16, FOURDIR),+ ("icon-16-json-pass.txt", "json", 16, ("icon",)),+]++[email protected]("name,fmt,size,frames", PASSING)+def test_recorded_answers_that_parse_whole(name, fmt, size, frames):+ grid, issues = pg.parse_answer(fixture(name), fmt, size, size, frames)+ assert issues == []+ assert list(grid.frames) == list(frames)+ for rows in grid.frames.values():+ assert len(rows) == size and all(len(row) == size for row in rows)+++def test_a_row_one_key_too_long_is_a_row_issue():+ grid, issues = pg.parse_answer(fixture("icon-32-row-width.txt"), "chargrid", 32, 32, ("icon",))+ assert [i.to_dict() for i in issues] == [{"code": "row_width", "frame": "icon", "row": 16, "detail": "33 values, needs 32"}]+ assert pg.structural(issues) == [] and pg.row_issues(issues) == issues+++def test_a_lookalike_letter_outside_the_palette_is_an_unknown_symbol():+ grid, issues = pg.parse_answer(fixture("fourdir-16-unknown-symbol.txt"), "chargrid", 16, 16, FOURDIR)+ assert [(i.code, i.frame, i.row) for i in issues] == [("unknown_symbol", "up", 8)]+ assert "'о'" in issues[0].detail # U+043E, not the palette's 'o'+++def test_a_single_frame_without_its_frame_line_is_recovered_and_said():+ grid, issues = pg.parse_answer(fixture("sprite-32-frame-header-missing.txt"), "chargrid", 32, 32, ("front",))+ assert codes(issues) == ["frame_header_missing"]+ assert pg.recovered(issues) == issues+ assert len(grid.frames["front"]) == 32+++def test_output_cut_short_is_one_broken_row_and_the_missing_rows():+ grid, issues = pg.parse_answer(fixture("tile-32-truncated.txt"), "chargrid", 32, 32, ("tile",))+ assert [(i.code, i.row) for i in pg.row_issues(issues) if i.code != "row_missing"] == [+ ("row_width", 16), ("unknown_symbol", 16)]+ assert [i.row for i in issues if i.code == "row_missing"] == list(range(17, 33))+ assert codes(pg.recovered(issues)) == ["no_end"]+ assert pg.structural(issues) == []+++def test_spaces_inside_rows_are_unknown_symbols():+ grid, issues = pg.parse_answer(fixture("icon-32-space-in-row.txt"), "chargrid", 32, 32, ("icon",))+ spaced = [i for i in issues if i.code == "unknown_symbol"]+ assert spaced and all("' '" in i.detail for i in spaced)+ assert pg.structural(issues) == []+++def test_an_answer_with_no_block_is_structural():+ grid, issues = pg.parse_answer("", "chargrid", 16, 16, ("front",))+ assert grid is None and codes(issues) == ["no_block"] and pg.structural(issues) == issues+++def _block(palette: str, frames: dict[str, list[str]], end: bool = True, tag: str = "pixels") -> str:+ body = ["PALETTE", palette]+ for name, rows in frames.items():+ body += [f"FRAME {name}", *rows]+ if end:+ body.append("END")+ return f"```{tag}\n" + "\n".join(body) + "\n```\n"+++ROWS8 = ["." * 8] + [".aaaaaa."] * 6 + ["." * 8]++[email protected]("text,frames,expected", [+ (_block(". transparent\na #112233", {"x": ROWS8 + ["." * 8]}), ("x",), "row_count_over"),+ (_block(". transparent\na #112233", {"a1": ROWS8}), ("a1", "a2"), "frame_missing"),+ (_block(". transparent\na #112233", {"a1": ROWS8, "a2": ROWS8, "zz": ROWS8}), ("a1", "a2"), "frame_extra"),+ (_block(". transparent\na #112233\na #445566", {"x": ROWS8}), ("x",), "palette_key_duplicate"),+ (_block(". #000000\na #112233", {"x": ROWS8}), ("x",), "dot_redefined"),+ (_block(". transparent\nt transparent\na #112233", {"x": ROWS8}), ("x",), "extra_transparent_key"),+ (_block(". transparent\na #112233", {"a1": ROWS8, "a1 ": ROWS8}), ("a1", "a2"), "frame_duplicate"),+])+def test_structural_issues(text, frames, expected):+ grid, issues = pg.parse_answer(text, "chargrid", 8, 8, frames)+ assert expected in codes(pg.structural(issues))+++def test_recovered_shapes_are_recorded_and_pass():+ renamed = _block(". transparent\na #112233", {"front": ROWS8})+ grid, issues = pg.parse_answer(renamed, "chargrid", 8, 8, ("icon",))+ assert codes(issues) == ["frame_renamed"] and list(grid.frames) == ["icon"]+ swapped = _block(". transparent\na #112233", {"b": ROWS8, "a": ROWS8}, end=False, tag="text")+ grid, issues = pg.parse_answer(swapped, "chargrid", 8, 8, ("a", "b"))+ assert codes(issues) == ["block_tag", "frame_order", "no_end"]+ assert list(grid.frames) == ["a", "b"]+++def test_a_block_cut_off_or_unfenced_keeps_its_rows():+ text = fixture("sprite-16-pass.txt")+ cut = text[:text.index("END")].rsplit("\n", 7)[0] # the last six rows, END and the fence never came+ grid, issues = pg.parse_answer(cut, "chargrid", 16, 16, ("front",))+ assert codes(pg.recovered(issues)) == ["block_unclosed", "no_end"]+ assert [i.row for i in issues if i.code == "row_missing"] == list(range(11, 17))+ bare = text.replace("```pixels\n", "").replace("```", "")+ grid, issues = pg.parse_answer("Here it is:\n" + bare, "chargrid", 16, 16, ("front",))+ assert codes(issues) == ["block_tag"]+++def test_json_answers_and_their_issues():+ rows = [[0] * 8] + [[0, 1, 1, 1, 1, 1, 1, 0]] * 6 + [[0] * 8]+ good = {"palette": ["transparent", "#112233"], "frames": {"x": rows}}+ grid, issues = pg.parse_answer("```json\n" + json.dumps(good) + "\n```", "json", 8, 8, ("x",))+ assert issues == [] and grid.frames["x"][1][1] == "1"+ bare, issues = pg.parse_answer("here: " + json.dumps(good), "json", 8, 8, ("x",))+ assert codes(issues) == ["block_tag"]+ long_row = {**good, "frames": {"x": [[0] * 9] + rows[1:]}}+ assert codes(pg.parse_answer(json.dumps(long_row), "json", 8, 8, ("x",))[1]) == ["block_tag", "row_width"]+ outside = {**good, "frames": {"x": [[0, 7, 0, 0, 0, 0, 0, 0]] + rows[1:]}}+ assert "unknown_symbol" in codes(pg.parse_answer(json.dumps(outside), "json", 8, 8, ("x",))[1])+ first = {**good, "palette": ["#000000", "#112233"]}+ assert "palette0_not_transparent" in codes(pg.structural(pg.parse_answer(json.dumps(first), "json", 8, 8, ("x",))[1]))+ assert codes(pg.parse_answer("```json\n{not json}\n```", "json", 8, 8, ("x",))[1]) == ["json_invalid"]+++def test_the_recorded_repair_answer_is_spliced_into_its_row():+ grid, issues = pg.parse_answer(fixture("icon-32-row-width.txt"), "chargrid", 32, 32, ("icon",))+ wanted = {(i.frame, i.row) for i in pg.row_issues(issues)}+ fixes, ignored = pg.parse_row_answers(fixture("icon-32-row-width.repair.txt"), grid, wanted)+ assert ignored == [] and list(fixes) == [("icon", 16)]+ fixed = pg.splice(grid, fixes)+ assert pg.check_rows(fixed) == []+ assert "".join(fixed.frames["icon"][15]) == ".ooooooooooooGGooGgoooooooooooo."+ assert [r for n, r in enumerate(fixed.frames["icon"]) if n != 15] == \+ [r for n, r in enumerate(grid.frames["icon"]) if n != 15]+++def test_a_repair_round_can_leave_a_row_still_broken():+ grid, issues = pg.parse_answer(fixture("tile-32-truncated.txt"), "chargrid", 32, 32, ("tile",))+ wanted = {(i.frame, i.row) for i in pg.row_issues(issues)}+ fixes, _ = pg.parse_row_answers(fixture("tile-32-truncated.repair.txt"), grid, wanted)+ left = pg.check_rows(pg.splice(grid, fixes))+ assert [(i.code, i.row, i.detail) for i in left] == [("row_width", 25, "33 values, needs 32")]+++def test_rows_not_asked_for_are_ignored():+ grid, issues = pg.parse_answer(fixture("icon-32-row-width.txt"), "chargrid", 32, 32, ("icon",))+ answer = "ROW icon 16: " + "." * 32 + "\nROW icon 3: " + "o" * 32 + "\nROW other 1: x"+ fixes, ignored = pg.parse_row_answers(answer, grid, {("icon", 16)})+ assert list(fixes) == [("icon", 16)] and ignored == ["icon 3", "other 1"]+++def test_grid_text_is_canonical_and_reads_back():+ grid, _ = pg.parse_answer(fixture("walk-16-pass.txt"), "chargrid", 16, 16, WALK)+ text = pg.to_text(grid)+ assert text.startswith("PALETTE\n. transparent\no #2a1e2e\n") and text.endswith("END\n")+ again, issues = pg.read_grid_text(text)+ assert issues == [] and again.frames == grid.frames and again.palette == grid.palette+ assert (again.width, again.height) == (16, 16)+++def test_a_json_answer_becomes_a_chargrid_grid_text():+ grid, _ = pg.parse_answer(fixture("icon-16-json-pass.txt"), "json", 16, 16, ("icon",))+ text = pg.to_text(grid)+ assert text.splitlines()[1:4] == [". transparent", "a #2b1b2e", "b #6b3f22"]+ again, issues = pg.read_grid_text(text)+ assert issues == []+ assert pg.frame_pixels(again, "icon") == pg.frame_pixels(grid, "icon")+++def test_an_edited_grid_text_with_one_broken_row_reports_that_row():+ grid, _ = pg.parse_answer(fixture("sprite-16-pass.txt"), "chargrid", 16, 16, ("front",))+ lines = pg.to_text(grid).splitlines()+ first_row = lines.index("FRAME front") + 1+ lines[first_row] = lines[first_row][:-1]+ again, issues = pg.read_grid_text("\n".join(lines))+ assert (again.width, again.height) == (16, 16)+ assert [(i.code, i.row) for i in issues] == [("row_width", 1)]+++GOLDEN_2X2 = bytes.fromhex(+ "89504e470d0a1a0a0000000d494844520000000200000002080600000072b60d240000001d494441547801011200edff00ff0000ff"+ "000000000000ff00ff0000ff802d65057c18ea43280000000049454e44ae426082")+++def test_png_bytes_are_a_function_of_the_pixels_alone():+ pixels = [[(255, 0, 0, 255), (0, 0, 0, 0)], [(0, 255, 0, 255), (0, 0, 255, 128)]]+ data = pg.png_bytes(pixels)+ assert data == GOLDEN_2X2 # assembled from the PNG spec by hand, not by this code+ with Image.open(io.BytesIO(data)) as image:+ assert image.mode == "RGBA" and list(image.get_flattened_data()) == [p for row in pixels for p in row]+++def test_a_frame_png_decodes_to_the_grid_and_repeats_byte_for_byte():+ grid, _ = pg.parse_answer(fixture("icon-32-pass.txt"), "chargrid", 32, 32, ("icon",))+ pixels = pg.frame_pixels(grid, "icon")+ first, second = pg.png_bytes(pixels), pg.png_bytes(pg.frame_pixels(grid, "icon"))+ assert first == second+ with Image.open(io.BytesIO(first)) as image:+ assert image.size == (32, 32) and list(image.get_flattened_data()) == [p for row in pixels for p in row]+++def test_palette_rules(tmp_path):+ assert pg.palette_rule("free") == pg.PaletteRule("free:16", 16)+ assert pg.palette_rule("free:8") == pg.PaletteRule("free:8", 8)+ assert pg.palette_rule("pico8").colors == pg.PICO8 and pg.palette_rule("pico8").limit == 16+ fixed = pg.palette_rule("#aabbcc,#112233")+ assert fixed.colors == ("#AABBCC", "#112233") and fixed.limit == 2 and fixed.fixed+ hexfile = tmp_path / "pal.hex"+ hexfile.write_text("; lospec\nff0044\n\n#00AAFF\n", encoding="utf-8")+ assert pg.palette_rule(str(hexfile)).colors == ("#FF0044", "#00AAFF")+ jsonfile = tmp_path / "pal.json"+ jsonfile.write_text(json.dumps({"colors": ["#000000", "#ffffff"]}), encoding="utf-8")+ assert pg.palette_rule(str(jsonfile)).colors == ("#000000", "#FFFFFF")+ for bad in ("free:0", "free:63", "free:x", "#12345", "#aabbcc,#AABBCC", str(tmp_path / "missing.hex")):+ with pytest.raises(ValueError):+ pg.palette_rule(bad)