pixelsrc 0.2.0

Pixelsrc - GenAI-native pixel art format and compiler
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
---
phase: 24
title: LSP Support
---

# Phase 24: LSP Support

**Goal:** Enable live validation, grid alignment assistance, and GenAI tooling for Pixelsrc files via Language Server Protocol

**Status:** Not Started

**Depends on:** Phase 0 (Core CLI), Phase 15 (AI Tools - Validator), Phase 22 (CSS Integration - for Wave 6)

---

## Scope

Phase 24 adds:
- `pxl lsp` - Hidden command that starts LSP server over stdio
- Real-time diagnostics from existing `Validator`
- Grid alignment features specifically designed for GenAI assistance
- Completion suggestions for tokens and structure
- Hover information showing grid coordinates and token details
- **LspAgentClient** - Rust library for GenAI agents to communicate with LSP server programmatically
- **CSS-aware features** (Wave 6, requires Phase 22):
  - CSS color previews with computed `hsl()`, `oklch()`, `color-mix()` values
  - CSS variable completions and hover resolution
  - Timing function visualization
  - Transform explanation

**Not in scope:** Full IDE plugin development (users can use Generic LSP Client), visual sprite previews in editor

---

## Motivation

### For Humans
IDE integration provides immediate feedback on pixelsrc files - syntax errors, undefined tokens, and row mismatches highlighted as you type.

### For GenAI Agents
The LSP becomes a **structured verification API** that agents can use programmatically:

1. **Grid Alignment Verification** - The #1 failure mode for AI-generated sprites is inconsistent row lengths. LSP provides machine-readable diagnostics before the agent declares "done."

2. **Coordinate Awareness** - Agents can query "what token is at position (x,y)?" and "how wide should this row be?" to maintain grid consistency.

3. **Self-Correction Loop** - Agent drafts content → sends to LSP → receives diagnostics → fixes issues → re-validates. Eliminates syntax errors before rendering.

4. **Context Discovery** - Agents use `textDocument/documentSymbol` to discover project structure and `textDocument/completion` to ground generation in existing palettes.

---

## Task Dependency Diagram

```
                          PHASE 24 TASK FLOW
═══════════════════════════════════════════════════════════════════

PREREQUISITES
┌─────────────────────────────────────────────────────────────────┐
│     Phase 0 (CLI)    +    Phase 15 (Validator exists)          │
└─────────────────────────────────────────────────────────────────┘
WAVE 1 (Foundation)
┌─────────────────────────────────────────────────────────────────┐
│  ┌──────────────────────────────────────────────────────────┐   │
│  │   24.1 LSP Server Infrastructure                         │   │
│  │   - tower-lsp integration                                │   │
│  │   - Basic initialize/shutdown                            │   │
│  │   - Hidden `pxl lsp` command                             │   │
│  └──────────────────────────────────────────────────────────┘   │
└─────────────────────────────────────────────────────────────────┘
WAVE 2 (Validation Bridge)
┌─────────────────────────────────────────────────────────────────┐
│  ┌──────────────────────────────────────────────────────────┐   │
│  │   24.2 Diagnostics Integration                           │   │
│  │   - Wire Validator to LSP diagnostics                    │   │
│  │   - didOpen/didChange handlers                           │   │
│  │   - Map ValidationIssue → Diagnostic                     │   │
│  └──────────────────────────────────────────────────────────┘   │
└─────────────────────────────────────────────────────────────────┘
WAVE 3 (Grid Alignment - GenAI Focus)
┌─────────────────────────────────────────────────────────────────┐
│  ┌────────────────────────────┐  ┌──────────────────────────┐  │
│  │   24.3                     │  │   24.4                   │  │
│  │  Grid Coordinate Hover     │  │  Row Length Diagnostics  │  │
│  │  (show x,y at cursor)      │  │  (expected vs actual)    │  │
│  └────────────────────────────┘  └──────────────────────────┘  │
└─────────────────────────────────────────────────────────────────┘
WAVE 4 (Completions & Symbols)
┌─────────────────────────────────────────────────────────────────┐
│  ┌────────────────────────────┐  ┌──────────────────────────┐  │
│  │   24.5                     │  │   24.6                   │  │
│  │  Token Completions         │  │  Document Symbols        │  │
│  │  (suggest {tokens})        │  │  (palette, sprite list)  │  │
│  └────────────────────────────┘  └──────────────────────────┘  │
└─────────────────────────────────────────────────────────────────┘
WAVE 5 (GenAI Agent Integration - CRITICAL)
┌─────────────────────────────────────────────────────────────────┐
│  ┌──────────────────────────────────────────────────────────┐   │
│  │   24.7 LspAgentClient Library                            │   │
│  │   - Rust crate for agent ↔ LSP communication             │   │
│  │   - spawn(), verify_content(), get_completions()         │   │
│  │   - JSON-RPC protocol handling                           │   │
│  │   - Async/await with tokio                               │   │
│  └──────────────────────────────────────────────────────────┘   │
│                                                                 │
│  ┌──────────────────────────────────────────────────────────┐   │
│  │   24.8 Agent CLI Bridge                                  │   │
│  │   - `pxl agent-verify` command (thin wrapper)            │   │
│  │   - Uses LspAgentClient internally                       │   │
│  │   - JSON output for shell-based agents                   │   │
│  └──────────────────────────────────────────────────────────┘   │
└─────────────────────────────────────────────────────────────────┘
WAVE 6 (CSS-Aware Features - Requires Phase 22)
┌─────────────────────────────────────────────────────────────────┐
│  ┌────────────────────────────┐  ┌──────────────────────────┐  │
│  │   24.9                     │  │   24.10                  │  │
│  │  CSS Color Provider        │  │  CSS Variable Support    │  │
│  │  (swatches, color-mix)     │  │  (completions, hover)    │  │
│  └────────────────────────────┘  └──────────────────────────┘  │
│                                                                 │
│  ┌────────────────────────────┐  ┌──────────────────────────┐  │
│  │   24.11                    │  │   24.12                  │  │
│  │  Timing Function Viz       │  │  Transform Explainer     │  │
│  │  (easing curve preview)    │  │  (describe effect)       │  │
│  └────────────────────────────┘  └──────────────────────────┘  │
└─────────────────────────────────────────────────────────────────┘
WAVE 7 (Agent CSS Extensions)
┌─────────────────────────────────────────────────────────────────┐
│  ┌──────────────────────────────────────────────────────────┐   │
│  │   24.13 LspAgentClient CSS Methods                       │   │
│  │   - resolve_colors() - computed var(), color-mix()       │   │
│  │   - analyze_timing() - timing function descriptions      │   │
│  │   - Extend CLI with --resolve-colors, --analyze-timing   │   │
│  └──────────────────────────────────────────────────────────┘   │
└─────────────────────────────────────────────────────────────────┘

═══════════════════════════════════════════════════════════════════

PARALLELIZATION SUMMARY
┌─────────────────────────────────────────────────────────────────┐
│  Wave 1: 24.1                        (1 task, foundation)       │
│  Wave 2: 24.2                        (1 task, needs 24.1)       │
│  Wave 3: 24.3 + 24.4                 (2 tasks in parallel)      │
│  Wave 4: 24.5 + 24.6                 (2 tasks in parallel)      │
│  Wave 5: 24.7 → 24.8                 (sequential, 24.8 uses 24.7│
│  Wave 6: 24.9 + 24.10 + 24.11 + 24.12 (4 tasks, needs Phase 22) │
│  Wave 7: 24.13                       (1 task, extends 24.7)     │
└─────────────────────────────────────────────────────────────────┘
```

---

## Tasks

### Task 24.1: LSP Server Infrastructure

**Wave:** 1 (foundation)

Set up the basic LSP server framework.

**Deliverables:**

1. Add dependencies to `Cargo.toml`:
   ```toml
   tower-lsp = "0.20"
   tokio = { version = "1", features = ["full"] }
   ```

2. Create `src/lsp.rs`:
   ```rust
   use tower_lsp::jsonrpc::Result;
   use tower_lsp::lsp_types::*;
   use tower_lsp::{Client, LanguageServer, LspService, Server};

   pub struct PixelsrcLsp {
       client: Client,
   }

   impl PixelsrcLsp {
       pub fn new(client: Client) -> Self {
           Self { client }
       }
   }

   #[tower_lsp::async_trait]
   impl LanguageServer for PixelsrcLsp {
       async fn initialize(&self, _: InitializeParams) -> Result<InitializeResult> {
           Ok(InitializeResult {
               capabilities: ServerCapabilities {
                   text_document_sync: Some(TextDocumentSyncCapability::Kind(
                       TextDocumentSyncKind::FULL,
                   )),
                   ..Default::default()
               },
               ..Default::default()
           })
       }

       async fn shutdown(&self) -> Result<()> {
           Ok(())
       }
   }

   pub async fn run_server() {
       let stdin = tokio::io::stdin();
       let stdout = tokio::io::stdout();

       let (service, socket) = LspService::new(PixelsrcLsp::new);
       Server::new(stdin, stdout, socket).serve(service).await;
   }
   ```

3. Add hidden CLI command in `src/cli.rs`:
   ```rust
   /// Start LSP server (for IDE integration)
   #[command(hide = true)]
   Lsp,
   ```

4. Wire up in main:
   ```rust
   Commands::Lsp => {
       tokio::runtime::Runtime::new()
           .unwrap()
           .block_on(lsp::run_server());
   }
   ```

**Verification:**
```bash
cargo build
./target/release/pxl lsp --help  # Should not appear in help (hidden)

# Test server starts (will hang waiting for input, Ctrl+C to exit)
echo '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"capabilities":{}}}' | ./target/release/pxl lsp
```

**Dependencies:** Phase 0 complete

---

### Task 24.2: Diagnostics Integration

**Wave:** 2 (needs 24.1)

Wire the existing `Validator` to produce LSP diagnostics.

**Deliverables:**

1. Add document state tracking to `PixelsrcLsp`:
   ```rust
   use std::sync::RwLock;
   use std::collections::HashMap;

   pub struct PixelsrcLsp {
       client: Client,
       documents: RwLock<HashMap<Url, String>>,
   }
   ```

2. Implement `did_open` and `did_change`:
   ```rust
   async fn did_open(&self, params: DidOpenTextDocumentParams) {
       let uri = params.text_document.uri;
       let text = params.text_document.text;
       self.documents.write().unwrap().insert(uri.clone(), text.clone());
       self.validate_and_publish(&uri, &text).await;
   }

   async fn did_change(&self, params: DidChangeTextDocumentParams) {
       let uri = params.text_document.uri;
       if let Some(change) = params.content_changes.into_iter().next() {
           self.documents.write().unwrap().insert(uri.clone(), change.text.clone());
           self.validate_and_publish(&uri, &change.text).await;
       }
   }
   ```

3. Create validation bridge:
   ```rust
   use crate::validate::{Validator, ValidationIssue, Severity};

   impl PixelsrcLsp {
       async fn validate_and_publish(&self, uri: &Url, content: &str) {
           let mut validator = Validator::new();
           for (line_num, line) in content.lines().enumerate() {
               validator.validate_line(line_num + 1, line);
           }

           let diagnostics: Vec<Diagnostic> = validator
               .issues()
               .iter()
               .map(|issue| self.issue_to_diagnostic(issue))
               .collect();

           self.client
               .publish_diagnostics(uri.clone(), diagnostics, None)
               .await;
       }

       fn issue_to_diagnostic(&self, issue: &ValidationIssue) -> Diagnostic {
           Diagnostic {
               range: Range {
                   start: Position { line: (issue.line - 1) as u32, character: 0 },
                   end: Position { line: (issue.line - 1) as u32, character: u32::MAX },
               },
               severity: Some(match issue.severity {
                   Severity::Error => DiagnosticSeverity::ERROR,
                   Severity::Warning => DiagnosticSeverity::WARNING,
               }),
               message: issue.message.clone(),
               ..Default::default()
           }
       }
   }
   ```

**Verification:**
```bash
# Create test file with error
echo '{"type": "sprite", "name": "test", "grid": ["{a}{a}", "{a}"]}' > /tmp/test.pxl

# Use VS Code with Generic LSP Client configured to use `pxl lsp`
# Should see diagnostics for undefined token and row mismatch
```

**Dependencies:** Task 24.1

---

### Task 24.3: Grid Coordinate Hover

**Wave:** 3 (parallel with 24.4)

Show grid coordinates when hovering over tokens - critical for GenAI to understand spatial positions.

**Deliverables:**

1. Add hover capability:
   ```rust
   ServerCapabilities {
       hover_provider: Some(HoverProviderCapability::Simple(true)),
       ...
   }
   ```

2. Implement hover handler:
   ```rust
   async fn hover(&self, params: HoverParams) -> Result<Option<Hover>> {
       let uri = &params.text_document_position_params.text_document.uri;
       let pos = params.text_document_position_params.position;

       let documents = self.documents.read().unwrap();
       let content = documents.get(uri)?;
       let line = content.lines().nth(pos.line as usize)?;

       // Parse line to find grid context
       if let Some(grid_info) = self.parse_grid_context(line, pos.character) {
           let hover_text = format!(
               "**Grid Position**: ({}, {})\n\n\
                **Token**: `{}`\n\n\
                **Row Width**: {} tokens\n\n\
                **Expected Width**: {} tokens",
               grid_info.x, grid_info.y,
               grid_info.token,
               grid_info.row_width,
               grid_info.expected_width
           );

           return Ok(Some(Hover {
               contents: HoverContents::Markup(MarkupContent {
                   kind: MarkupKind::Markdown,
                   value: hover_text,
               }),
               range: None,
           }));
       }

       Ok(None)
   }
   ```

3. Grid context parser:
   ```rust
   struct GridInfo {
       x: usize,        // Column (0-indexed)
       y: usize,        // Row (0-indexed within grid array)
       token: String,   // The token at this position
       row_width: usize,
       expected_width: usize,
   }

   fn parse_grid_context(&self, line: &str, char_pos: u32) -> Option<GridInfo> {
       // Parse JSON line, find "grid" array
       // Determine which row and which token based on char_pos
       // Calculate expected width from size field or first row
   }
   ```

**Verification:**
```bash
# In VS Code, hover over a token in a grid
# Should show: "Grid Position: (3, 2)" etc.
```

**Dependencies:** Task 24.2

---

### Task 24.4: Row Length Diagnostics

**Wave:** 3 (parallel with 24.3)

Enhanced diagnostics specifically for grid alignment issues.

**Deliverables:**

1. Extend `ValidationIssue` for grid-specific errors:
   ```rust
   pub enum IssueType {
       // ... existing types
       RowTooShort { row: usize, actual: usize, expected: usize },
       RowTooLong { row: usize, actual: usize, expected: usize },
       GridHeightMismatch { actual: usize, expected: usize },
   }
   ```

2. Add detailed grid alignment messages:
   ```rust
   fn format_grid_issue(issue: &IssueType) -> String {
       match issue {
           IssueType::RowTooShort { row, actual, expected } => {
               format!(
                   "Row {} has {} tokens but should have {}. Add {} more token(s) to align grid.",
                   row, actual, expected, expected - actual
               )
           }
           IssueType::RowTooLong { row, actual, expected } => {
               format!(
                   "Row {} has {} tokens but should have {}. Remove {} token(s) to align grid.",
                   row, actual, expected, actual - expected
               )
           }
           IssueType::GridHeightMismatch { actual, expected } => {
               format!(
                   "Grid has {} rows but size specifies height of {}.",
                   actual, expected
               )
           }
           // ...
       }
   }
   ```

3. Add code actions for quick fixes:
   ```rust
   // Suggest padding with {_} for short rows
   // Suggest which tokens to remove for long rows
   ```

**Verification:**
```bash
# Create misaligned grid
cat > /tmp/misaligned.pxl << 'EOF'
{"type": "palette", "name": "p", "colors": {"{a}": "#FF0000", "{_}": "#00000000"}}
{"type": "sprite", "name": "s", "size": [4, 3], "palette": "p", "grid": ["{a}{a}{a}{a}", "{a}{a}{a}", "{a}{a}{a}{a}{a}"]}
EOF

# LSP should report:
# - Row 2: has 3 tokens, expected 4 (add 1)
# - Row 3: has 5 tokens, expected 4 (remove 1)
```

**Dependencies:** Task 24.2

---

### Task 24.5: Token Completions

**Wave:** 4 (parallel with 24.6)

Suggest tokens when typing inside grid strings.

**Deliverables:**

1. Add completion capability:
   ```rust
   ServerCapabilities {
       completion_provider: Some(CompletionOptions {
           trigger_characters: Some(vec!["{".to_string()]),
           ..Default::default()
       }),
       ...
   }
   ```

2. Implement completion handler:
   ```rust
   async fn completion(&self, params: CompletionParams) -> Result<Option<CompletionResponse>> {
       let uri = &params.text_document_position.text_document.uri;

       // Find all defined tokens in the document
       let tokens = self.collect_defined_tokens(uri);

       // Include built-in tokens
       let mut completions: Vec<CompletionItem> = vec![
           CompletionItem {
               label: "{_}".to_string(),
               detail: Some("Transparent".to_string()),
               kind: Some(CompletionItemKind::COLOR),
               ..Default::default()
           },
       ];

       for (token, color) in tokens {
           completions.push(CompletionItem {
               label: token.clone(),
               detail: Some(color),
               kind: Some(CompletionItemKind::COLOR),
               ..Default::default()
           });
       }

       Ok(Some(CompletionResponse::Array(completions)))
   }
   ```

**Verification:**
```bash
# In VS Code, type "{" inside a grid string
# Should show completion menu with all defined tokens
```

**Dependencies:** Task 24.2

---

### Task 24.6: Document Symbols

**Wave:** 4 (parallel with 24.5)

Provide outline view of palettes, sprites, animations.

**Deliverables:**

1. Add symbols capability and handler:
   ```rust
   async fn document_symbol(
       &self,
       params: DocumentSymbolParams,
   ) -> Result<Option<DocumentSymbolResponse>> {
       let uri = &params.text_document.uri;
       let documents = self.documents.read().unwrap();
       let content = documents.get(uri)?;

       let mut symbols = Vec::new();

       for (line_num, line) in content.lines().enumerate() {
           if let Ok(obj) = serde_json::from_str::<serde_json::Value>(line) {
               let obj_type = obj.get("type").and_then(|t| t.as_str());
               let name = obj.get("name").and_then(|n| n.as_str());

               if let (Some(t), Some(n)) = (obj_type, name) {
                   symbols.push(SymbolInformation {
                       name: n.to_string(),
                       kind: match t {
                           "palette" => SymbolKind::COLOR,
                           "sprite" => SymbolKind::CLASS,
                           "animation" => SymbolKind::FUNCTION,
                           "composition" => SymbolKind::MODULE,
                           _ => SymbolKind::OBJECT,
                       },
                       location: Location {
                           uri: uri.clone(),
                           range: Range {
                               start: Position { line: line_num as u32, character: 0 },
                               end: Position { line: line_num as u32, character: line.len() as u32 },
                           },
                       },
                       ..Default::default()
                   });
               }
           }
       }

       Ok(Some(DocumentSymbolResponse::Flat(symbols)))
   }
   ```

**Verification:**
```bash
# In VS Code, open Outline panel (Cmd+Shift+O)
# Should show palettes, sprites, animations as navigable symbols
```

**Dependencies:** Task 24.2

---

### Task 24.7: LspAgentClient Library

**Wave:** 5 (GenAI Agent Integration - CRITICAL)

A Rust library that enables GenAI agents to communicate with the LSP server programmatically via JSON-RPC. This is the **primary interface** for AI agents - the CLI wrapper (24.8) is built on top of this.

**Motivation:**

The LSP server speaks JSON-RPC over stdio. Rather than making agents implement the protocol themselves, we provide `LspAgentClient` - a high-level async Rust API that handles:
- Process spawning and lifecycle
- JSON-RPC message framing (Content-Length headers)
- Request/response correlation
- Notification handling (diagnostics are pushed, not pulled)

**Deliverables:**

1. Create new crate `pxl-agent` (or module `src/agent_client.rs`):
   ```rust
   use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
   use tokio::process::{Child, Command};
   use serde_json::{json, Value};
   use std::process::Stdio;

   /// Client for AI agents to communicate with the pixelsrc LSP server.
   ///
   /// # Example
   /// ```rust
   /// let mut client = LspAgentClient::spawn("pxl").await?;
   /// let diagnostics = client.verify_content(sprite_jsonl).await?;
   /// if diagnostics.is_empty() {
   ///     println!("Valid!");
   /// }
   /// ```
   pub struct LspAgentClient {
       child: Child,
       stdin: tokio::process::ChildStdin,
       reader: BufReader<tokio::process::ChildStdout>,
       request_id: u64,
   }

   impl LspAgentClient {
       /// Spawn the LSP server and initialize the connection.
       pub async fn spawn(bin_path: &str) -> anyhow::Result<Self> {
           let mut child = Command::new(bin_path)
               .arg("lsp")
               .stdin(Stdio::piped())
               .stdout(Stdio::piped())
               .spawn()?;

           let stdin = child.stdin.take().unwrap();
           let stdout = child.stdout.take().unwrap();
           let reader = BufReader::new(stdout);

           let mut client = Self { child, stdin, reader, request_id: 0 };
           client.initialize().await?;
           Ok(client)
       }

       /// Initialize the LSP connection (called automatically by spawn).
       async fn initialize(&mut self) -> anyhow::Result<()> {
           self.send_request("initialize", json!({ "capabilities": {} })).await?;
           self.send_notification("initialized", json!({})).await?;
           Ok(())
       }

       /// Validate pixelsrc content and return diagnostics.
       ///
       /// Opens a virtual document, waits for diagnostics, then closes it.
       pub async fn verify_content(&mut self, content: &str) -> anyhow::Result<Vec<Diagnostic>> {
           let uri = "file:///virtual/check.pxl";

           // Open document
           self.send_notification("textDocument/didOpen", json!({
               "textDocument": {
                   "uri": uri,
                   "languageId": "pixelsrc",
                   "version": 1,
                   "text": content
               }
           })).await?;

           // Wait for publishDiagnostics notification
           let diagnostics = self.wait_for_diagnostics(uri).await?;

           // Close document
           self.send_notification("textDocument/didClose", json!({
               "textDocument": { "uri": uri }
           })).await?;

           Ok(diagnostics)
       }

       /// Get completions at a position in the content.
       pub async fn get_completions(&mut self, content: &str, line: u32, character: u32) -> anyhow::Result<Vec<CompletionItem>> {
           let uri = "file:///virtual/complete.pxl";

           self.send_notification("textDocument/didOpen", json!({
               "textDocument": {
                   "uri": uri,
                   "languageId": "pixelsrc",
                   "version": 1,
                   "text": content
               }
           })).await?;

           let result = self.send_request("textDocument/completion", json!({
               "textDocument": { "uri": uri },
               "position": { "line": line, "character": character }
           })).await?;

           self.send_notification("textDocument/didClose", json!({
               "textDocument": { "uri": uri }
           })).await?;

           Ok(parse_completions(&result))
       }

       /// Get document symbols (palettes, sprites, animations).
       pub async fn get_symbols(&mut self, content: &str) -> anyhow::Result<Vec<Symbol>> {
           let uri = "file:///virtual/symbols.pxl";

           self.send_notification("textDocument/didOpen", json!({
               "textDocument": {
                   "uri": uri,
                   "languageId": "pixelsrc",
                   "version": 1,
                   "text": content
               }
           })).await?;

           let result = self.send_request("textDocument/documentSymbol", json!({
               "textDocument": { "uri": uri }
           })).await?;

           self.send_notification("textDocument/didClose", json!({
               "textDocument": { "uri": uri }
           })).await?;

           Ok(parse_symbols(&result))
       }

       /// Get hover information at a position.
       pub async fn get_hover(&mut self, content: &str, line: u32, character: u32) -> anyhow::Result<Option<String>> {
           let uri = "file:///virtual/hover.pxl";

           self.send_notification("textDocument/didOpen", json!({
               "textDocument": {
                   "uri": uri,
                   "languageId": "pixelsrc",
                   "version": 1,
                   "text": content
               }
           })).await?;

           let result = self.send_request("textDocument/hover", json!({
               "textDocument": { "uri": uri },
               "position": { "line": line, "character": character }
           })).await?;

           self.send_notification("textDocument/didClose", json!({
               "textDocument": { "uri": uri }
           })).await?;

           Ok(result.get("contents").and_then(|c| c.as_str()).map(String::from))
       }

       /// Shutdown the LSP server gracefully.
       pub async fn shutdown(mut self) -> anyhow::Result<()> {
           self.send_request("shutdown", json!(null)).await?;
           self.send_notification("exit", json!(null)).await?;
           self.child.wait().await?;
           Ok(())
       }

       // --- Internal JSON-RPC helpers ---

       async fn send_request(&mut self, method: &str, params: Value) -> anyhow::Result<Value> {
           self.request_id += 1;
           let msg = json!({
               "jsonrpc": "2.0",
               "id": self.request_id,
               "method": method,
               "params": params
           });
           self.send_message(&msg).await?;

           // Wait for response with matching ID
           loop {
               let response = self.read_message().await?;
               if response.get("id") == Some(&json!(self.request_id)) {
                   return Ok(response.get("result").cloned().unwrap_or(json!(null)));
               }
               // It's a notification, ignore and keep waiting
           }
       }

       async fn send_notification(&mut self, method: &str, params: Value) -> anyhow::Result<()> {
           let msg = json!({
               "jsonrpc": "2.0",
               "method": method,
               "params": params
           });
           self.send_message(&msg).await
       }

       async fn send_message(&mut self, msg: &Value) -> anyhow::Result<()> {
           let body = serde_json::to_string(msg)?;
           let header = format!("Content-Length: {}\r\n\r\n", body.len());
           self.stdin.write_all(header.as_bytes()).await?;
           self.stdin.write_all(body.as_bytes()).await?;
           self.stdin.flush().await?;
           Ok(())
       }

       async fn read_message(&mut self) -> anyhow::Result<Value> {
           let mut line = String::new();
           let mut content_length = 0;

           // Read headers
           loop {
               line.clear();
               self.reader.read_line(&mut line).await?;
               if line == "\r\n" || line.is_empty() { break; }
               if line.starts_with("Content-Length: ") {
                   content_length = line.trim_start_matches("Content-Length: ")
                       .trim().parse::<usize>()?;
               }
           }

           // Read body
           let mut body = vec![0u8; content_length];
           self.reader.read_exact(&mut body).await?;
           Ok(serde_json::from_slice(&body)?)
       }

       async fn wait_for_diagnostics(&mut self, uri: &str) -> anyhow::Result<Vec<Diagnostic>> {
           loop {
               let msg = self.read_message().await?;
               if msg.get("method") == Some(&json!("textDocument/publishDiagnostics")) {
                   if let Some(params) = msg.get("params") {
                       if params.get("uri") == Some(&json!(uri)) {
                           return Ok(parse_diagnostics(params.get("diagnostics")));
                       }
                   }
               }
           }
       }
   }

   // --- Public types ---

   #[derive(Debug, Clone, serde::Serialize)]
   pub struct Diagnostic {
       pub line: usize,
       pub severity: String,
       pub message: String,
       pub code: Option<String>,
   }

   #[derive(Debug, Clone, serde::Serialize)]
   pub struct CompletionItem {
       pub label: String,
       pub detail: Option<String>,
       pub kind: String,
   }

   #[derive(Debug, Clone, serde::Serialize)]
   pub struct Symbol {
       pub name: String,
       pub kind: String,  // "palette", "sprite", "animation", "composition"
       pub line: usize,
   }
   ```

2. Add to `Cargo.toml`:
   ```toml
   [features]
   agent-client = ["tokio/process", "tokio/io-util"]

   [dependencies]
   tokio = { version = "1", features = ["rt-multi-thread", "macros"], optional = true }
   ```

3. Export from library:
   ```rust
   // src/lib.rs
   #[cfg(feature = "agent-client")]
   pub mod agent_client;
   #[cfg(feature = "agent-client")]
   pub use agent_client::LspAgentClient;
   ```

**Usage Example for AI Agents:**

```rust
use pxl::LspAgentClient;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    // Spawn LSP server
    let mut client = LspAgentClient::spawn("pxl").await?;

    // Validate content
    let sprite = r#"{"type":"sprite","name":"test","grid":["{a}{a}","{a}"]}"#;
    let diagnostics = client.verify_content(sprite).await?;

    for d in &diagnostics {
        println!("Line {}: {} - {}", d.line, d.severity, d.message);
    }

    // Get completions at position
    let completions = client.get_completions(sprite, 0, 42).await?;
    println!("Available tokens: {:?}", completions);

    // Get document structure
    let symbols = client.get_symbols(sprite).await?;
    println!("Symbols: {:?}", symbols);

    // Clean shutdown
    client.shutdown().await?;
    Ok(())
}
```

**Agent Self-Correction Loop:**

```rust
async fn generate_validated_sprite(prompt: &str, client: &mut LspAgentClient) -> String {
    let mut content = llm_generate(prompt);

    for _ in 0..3 {  // Max 3 correction attempts
        let diagnostics = client.verify_content(&content).await.unwrap();

        if diagnostics.iter().all(|d| d.severity != "error") {
            return content;  // Valid!
        }

        // Feed errors back to LLM for correction
        let error_summary: String = diagnostics
            .iter()
            .filter(|d| d.severity == "error")
            .map(|d| format!("Line {}: {}", d.line, d.message))
            .collect::<Vec<_>>()
            .join("\n");

        content = llm_generate(&format!(
            "Fix these errors in the sprite:\n{}\n\nOriginal:\n{}",
            error_summary, content
        ));
    }

    content  // Return best effort after 3 attempts
}
```

**Verification:**
```bash
cargo build --features agent-client
cargo test agent_client

# Integration test
cargo run --features agent-client --example agent_verify
```

**Dependencies:** Task 24.2 (LSP server with diagnostics)

---

### Task 24.8: Agent CLI Bridge

**Wave:** 5 (after 24.7)

A thin CLI wrapper around `LspAgentClient` for shell-based agents and simple scripting.

**Motivation:**

Not all agents are written in Rust. The CLI bridge provides the same capabilities as `LspAgentClient` but via stdin/stdout JSON, usable from Python, shell scripts, or any language.

**Deliverables:**

1. Add CLI command that uses `LspAgentClient` internally:
   ```rust
   /// Verify pixelsrc content for AI agents (returns JSON)
   #[command(name = "agent-verify")]
   AgentVerify {
       /// Content to verify (reads from stdin if not provided)
       #[arg(long)]
       content: Option<String>,

       /// Include grid coordinate info for each sprite
       #[arg(long)]
       grid_info: bool,

       /// Include token suggestions for completion
       #[arg(long)]
       suggest_tokens: bool,
   }
   ```

2. Implementation uses `LspAgentClient`:
   ```rust
   async fn run_agent_verify(args: AgentVerify) -> anyhow::Result<()> {
       let content = match args.content {
           Some(c) => c,
           None => {
               let mut buf = String::new();
               std::io::stdin().read_to_string(&mut buf)?;
               buf
           }
       };

       // Use LspAgentClient internally
       let mut client = LspAgentClient::spawn("pxl").await?;
       let diagnostics = client.verify_content(&content).await?;

       let mut result = AgentVerifyResult {
           valid: diagnostics.iter().all(|d| d.severity != "error"),
           diagnostics: diagnostics.into_iter().map(Into::into).collect(),
           grid_info: None,
           available_tokens: None,
       };

       if args.grid_info {
           result.grid_info = Some(extract_grid_info(&content));
       }

       if args.suggest_tokens {
           let completions = client.get_completions(&content, 0, 0).await?;
           result.available_tokens = Some(completions.into_iter().map(Into::into).collect());
       }

       client.shutdown().await?;
       println!("{}", serde_json::to_string_pretty(&result)?);
       Ok(())
   }
   ```

3. JSON output format:
   ```json
   {
     "valid": false,
     "diagnostics": [
       {
         "line": 2,
         "severity": "warning",
         "message": "Row 2 has 3 tokens but should have 4",
         "fix_suggestion": "Add {_} to pad row to 4 tokens"
       }
     ],
     "grid_info": [
       {
         "name": "hero",
         "size": [16, 16],
         "actual_rows": 16,
         "row_widths": [16, 16, 15, 16],
         "aligned": false
       }
     ],
     "available_tokens": [
       {"token": "{skin}", "color": "#FFCC99", "palette": "hero"},
       {"token": "{_}", "color": "#00000000", "palette": "hero"}
     ]
   }
   ```

**Verification:**
```bash
# Verify content from stdin
echo '{"type":"sprite","name":"x","grid":["{a}{a}","{a}"]}' | pxl agent-verify

# With grid info
cat sprite.jsonl | pxl agent-verify --grid-info

# Python usage
import subprocess, json
result = subprocess.run(
    ["pxl", "agent-verify", "--grid-info"],
    input=sprite_content,
    capture_output=True,
    text=True
)
data = json.loads(result.stdout)
```

**Dependencies:** Task 24.7 (LspAgentClient)

---

### Task 24.9: CSS Color Provider

**Wave:** 6 (parallel with 24.10-24.12, requires Phase 22)

Implement LSP Color Provider for CSS color syntax - swatches, pickers, and computed previews.

**Deliverables:**

1. Add color provider capability:
   ```rust
   ServerCapabilities {
       color_provider: Some(ColorProviderCapability::Simple(true)),
       ...
   }
   ```

2. Implement `document_color` handler:
   ```rust
   async fn document_color(&self, params: DocumentColorParams) -> Result<Vec<ColorInformation>> {
       let uri = &params.text_document.uri;
       let content = self.documents.read().unwrap().get(uri)?.clone();

       let mut colors = Vec::new();

       for (line_num, line) in content.lines().enumerate() {
           // Find color values in palette definitions
           for color_match in find_colors_in_line(line) {
               let resolved = resolve_color(&color_match.value, &self.var_registry)?;
               colors.push(ColorInformation {
                   range: color_match.range_at_line(line_num),
                   color: rgba_to_lsp_color(&resolved),
               });
           }
       }

       Ok(colors)
   }
   ```

3. Support color formats:
   - Hex: `#FF0000`, `#F00`
   - CSS functions: `rgb()`, `hsl()`, `oklch()`, `hwb()`
   - `color-mix()` - resolve and show computed result
   - `var(--name)` - resolve and show computed result

4. Implement `color_presentation` for color picker edits:
   ```rust
   async fn color_presentation(&self, params: ColorPresentationParams) -> Result<Vec<ColorPresentation>> {
       // Offer multiple format options when user picks a color
       let hex = format!("#{:02X}{:02X}{:02X}", r, g, b);
       let hsl = format!("hsl({}, {}%, {}%)", h, s, l);
       let oklch = format!("oklch({}% {} {})", l, c, h);

       Ok(vec![
           ColorPresentation { label: hex, .. },
           ColorPresentation { label: hsl, .. },
           ColorPresentation { label: oklch, .. },
       ])
   }
   ```

**GenAI benefit:** Agents can "see" what `color-mix(in oklch, var(--primary) 70%, black)` actually resolves to.

**Verification:**
```bash
# In VS Code, color values should show colored squares
# Clicking square opens color picker
# color-mix() shows computed result, not the function
```

**Dependencies:** Task 24.2, Phase 22 (CSS-3 color parsing)

---

### Task 24.10: CSS Variable Support

**Wave:** 6 (parallel with 24.9, 24.11, 24.12, requires Phase 22)

Completions, hover, and go-to-definition for CSS custom properties.

**Deliverables:**

1. Extend completion handler for `var(--`:
   ```rust
   async fn completion(&self, params: CompletionParams) -> Result<Option<CompletionResponse>> {
       // ... existing token completions

       // CSS variable completions
       if is_inside_var_function(&context) {
           let vars = self.collect_css_variables(uri);
           for (name, value) in vars {
               completions.push(CompletionItem {
                   label: name.clone(),           // "--primary"
                   detail: Some(value.clone()),   // "hsl(220, 60%, 50%)"
                   kind: Some(CompletionItemKind::VARIABLE),
                   insert_text: Some(name),
                   ..Default::default()
               });
           }
       }

       Ok(Some(CompletionResponse::Array(completions)))
   }
   ```

2. Extend hover for CSS variables:
   ```rust
   // When hovering over var(--primary) or --primary definition
   if let Some(var_info) = self.get_variable_info(line, char_pos) {
       let resolved = self.var_registry.resolve(&var_info.name, false)?;

       let hover_text = format!(
           "**CSS Variable**: `{}`\n\n\
            **Value**: `{}`\n\n\
            **Resolved**: `{}`",
           var_info.name,
           var_info.raw_value,
           resolved
       );
       // If it's a color, include computed hex
       if let Ok(rgba) = parse_color(&resolved) {
           hover_text.push_str(&format!("\n\n**Computed**: `#{:02X}{:02X}{:02X}`",
               rgba[0], rgba[1], rgba[2]));
       }
   }
   ```

3. Go to definition for variables:
   ```rust
   async fn goto_definition(&self, params: GotoDefinitionParams) -> Result<Option<GotoDefinitionResponse>> {
       // If cursor is on var(--name), jump to --name definition
       if let Some(var_name) = extract_var_reference(&line, char_pos) {
           if let Some(def_location) = self.find_variable_definition(&var_name, uri) {
               return Ok(Some(GotoDefinitionResponse::Scalar(def_location)));
           }
       }
       Ok(None)
   }
   ```

4. Diagnostic for circular references:
   ```rust
   // Detect: --a: var(--b); --b: var(--a);
   if let Err(VariableError::Circular(chain)) = self.var_registry.resolve(&value, true) {
       diagnostics.push(Diagnostic {
           severity: Some(DiagnosticSeverity::ERROR),
           message: format!("Circular variable reference: {}", chain),
           ..
       });
   }
   ```

**GenAI benefit:** Agents discover what variables exist and what they resolve to without guessing.

**Verification:**
```bash
# Type var(-- and see completion list
# Hover over var(--primary) shows resolved value
# Cmd+Click on var(--primary) jumps to definition
# Circular refs show error squiggle
```

**Dependencies:** Task 24.5, Phase 22 (CSS-5, CSS-6 variable registry)

---

### Task 24.11: Timing Function Visualization

**Wave:** 6 (parallel with 24.9, 24.10, 24.12, requires Phase 22)

Show ASCII easing curve preview when hovering over timing functions.

**Deliverables:**

1. Extend hover for timing functions:
   ```rust
   if let Some(timing_fn) = extract_timing_function(line, char_pos) {
       let curve = render_ascii_easing_curve(&timing_fn, 20, 8);
       let description = describe_timing_function(&timing_fn);

       let hover_text = format!(
           "**Timing Function**: `{}`\n\n\
            ```\n{}\n```\n\n\
            {}",
           timing_fn.to_css_string(),
           curve,
           description
       );
   }
   ```

2. ASCII curve renderer:
   ```rust
   fn render_ascii_easing_curve(timing: &Interpolation, width: usize, height: usize) -> String {
       // Example output for ease-in-out:
       // ┌────────────────────┐
       // │                 ███│
       // │              ███   │
       // │           ███      │
       // │        ███         │
       // │      ██            │
       // │   ███              │
       // │███                 │
       // └────────────────────┘
   }
   ```

3. Timing function descriptions:
   ```rust
   fn describe_timing_function(timing: &Interpolation) -> &'static str {
       match timing {
           Interpolation::Linear => "Constant speed from start to end.",
           Interpolation::EaseIn => "Starts slow, accelerates toward end.",
           Interpolation::EaseOut => "Starts fast, decelerates toward end.",
           Interpolation::EaseInOut => "Slow start and end, fast middle.",
           Interpolation::Steps { count, position } =>
               &format!("Jumps in {} discrete steps ({:?}).", count, position),
           Interpolation::Bezier { p1, p2 } =>
               "Custom cubic bezier curve.",
           // ...
       }
   }
   ```

4. Special handling for `steps()`:
   ```
   **Timing Function**: `steps(4, jump-end)`

   ```
   ┌────────────────────┐
   │               ████│
   │          ████     │
   │     ████          │
   │████               │
   └────────────────────┘
   ```

   Jumps in 4 discrete steps (jump-end).

   **Note**: For pixel art animations, steps() affects property
   tweening (opacity, position), not frame selection. Frame
   selection is handled by the frame array.
   ```

**GenAI benefit:** Agents understand *how* an animation will feel without rendering it.

**Verification:**
```bash
# Hover over ease-in-out, cubic-bezier(), steps()
# Should show ASCII curve and description
```

**Dependencies:** Task 24.3, Phase 22 (CSS-8 timing functions)

---

### Task 24.12: Transform Explainer

**Wave:** 6 (parallel with 24.9, 24.10, 24.11, requires Phase 22)

Describe what CSS transforms will do in plain language.

**Deliverables:**

1. Extend hover for transform values:
   ```rust
   if let Some(transform) = extract_transform(line, char_pos) {
       let explanation = explain_transform(&transform);

       let hover_text = format!(
           "**Transform**: `{}`\n\n\
            **Effect**:\n{}",
           transform.to_css_string(),
           explanation
       );
   }
   ```

2. Transform explainer:
   ```rust
   fn explain_transform(transform: &Transform) -> String {
       let mut effects = Vec::new();

       if let Some((x, y)) = transform.translate {
           effects.push(format!("• Move {} pixels right, {} pixels down", x, y));
       }
       if let Some(deg) = transform.rotate {
           let direction = if deg > 0.0 { "clockwise" } else { "counter-clockwise" };
           effects.push(format!("• Rotate {:.0}° {}", deg.abs(), direction));
       }
       if let Some((sx, sy)) = transform.scale {
           if sx == sy {
               effects.push(format!("• Scale to {}%", (sx * 100.0) as i32));
           } else {
               effects.push(format!("• Scale width to {}%, height to {}%",
                   (sx * 100.0) as i32, (sy * 100.0) as i32));
           }
       }
       if transform.flip_x {
           effects.push("• Flip horizontally (mirror)".to_string());
       }
       if transform.flip_y {
           effects.push("• Flip vertically".to_string());
       }

       effects.join("\n")
   }
   ```

3. Example hover output:
   ```
   **Transform**: `rotate(90deg) scale(2) translate(8, 0)`

   **Effect**:
   • Rotate 90° clockwise
   • Scale to 200%
   • Move 8 pixels right, 0 pixels down

   **Order**: Transforms apply right-to-left (translate first, then scale, then rotate).
   ```

**GenAI benefit:** Agents understand transformation results without trial-and-error rendering.

**Verification:**
```bash
# Hover over transform values in animation keyframes
# Should show plain-language explanation
```

**Dependencies:** Task 24.3, Phase 22 (CSS-14 transforms)

---

### Task 24.13: LspAgentClient CSS Extensions

**Wave:** 7 (after 24.9-24.12)

Extend `LspAgentClient` with CSS-aware methods for resolving computed values.

**Deliverables:**

1. Add CSS methods to `LspAgentClient`:
   ```rust
   impl LspAgentClient {
       /// Resolve all CSS colors in content to computed hex values.
       ///
       /// Resolves var() references and color-mix() functions.
       pub async fn resolve_colors(&mut self, content: &str) -> anyhow::Result<Vec<ResolvedColor>> {
           let uri = "file:///virtual/colors.pxl";

           self.send_notification("textDocument/didOpen", json!({
               "textDocument": {
                   "uri": uri,
                   "languageId": "pixelsrc",
                   "version": 1,
                   "text": content
               }
           })).await?;

           // Use documentColor to get all colors with their resolved values
           let result = self.send_request("textDocument/documentColor", json!({
               "textDocument": { "uri": uri }
           })).await?;

           self.send_notification("textDocument/didClose", json!({
               "textDocument": { "uri": uri }
           })).await?;

           Ok(parse_resolved_colors(&result, content))
       }

       /// Analyze timing functions in animations.
       pub async fn analyze_timing(&mut self, content: &str) -> anyhow::Result<Vec<TimingAnalysis>> {
           // Parse animations and extract timing function info
           // Returns human-readable descriptions
       }
   }

   #[derive(Debug, Clone, serde::Serialize)]
   pub struct ResolvedColor {
       pub token: String,           // "{skin}"
       pub original: String,        // "var(--skin-tone)"
       pub resolved: String,        // "#FFCC99"
       pub palette: String,
   }

   #[derive(Debug, Clone, serde::Serialize)]
   pub struct TimingAnalysis {
       pub animation: String,
       pub timing_function: String,
       pub description: String,
       pub curve_type: String,      // "smooth" | "stepped" | "bouncy"
   }
   ```

2. Extend CLI command:
   ```rust
   AgentVerify {
       // ... existing args

       /// Resolve CSS variables and color-mix() to computed values
       #[arg(long)]
       resolve_colors: bool,

       /// Show timing function analysis
       #[arg(long)]
       analyze_timing: bool,
   }
   ```

3. Example Rust usage:
   ```rust
   let mut client = LspAgentClient::spawn("pxl").await?;

   // Get resolved colors
   let colors = client.resolve_colors(content).await?;
   for c in &colors {
       println!("{}: {}{}", c.token, c.original, c.resolved);
   }

   // Analyze timing
   let timing = client.analyze_timing(content).await?;
   for t in &timing {
       println!("{}: {} ({})", t.animation, t.timing_function, t.curve_type);
   }
   ```

4. Example CLI output with `--resolve-colors`:
   ```json
   {
     "valid": true,
     "resolved_colors": [
       {
         "token": "{skin}",
         "original": "var(--skin-tone)",
         "resolved": "#FFCC99",
         "palette": "character"
       },
       {
         "token": "{shadow}",
         "original": "color-mix(in oklch, var(--skin-tone) 70%, black)",
         "resolved": "#B38F6B",
         "palette": "character"
       }
     ]
   }
   ```

4. Example output with `--analyze-timing`:
   ```json
   {
     "valid": true,
     "timing_analysis": [
       {
         "animation": "walk_cycle",
         "timing_function": "steps(4, jump-end)",
         "description": "Jumps in 4 discrete steps",
         "curve_type": "stepped"
       }
     ]
   }
   ```

**GenAI benefit:** Agents can verify their CSS expressions resolve to expected values before rendering.

**Verification:**
```bash
pxl agent-verify --resolve-colors < sprite_with_vars.pxl
# Shows all colors with original and resolved values

pxl agent-verify --analyze-timing < animation.pxl
# Shows timing function analysis for each animation
```

**Dependencies:** Tasks 24.7-24.11

---

## GenAI Integration Patterns

### Pattern 1: Pre-Render Validation Loop

```python
def generate_sprite(prompt):
    content = llm.generate(prompt)

    # Verify before declaring done
    result = run("pxl agent-verify --grid-info", input=content)

    if not result["valid"]:
        # Feed diagnostics back to LLM for self-correction
        content = llm.generate(f"""
            Fix these issues in the sprite:
            {json.dumps(result["diagnostics"])}

            Original content:
            {content}
        """)
        # Re-verify...

    return content
```

### Pattern 2: Grid-Aware Generation

```python
# Get grid info to understand current state
result = run("pxl agent-verify --grid-info", input=partial_content)

for sprite in result["grid_info"]:
    if not sprite["aligned"]:
        expected_width = sprite["size"][0]
        for i, width in enumerate(sprite["row_widths"]):
            if width != expected_width:
                print(f"Row {i}: needs {expected_width - width} more tokens")
```

### Pattern 3: Token Discovery

```python
# Discover available tokens before generating
result = run("pxl agent-verify --suggest-tokens", input=existing_content)

available = [t["token"] for t in result["available_tokens"]]
# Use in prompt: "Only use these tokens: {available}"
```

### Pattern 4: CSS Color Verification (requires Phase 22)

```python
def generate_palette_with_shadows(base_colors):
    """Generate palette with computed shadow colors."""
    content = llm.generate(f"""
        Create a pixelsrc palette with these base colors: {base_colors}
        Use color-mix(in oklch, <base> 70%, black) for shadow variants.
        Use CSS variables to avoid repetition.
    """)

    # Verify computed colors resolve correctly
    result = run("pxl agent-verify --resolve-colors", input=content)

    if result["valid"]:
        # Log what colors actually resolved to
        for color in result["resolved_colors"]:
            print(f"{color['token']}: {color['original']} → {color['resolved']}")

    return content
```

### Pattern 5: Animation Timing Analysis (requires Phase 22)

```python
def verify_animation_feel(animation_content, expected_type):
    """Ensure animation timing matches expected feel."""
    result = run("pxl agent-verify --analyze-timing", input=animation_content)

    for timing in result.get("timing_analysis", []):
        if timing["curve_type"] != expected_type:
            # Re-generate with corrected timing
            return llm.generate(f"""
                Fix this animation to use {expected_type} timing instead of {timing['curve_type']}.
                Current: {timing['timing_function']}
                Content: {animation_content}
            """)

    return animation_content
```

---

## VS Code Configuration

Users can integrate with the Generic LSP Client extension:

```json
{
    "generic-lsp.server-definitions": {
        "pixelsrc": {
            "command": "pxl",
            "args": ["lsp"],
            "rootUri": "${workspaceFolder}",
            "languages": ["json", "jsonl"],
            "extensions": [".pxl", ".jsonl"]
        }
    }
}
```

---

## Verification Summary

```bash
# === WAVE 1-4: Core LSP (24.1-24.6) ===

# 1. LSP server starts (24.1)
./target/release/pxl lsp &
# (test with LSP client)

# 2. Diagnostics work (24.2)
# Open file with errors in VS Code, should see squiggles

# 3. Hover shows grid coordinates (24.3)
# Hover over grid tokens, should see x,y position

# 4. Row length diagnostics (24.4)
# Misaligned rows show warning with fix suggestion

# 5. Completions work (24.5)
# Type "{" in grid, should see token suggestions

# 6. Symbols work (24.6)
# Open outline (Cmd+Shift+O), should see palettes/sprites

# === WAVE 5: LspAgentClient (24.7-24.8) ===

# 7. LspAgentClient library works (24.7)
cargo test --features agent-client agent_client
cargo run --features agent-client --example agent_verify

# 8. Rust agent integration
use pxl::LspAgentClient;
let mut client = LspAgentClient::spawn("pxl").await?;
let diagnostics = client.verify_content(content).await?;
let completions = client.get_completions(content, 0, 42).await?;
let symbols = client.get_symbols(content).await?;

# 9. CLI bridge works (24.8)
echo '{"type":"sprite","name":"x","grid":["{a}{a}","{a}"]}' | pxl agent-verify
# Should return JSON with diagnostics

# === WAVE 6-7: CSS Features (requires Phase 22) ===

# 10. Color provider works (24.9)
# Open palette with hsl(), color-mix() - should show color swatches
# Click swatch to open picker

# 11. CSS variable completions (24.10)
# Type var(-- inside a color value, should see defined variables

# 12. CSS variable hover (24.10)
# Hover over var(--primary), should show resolved value

# 13. Timing function visualization (24.11)
# Hover over ease-in-out or cubic-bezier(), should show ASCII curve

# 14. Transform explanation (24.12)
# Hover over rotate(90deg) scale(2), should show effect description

# 15. LspAgentClient CSS extensions (24.13)
# Rust API:
let colors = client.resolve_colors(content).await?;
let timing = client.analyze_timing(content).await?;

# CLI:
pxl agent-verify --resolve-colors < sprite_with_vars.pxl
pxl agent-verify --analyze-timing < animation.pxl
```

---

## Future Enhancements

| Feature | Description |
|---------|-------------|
| Go to Definition (tokens) | Jump from grid token `{skin}` to palette definition |
| Find References | Find all uses of a token across file |
| Rename Symbol | Safely rename tokens or CSS variables across file |
| Format on Save | Wire `pxl fmt` to LSP formatting |
| Semantic Tokens | Syntax highlighting via LSP |
| Grid Visualization | ASCII sprite preview in hover tooltip |
| Color Contrast Check | Warn when adjacent colors have low contrast |
| Palette Suggestions | Suggest harmonious colors based on existing palette |