pointbreak 0.6.0

Durable terminal code review for changes humans and coding agents collaborate on together
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
//! Endpoint contract coverage for the `shore inspect` JSON API (issue #110),
//! exercised over real HTTP against a store built at test time. The harness
//! lives in `support::inspect` so multiple inspector suites share one
//! spawn-the-real-server fixture.

mod support;

use serde_json::Value;
use support::git_repo::GitRepo;
use support::inspect::{Inspector, capture, representative_store, urlencode};
use support::shore_env;

/// Find the captured Revision event id via the public read path (`read_events`).
fn captured_event_id(repo: &std::path::Path) -> String {
    pointbreak::session::read_events(repo)
        .unwrap()
        .iter()
        .find(|e| e.event_type == pointbreak::session::event::EventType::WorkObjectProposed)
        .expect("a captured review unit")
        .event_id
        .as_str()
        .to_owned()
}

/// Parsed instant from either legal `occurredAt` form.
fn occurred_instant(entry: &Value) -> i64 {
    let raw = entry["occurredAt"]
        .as_str()
        .expect("occurredAt is a string");
    pointbreak::session::parse_event_instant(raw)
        .unwrap_or_else(|| panic!("occurredAt is not a legal instant: {raw}"))
}

fn entries_of_type<'a>(history: &'a Value, event_type: &str) -> Vec<&'a Value> {
    history["entries"]
        .as_array()
        .expect("entries is an array")
        .iter()
        .filter(|e| e["eventType"] == event_type)
        .collect()
}

/// Spawn the inspector against a throwaway repo for served-asset contract checks.
/// The static asset routes never read the store, so a bare repo keeps the
/// served-copy assertions cheap. The returned [`GitRepo`] must be held for the
/// lifetime of the [`Inspector`].
fn served_asset_inspector() -> (GitRepo, Inspector) {
    let repo = GitRepo::new();
    let inspector = Inspector::spawn(repo.path());
    (repo, inspector)
}

/// Smoke: the shared harness spawns the real `shore inspect --port 0` server and
/// serves a well-formed history payload for a minimal store.
#[test]
fn inspector_harness_serves_history_for_minimal_store() {
    let repo = GitRepo::new();
    repo.write("src/lib.rs", "pub fn value() -> u32 { 1 }\n");
    repo.commit_all("base");
    repo.write("src/lib.rs", "pub fn value() -> u32 { 2 }\n");
    capture(repo.path());

    let inspector = Inspector::spawn(repo.path());
    let history = inspector.get_json("/api/history");

    assert_eq!(history["schema"], "pointbreak.inspect-history");
    // A minimal worktree capture records the capture event plus the auto-recorded
    // capture-time ref association (no separate `review_initialized` event exists).
    let entries = history["entries"].as_array().unwrap();
    assert_eq!(entries.len(), 2);
    let event_types: Vec<&str> = entries
        .iter()
        .filter_map(|entry| entry["eventType"].as_str())
        .collect();
    assert!(
        event_types.contains(&"work_object_proposed"),
        "{event_types:?}"
    );
    assert!(
        event_types.contains(&"revision_ref_associated"),
        "{event_types:?}"
    );
}

#[test]
fn api_attention_serves_projection() {
    let store = representative_store();
    // The fixture's human assessment REPLACES the agent one, leaving a single
    // current record. Append one extra un-replaced assessment on a distinct track
    // so two current assessments coexist and the revision is ambiguous. It must
    // be NON-accepting: a unanimously accepting current set recorded after the
    // fixture's failed clippy check would subsume the failed_validation item
    // (judgment-subsumption Rule B), and this test needs that kind visible.
    let added = support::shore([
        "assessment",
        "add",
        "--repo",
        store.repo.path().to_str().unwrap(),
        "--track",
        "agent:second",
        "--assessment",
        "needs-changes",
        "--summary",
        "second opinion",
    ]);
    assert!(
        added.status.success(),
        "stderr:\n{}",
        String::from_utf8_lossy(&added.stderr)
    );

    let inspector = Inspector::spawn(store.repo.path());
    let attention = inspector.get_json("/api/attention");

    assert_eq!(attention["schema"], "pointbreak.inspect-attention");
    assert!(
        attention["eventSetHash"]
            .as_str()
            .unwrap()
            .starts_with("sha256:")
    );

    let items = attention["items"].as_array().unwrap();
    let kinds: Vec<&str> = items
        .iter()
        .map(|item| item["kind"].as_str().unwrap())
        .collect();
    assert!(kinds.contains(&"open_input_request"), "kinds: {kinds:?}");
    assert!(kinds.contains(&"failed_validation"), "kinds: {kinds:?}");
    assert!(kinds.contains(&"ambiguous_assessment"), "kinds: {kinds:?}");

    // Stage guard (invariant 2): no item carries a "stage" key, and no field
    // anywhere carries a lifecycle-stage value.
    for item in items {
        let obj = item.as_object().unwrap();
        assert!(
            !obj.contains_key("stage"),
            "item carries a stage key: {item}"
        );
        for (key, value) in obj {
            if let Some(text) = value.as_str() {
                assert!(
                    !matches!(text, "reviewing" | "deciding" | "done"),
                    "item field {key} carries a lifecycle-stage value: {item}"
                );
            }
        }
    }

    // failed_validation legitimately carries a VALIDATION outcome in "status".
    let failed = items
        .iter()
        .find(|item| item["kind"] == "failed_validation")
        .expect("a failed_validation item");
    let status = failed["status"].as_str().unwrap();
    assert!(
        status == "failed" || status == "errored",
        "failed_validation status must be failed/errored, got {status}"
    );
}

#[test]
fn api_history_returns_chronological_typed_summaries() {
    let store = representative_store();
    let inspector = Inspector::spawn(store.repo.path());
    let history = inspector.get_json("/api/history");

    assert_eq!(history["schema"], "pointbreak.inspect-history");
    assert!(
        history["eventSetHash"]
            .as_str()
            .unwrap()
            .starts_with("sha256:")
    );
    let entries = history["entries"].as_array().unwrap();
    // capture + auto-recorded ref association + observation + input-request
    // + 2 assessments + 2 validation checks.
    assert_eq!(history["eventCount"], 8);
    assert_eq!(history["historyCount"], 8);
    assert_eq!(entries.len(), 8, "one entry per recorded event");

    // Entries are chronological (occurredAt ascending).
    let stamps: Vec<i64> = entries.iter().map(occurred_instant).collect();
    assert!(
        stamps.windows(2).all(|w| w[0] <= w[1]),
        "entries must be sorted by occurredAt asc: {stamps:?}"
    );

    // Every entry carries the identity fields the UI reads.
    for entry in entries {
        assert!(entry["eventId"].as_str().unwrap().starts_with("evt:"));
        assert!(
            entry["payloadHash"]
                .as_str()
                .unwrap()
                .starts_with("sha256:")
        );
        assert!(
            entry["writer"]["actorId"]
                .as_str()
                .unwrap()
                .starts_with("actor:")
        );
        // The summary is kind-tagged. The capture event carries a domain-named
        // kind distinct from its envelope event type; every other event's tag
        // matches its event type.
        if entry["eventType"] == "work_object_proposed" {
            assert_eq!(entry["summary"]["kind"], "revision_captured");
        } else {
            assert_eq!(entry["summary"]["kind"], entry["eventType"]);
        }
    }

    // The observation summary carries its title and range target.
    let observations = entries_of_type(&history, "review_observation_recorded");
    assert_eq!(observations.len(), 1);
    let obs = observations[0];
    assert_eq!(obs["summary"]["title"], "Observed change");
    assert_eq!(obs["summary"]["target"]["kind"], "range");
    assert_eq!(obs["summary"]["target"]["filePath"], "src/lib.rs");
    assert_eq!(obs["summary"]["target"]["startLine"], 2);
    assert_eq!(obs["summary"]["target"]["endLine"], 2);
    assert_eq!(obs["trackId"], "agent:codex");
    assert_eq!(obs["subject"]["revisionId"], store.revision_id.as_str());
}

#[test]
fn api_units_lists_captured_unit_with_counts_and_target_display() {
    let store = representative_store();
    let inspector = Inspector::spawn(store.repo.path());
    let units = inspector.get_json("/api/revisions");

    assert_eq!(units["schema"], "pointbreak.inspect-revisions");
    assert_eq!(units["revisionCount"], 1);
    let entry = &units["entries"][0];
    assert_eq!(entry["revisionId"], store.revision_id.as_str());
    assert_eq!(entry["snapshotId"], store.snapshot_id.as_str());

    // The path-private derived display block is spliced in (regression alongside
    // cli_inspect_target_display.rs).
    assert!(entry["targetDisplay"]["label"].is_string());
    assert_eq!(entry["targetDisplay"]["pathPrivate"], true);
    assert!(entry["targetDisplay"]["head"]["commitOidShort"].is_string());
}

#[test]
fn api_units_include_additive_overview_summary() {
    let store = representative_store();
    let inspector = Inspector::spawn(store.repo.path());
    let units = inspector.get_json("/api/revisions");
    let revision = inspector.get_json(&format!("/api/revisions/{}", urlencode(&store.revision_id)));

    let entry = &units["entries"][0];
    assert_eq!(entry["revisionId"], store.revision_id.as_str());
    assert_eq!(entry["snapshotId"], store.snapshot_id.as_str());
    assert!(entry["target"].is_object());
    assert!(entry["base"].is_object());
    assert!(entry["targetDisplay"].is_object());

    let overview = &entry["overview"];
    assert_eq!(overview["currentAssessment"]["status"], "resolved");
    assert_eq!(overview["currentAssessment"]["assessment"], "accepted");

    let attention = &overview["attention"];
    assert_eq!(attention["unassessed"], false);
    assert_eq!(attention["acceptedWithFollowUp"], false);
    assert_eq!(attention["openInputRequestCount"], 1);
    assert_eq!(attention["failedValidationCount"], 1);
    assert_eq!(attention["erroredValidationCount"], 0);
    assert_eq!(attention["staleFactCount"], 0);

    let counts = &overview["counts"];
    assert_eq!(counts["files"], revision["summary"]["fileCount"]);
    assert_eq!(counts["rows"], revision["summary"]["rowCount"]);
    assert_eq!(
        counts["observations"],
        revision["summary"]["observationCount"]
    );
    assert_eq!(
        counts["inputRequests"],
        revision["summary"]["inputRequestCount"]
    );
    assert_eq!(
        counts["assessments"],
        revision["summary"]["assessmentCount"]
    );
    assert_eq!(
        counts["validationChecks"],
        revision["summary"]["validationCheckCount"]
    );

    let latest_activity = &overview["latestActivity"];
    if !latest_activity.is_null() {
        assert!(latest_activity["kind"].is_string());
        assert!(latest_activity["title"].is_string());
        assert!(latest_activity["at"].is_string());
    }
}

/// `/api/revisions` is served from a head-marker-keyed response cache (#426):
/// an unchanged store version serves the identical payload again, and a store
/// write moves the marker so the next request reflects the new revision — never
/// a stale hit.
#[test]
fn api_revisions_cache_serves_fresh_payload_after_store_writes() {
    let repo = GitRepo::new();
    repo.write("src/lib.rs", "pub fn value() -> u32 { 1 }\n");
    repo.commit_all("base");
    repo.write("src/lib.rs", "pub fn value() -> u32 { 2 }\n");
    let first_revision = capture(repo.path());

    let inspector = Inspector::spawn(repo.path());
    let initial = inspector.get_json("/api/revisions");
    assert_eq!(initial["revisionCount"], 1);
    assert_eq!(initial["entries"][0]["revisionId"], first_revision.as_str());

    // Unchanged store version: the identical payload serves again.
    let repeat = inspector.get_json("/api/revisions");
    assert_eq!(repeat, initial);

    // A store write moves the head marker: the cache rebuilds and the new
    // revision appears.
    repo.write("src/lib.rs", "pub fn value() -> u32 { 3 }\n");
    let second_revision = capture(repo.path());
    let refreshed = inspector.get_json("/api/revisions");
    assert_eq!(refreshed["revisionCount"], 2);
    let ids: Vec<&str> = refreshed["entries"]
        .as_array()
        .expect("entries is an array")
        .iter()
        .filter_map(|entry| entry["revisionId"].as_str())
        .collect();
    assert!(ids.contains(&first_revision.as_str()), "{ids:?}");
    assert!(ids.contains(&second_revision.as_str()), "{ids:?}");
    assert_ne!(refreshed["eventSetHash"], initial["eventSetHash"]);
}

#[test]
fn api_snapshot_returns_snapshot_scoped_artifact() {
    let store = representative_store();
    let inspector = Inspector::spawn(store.repo.path());
    let snapshot = inspector.get_json(&format!("/api/snapshots/{}", urlencode(&store.snapshot_id)));

    // Object-scoped wire (#146): content hash + frozen diff only — no
    // identity/endpoint fields. Identity/target display live on /api/revisions(/{id}).
    assert!(
        snapshot["contentHash"]
            .as_str()
            .unwrap()
            .starts_with("sha256:")
    );
    assert!(snapshot.get("revisionId").is_none());
    assert!(snapshot.get("target").is_none());
    assert!(snapshot.get("base").is_none());
    assert!(snapshot.get("source").is_none());
    assert!(snapshot.get("worktreeRootRedacted").is_none());

    // The captured diff has a real file with a hunk consistent with the edit.
    let files = snapshot["snapshot"]["files"].as_array().unwrap();
    assert!(!files.is_empty());
    let hunks = files[0]["hunks"].as_array().unwrap();
    assert!(!hunks.is_empty());
}

#[test]
fn api_freshness_exposes_the_event_count_marker() {
    let store = representative_store();
    let inspector = Inspector::spawn(store.repo.path());
    let history = inspector.get_json("/api/history");
    let freshness = inspector.get_json("/api/freshness");

    assert_eq!(freshness["schema"], "pointbreak.inspect-freshness");
    // The cheap change key is the event-log head marker — the event count, equal
    // to what a full history read reports, but computed without the full read.
    // (Monotonic-on-append and stable-across-envelope-edit are proven at the
    // journal level, in the backend `head_marker` tests.)
    assert!(freshness["eventCount"].is_u64());
    assert_eq!(freshness["eventCount"], history["eventCount"]);
    // The full-read fields are gone from the cheap probe: the freshness path no
    // longer folds or hashes the log. The event-set hash stays the authoritative
    // confirm stamp on the full-read endpoints (asserted for /api/history above).
    assert!(freshness.get("eventSetHash").is_none());
    assert!(freshness.get("diagnosticCount").is_none());
    // The commit-graph stamp is the second change key: a pure-git ref move —
    // most importantly a landing fast-forward — flips revision merge statuses
    // without appending an event, and the polling client refetches on either
    // key (#467).
    assert!(freshness["commitGraphStamp"].is_string());
}

#[test]
fn error_routes_over_real_socket() {
    let store = representative_store();
    let inspector = Inspector::spawn(store.repo.path());

    // Unknown route → 404 JSON.
    let (status, body) = inspector.get_error("/api/nope");
    assert!(status.contains("404"), "status: {status}");
    assert_eq!(body["error"], "no such route");

    // Missing required path member → 400 JSON.
    let (status, body) = inspector.get_error("/api/snapshots/");
    assert!(status.contains("400"), "status: {status}");
    assert!(body["error"].as_str().unwrap().contains("id"));

    // Non-GET method → 405.
    let status = inspector.request("POST", "/api/history");
    assert!(status.contains("405"), "status: {status}");
}

#[test]
fn payloads_never_expose_raw_repository_paths_on_path_private_surfaces() {
    let store = representative_store();
    let repo_path = store.repo.path().to_string_lossy().to_string();
    let inspector = Inspector::spawn(store.repo.path());

    // The freshness probe is a bare event count — genuinely path-free.
    let freshness = inspector.get_json("/api/freshness");
    assert!(!freshness.to_string().contains(&repo_path));

    // The snapshot wire is object-scoped — it carries no endpoint/target at all,
    // so there is no worktree path to leak (the redaction logic is gone).
    let snapshot = inspector.get_json(&format!("/api/snapshots/{}", urlencode(&store.snapshot_id)));
    assert!(snapshot.get("target").is_none());
    assert!(
        !snapshot.to_string().contains(&repo_path),
        "object-scoped wire must not carry the raw worktree path"
    );

    // The derived targetDisplay label on /api/revisions is always path-private
    // (basename + short OID only), even though the verbatim `target.worktreeRoot`
    // it sits beside legitimately carries the path for a working-tree capture
    // (see finding: no-raw-paths scope widened post-0062).
    let units = inspector.get_json("/api/revisions");
    let target_display = &units["entries"][0]["targetDisplay"];
    assert!(!target_display.to_string().contains(&repo_path));
}

#[test]
fn inspect_history_endpoint_renders_endorsement_readback() {
    let home = tempfile::tempdir().unwrap();
    let env_home = home.path().to_str().unwrap();
    let env: [(&str, &str); 1] = [("SHORE_HOME", env_home)];
    assert!(
        shore_env(["key", "init", "--name", "default"], &env)
            .status
            .success()
    );
    let repo = GitRepo::new();
    repo.write("src/lib.rs", "pub fn v() -> u32 { 1 }\n");
    repo.commit_all("base");
    repo.write("src/lib.rs", "pub fn v() -> u32 { 2 }\n");
    let repo_arg = repo.path().to_str().unwrap();
    // Enroll the default key under kevin (reader trust config in the repo).
    assert!(
        shore_env(
            [
                "key",
                "enroll",
                "default",
                "--actor",
                "actor:git-email:kevin@swiber.dev",
                "--repo",
                repo_arg,
            ],
            &env,
        )
        .status
        .success()
    );
    // Capture UNSIGNED so the detached endorsement carrier is not deduped, then endorse.
    assert!(
        shore_env(
            ["capture", "--repo", repo_arg],
            &[("SHORE_HOME", env_home), ("SHORE_SIGNING", "off")],
        )
        .status
        .success()
    );
    let target = captured_event_id(repo.path());
    assert!(
        shore_env(
            ["endorse", &target, "--repo", repo_arg],
            &[
                ("SHORE_HOME", env_home),
                ("SHORE_ACTOR_ID", "actor:git-email:kevin@swiber.dev"),
            ],
        )
        .status
        .success()
    );

    // The inspector reads the repo's reader config (allowed-signers.json), so it
    // resolves the same reader-relative classification as the CLI.
    let inspector = Inspector::spawn(repo.path());
    let history = inspector.get_json("/api/history");
    let endorsement = history["entries"]
        .as_array()
        .unwrap()
        .iter()
        .find_map(|e| e.get("endorsements").and_then(|x| x.get(0)))
        .expect("an endorsement readback in the inspector history");
    assert_eq!(endorsement["classification"], "endorsement-trusted");
    assert_eq!(endorsement["endorser"], "actor:git-email:kevin@swiber.dev");
}

#[test]
fn tokens_css_is_served_as_the_single_token_source() {
    let (_repo, inspector) = served_asset_inspector();

    // The fourth served asset is reachable and carries the semantic status
    // aliases, the radii scale, and the sans stack — the single token source.
    let (status, body) = inspector.raw_get("/tokens.css");
    assert!(
        status.contains("200 OK"),
        "tokens.css is served, got {status}"
    );
    assert!(
        body.contains("--success"),
        "tokens.css holds the semantic status aliases"
    );
    assert!(
        body.contains("--r-md"),
        "tokens.css carries the radii scale"
    );
    assert!(body.contains("--sans"), "tokens.css carries the sans stack");

    // index.html links tokens.css before app.css so the cascade resolves vars first.
    let index = inspector.get_text("/");
    let tokens_at = index.find("/tokens.css").expect("index links /tokens.css");
    let app_at = index.find("/app.css").expect("index links /app.css");
    assert!(
        tokens_at < app_at,
        "tokens.css must be linked before app.css"
    );
}

#[test]
fn app_css_no_longer_declares_the_root_token_block() {
    let (_repo, inspector) = served_asset_inspector();
    let app_css = inspector.get_text("/app.css");
    // The single :root lives in tokens.css now; app.css is component rules only.
    // Match the bare selector so `:root{` (no space) cannot slip past the guard.
    assert!(
        !app_css.contains(":root"),
        "app.css must not declare any :root token block (single-sourced in tokens.css)"
    );
}

#[test]
fn design_system_docs_state_the_component_state_contract() {
    let readme = include_str!("../src/cli/inspect/design-system/README.md");
    let styles = include_str!("../src/cli/inspect/design-system/styles.css");

    assert!(
        !styles.contains("mirror the live inspector 1:1"),
        "the gallery stylesheet must not claim complete live-app mirroring"
    );
    assert!(
        readme.contains("component/state preview"),
        "README names the narrower gallery contract"
    );
    assert!(
        readme.contains("not a full live-app mirror"),
        "README says runtime behavior belongs to the live inspector"
    );
    assert!(
        readme.contains("shared tokens"),
        "README keeps token sharing explicit"
    );
    assert!(
        readme.contains("status/readback/diff/shell/feedback"),
        "README names the critical parity surface set"
    );
    assert!(
        readme.contains("../assets/tokens.css") && readme.contains("live token source"),
        "README names the served token sheet as Review's live source"
    );
    assert!(
        readme.contains("contrast-check.mjs") && readme.contains("audit of record"),
        "README names the product-local contrast audit"
    );
    assert!(
        readme.contains("Node") && readme.contains("design tooling only"),
        "README keeps Node outside the Rust build and runtime"
    );
    assert!(
        !readme.contains("PR #261") && !styles.contains("PR #261"),
        "gallery docs should describe current state, not a completed PR redo"
    );
}

#[test]
fn design_system_bake_is_gated_by_a_local_live_token_audit() {
    let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
    let audit_path = root.join("src/cli/inspect/design-system/contrast-check.mjs");
    let audit = std::fs::read_to_string(&audit_path)
        .unwrap_or_else(|error| panic!("{} must exist: {error}", audit_path.display()));
    let bake = std::fs::read_to_string(root.join("src/cli/inspect/design-system/_bodies/bake.sh"))
        .expect("design-system bake script is readable");

    for required in [
        "assets/tokens.css",
        "--bg-row-sel",
        "--sel-bg",
        "--diff-add-fg",
        "--emph-add-bg",
        "--error-bg",
        "--evt-assessment",
        "--tok-keyword",
    ] {
        assert!(audit.contains(required), "audit must require {required}");
    }
    assert!(
        !audit.contains("withpointbreak.com"),
        "the product audit must not depend on the marketing repository"
    );

    let audit_at = bake
        .find("contrast-check.mjs")
        .expect("bake invokes the product-local contrast audit");
    let publish_at = bake
        .find("cat \"$TOKENS\"")
        .expect("bake publishes the generated token layer");
    assert!(
        audit_at < publish_at,
        "contrast verification must run before generated files are written"
    );
}

#[test]
fn design_system_gallery_is_claude_design_sync_ready() {
    let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
    let design_system = root.join("src/cli/inspect/design-system");
    let styles = std::fs::read_to_string(design_system.join("styles.css"))
        .expect("design-system stylesheet is readable");
    let bake = std::fs::read_to_string(design_system.join("_bodies/bake.sh"))
        .expect("design-system bake script is readable");
    let readme = std::fs::read_to_string(design_system.join("README.md"))
        .expect("design-system README is readable");
    let gitignore = std::fs::read_to_string(design_system.join(".gitignore"))
        .expect("design-system gitignore is readable");
    let identity = std::fs::read_to_string(design_system.join("_bodies/identity-large.body.html"))
        .expect("large identity body is readable");
    let brand_check = std::fs::read_to_string(design_system.join("brand-check.mjs"))
        .expect("design-system brand checker is readable");

    assert!(
        !styles.contains("url(\"/pointbreak-logo-mono") && !styles.contains("../../assets/"),
        "gallery styles must not use origin-absolute or project-escaping mono-logo URLs"
    );
    assert!(
        styles.contains("url(\"logo/pointbreak-logo-mono.svg\")"),
        "gallery styles use one project-root-relative mono-logo URL"
    );
    assert!(
        bake.contains(
            "cp \"$DS/../assets/pointbreak-logo-mono.svg\" \"$DS/logo/pointbreak-logo-mono.svg\""
        ),
        "bake publishes the live mono logo inside the synced project"
    );
    assert!(
        bake.contains("s#url(\"logo/#url(\"../logo/#g"),
        "bake rewrites project-root logo URLs for one-level-deep cards"
    );
    assert!(
        readme.contains("pointbreak-product-ds"),
        "README names the active Claude Design project"
    );
    assert!(
        identity.contains("<svg class=\"large-identity-mark large-identity-mark-multiband\"")
            && !identity.contains("<img"),
        "large identity must inline multiband geometry so SVG sanitization cannot remove its fills"
    );
    for fill in [
        "var(--wave-deep)",
        "var(--wave-trough)",
        "var(--wave-face)",
        "var(--wave-mid)",
        "var(--wave-crest)",
    ] {
        assert!(
            styles.contains(fill),
            "large identity styles must use {fill}"
        );
    }
    assert!(
        brand_check.contains("_bodies/identity-large.body.html")
            && brand_check.contains("inline identity geometry"),
        "brand check must validate inline identity geometry against the brand lock"
    );
    for ignored in [
        "/logo/pointbreak-logo-mono.svg",
        "/_ds_*",
        "/_adherence.oxlintrc.json",
        "templates/**/.thumbnail",
    ] {
        assert!(
            gitignore.contains(ignored),
            "gitignore must include {ignored}"
        );
    }
}

#[test]
fn design_system_brand_assets_are_locked_and_verified_offline() {
    let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
    let design_system = root.join("src/cli/inspect/design-system");
    let lock_path = design_system.join("pointbreak-brand.lock.json");
    let lock_source = std::fs::read_to_string(&lock_path)
        .unwrap_or_else(|error| panic!("{} must exist: {error}", lock_path.display()));
    let lock: serde_json::Value =
        serde_json::from_str(&lock_source).expect("brand lock is valid JSON");
    let checker_path = design_system.join("brand-check.mjs");
    let checker = std::fs::read_to_string(&checker_path)
        .unwrap_or_else(|error| panic!("{} must exist: {error}", checker_path.display()));
    let bake = std::fs::read_to_string(design_system.join("_bodies/bake.sh"))
        .expect("design-system bake script is readable");
    let server = std::fs::read_to_string(root.join("src/cli/inspect/server.rs"))
        .expect("inspector server source is readable");
    let index = std::fs::read_to_string(root.join("src/cli/inspect/assets/index.html"))
        .expect("inspector index is readable");

    assert_eq!(lock["schema"], "com.withpointbreak.brand-lock/v1");
    assert_eq!(
        lock["source"]["repository"],
        "https://github.com/withpointbreak/brand"
    );
    assert_eq!(
        lock["source"]["commit"],
        "45f3bc61a00535f5f7b59bf04dc6391a1153f31c"
    );
    assert_eq!(
        lock["source"]["manifestSha256"],
        "a6d36770cd2e9db2951c45835c7739fbb6d89ad45e959c50fe2bbe2e7a76eabe"
    );
    for field in ["commit", "manifestSha256"] {
        let value = lock["source"][field]
            .as_str()
            .unwrap_or_else(|| panic!("source.{field} must be a string"));
        let expected_len = if field == "commit" { 40 } else { 64 };
        assert_eq!(value.len(), expected_len, "source.{field} has exact length");
        assert!(
            value
                .bytes()
                .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase()),
            "source.{field} is lowercase hexadecimal"
        );
    }

    let destinations = lock["artifacts"]
        .as_array()
        .expect("brand lock artifacts are an array")
        .iter()
        .map(|artifact| {
            artifact["destination"]
                .as_str()
                .expect("every locked artifact has a destination")
        })
        .collect::<std::collections::BTreeSet<_>>();
    let mut expected = vec![
        "src/cli/inspect/assets/pointbreak-logo-mono.svg".to_owned(),
        "src/cli/inspect/design-system/logo/pointbreak-logo.svg".to_owned(),
        "src/cli/inspect/design-system/fonts/OFL.txt".to_owned(),
    ];
    for name in [
        "Bold",
        "BoldItalic",
        "ExtraBold",
        "ExtraBoldItalic",
        "ExtraLight",
        "ExtraLightItalic",
        "Italic",
        "Light",
        "LightItalic",
        "Medium",
        "MediumItalic",
        "Regular",
        "SemiBold",
        "SemiBoldItalic",
        "Thin",
        "ThinItalic",
    ] {
        expected.push(format!(
            "src/cli/inspect/design-system/fonts/JetBrainsMono-{name}.woff2"
        ));
    }
    for destination in expected {
        assert!(
            destinations.contains(destination.as_str()),
            "brand lock must cover {destination}"
        );
    }

    for forbidden in [
        "node:child_process",
        "fetch(",
        "http.request",
        "https.request",
        "POINTBREAK_BRAND_DIR",
        "/Users/",
    ] {
        assert!(
            !checker.contains(forbidden),
            "offline checker must not contain {forbidden}"
        );
    }
    let brand_at = bake
        .find("brand-check.mjs")
        .expect("bake invokes the offline brand checker");
    let audit_at = bake
        .find("contrast-check.mjs")
        .expect("bake invokes the local contrast audit");
    assert!(
        brand_at < audit_at,
        "brand verification must precede contrast verification"
    );
    assert!(
        !server.contains("design-system/logo") && !index.contains("pointbreak-logo.svg"),
        "the multiband logo must remain gallery-only; live chrome keeps its mono asset"
    );
}

#[test]
fn design_system_gallery_covers_live_shell_and_overlay_states() {
    let bodies = [
        include_str!("../src/cli/inspect/design-system/_bodies/navigation-topbar.body.html"),
        include_str!("../src/cli/inspect/design-system/_bodies/inputs-controls.body.html"),
        include_str!("../src/cli/inspect/design-system/_bodies/feedback-diagnostics.body.html"),
        include_str!("../src/cli/inspect/design-system/_bodies/data-diff.body.html"),
    ]
    .join("\n");
    let styles = include_str!("../src/cli/inspect/design-system/styles.css");
    let bake = include_str!("../src/cli/inspect/design-system/_bodies/bake.sh");

    for marker in [
        "id=\"topbar\"",
        "id=\"lens-switcher\"",
        "class=\"lens-tab\"",
        "class=\"split\"",
        "id=\"master\"",
        "id=\"detail\"",
        "class=\"route-diagnostic\"",
        "id=\"cmd-palette\"",
        "class=\"cmd-item\"",
        "class=\"cmd-empty\"",
        "id=\"key-help\"",
        "class=\"key-help-list\"",
        "class=\"advisory-note\"",
        "class=\"reader-scope-note\"",
        "class=\"modal\"",
        "class=\"modal-card\"",
        "data-ds-state=\"narrow\"",
    ] {
        assert!(bodies.contains(marker), "gallery bodies include {marker}");
    }

    for selector in [
        ".lens-tab",
        ".route-diagnostic",
        ".cmd-item",
        ".key-help-list",
        ".advisory-note",
        ".reader-scope-note",
        ".modal-card",
        ".split",
    ] {
        assert!(
            styles.contains(selector),
            "gallery styles include {selector}"
        );
    }

    for output in [
        "navigation/topbar-light.html",
        "inputs/controls-light.html",
        "feedback/diagnostics-light.html",
    ] {
        assert!(bake.contains(output), "bake matrix includes {output}");
    }

    let normalized_bake = bake.split_whitespace().collect::<Vec<_>>().join(" ");
    for named_pair in [
        "bake navigation-topbar.body.html navigation/topbar.html Navigation \"Navigation — top bar, tabs, stats\" \"\" \"\" \"Navigation — dark\" \"Dark theme\"",
        "bake inputs-controls.body.html inputs/controls.html Inputs \"Inputs — toolbar, buttons, toggles\" \"\" \"\" \"Inputs — dark\" \"Dark theme\"",
        "bake feedback-diagnostics.body.html feedback/diagnostics.html Feedback \"Feedback — diagnostics & errors\" \"\" \"\" \"Feedback — dark\" \"Dark theme\"",
    ] {
        assert!(
            normalized_bake.contains(named_pair),
            "dark theme twin carries explicit marker name + subtitle: {named_pair}"
        );
    }
}

#[test]
fn design_system_gallery_covers_the_shipped_attention_lens() {
    let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
    let body = std::fs::read_to_string(
        root.join("src/cli/inspect/design-system/_bodies/data-attention.body.html"),
    )
    .expect("Attention gallery body exists");
    let styles = std::fs::read_to_string(root.join("src/cli/inspect/design-system/styles.css"))
        .expect("gallery styles exist");

    for marker in [
        "attention-card",
        "attention-tier",
        "attention-kind",
        "attention-freshness",
    ] {
        assert!(
            body.contains(marker) || styles.contains(marker),
            "missing {marker}"
        );
    }
    assert!(body.contains("Needs input"));
    assert!(body.contains("Advisory"));
    for marker in [
        "open-input-request",
        "ambiguous-assessment",
        "stale-assessment",
        "failed-validation",
        "manual_decision_required",
        "accepted · current",
        "superseded by",
    ] {
        assert!(
            body.contains(marker),
            "Attention body must include {marker}"
        );
    }
}

#[test]
fn design_system_promotes_selected_review_treatments_and_soft_operational_dark() {
    let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
    let tokens = std::fs::read_to_string(root.join("src/cli/inspect/assets/tokens.css"))
        .expect("live Review tokens exist");
    for declaration in [
        "--bg: #101817;",
        "--bg-elev: #151f1e;",
        "--bg-row: #1b2725;",
        "--bg-row-sel: #243331;",
        "--bg-topbar: #131d1b;",
        "--sel-bg: #243331;",
        "--bg-code: #121c1a;",
        "--border: #2d3d39;",
        "--fg: #e5ebe7;",
        "--fg-dim: #9eaaa5;",
        "--accent: #5ce5f4;",
        "--accent-strong: #1fc4d6;",
        "--on-accent: #071012;",
        "--bg: #fdfbf5;",
        "--bg-elev: #fffefa;",
        "--bg-row: #f7f3e9;",
        "--bg-row-sel: #e2dbce;",
        "--bg-topbar: #f4f0e6;",
        "--sel-bg: #f7f3e9;",
        "--bg-code: #fffefa;",
        "--border: #9eaaa4;",
        "--fg: #1b1d1c;",
        "--fg-dim: #4e5853;",
        "--accent: #006875;",
        "--accent-strong: #007885;",
        "--on-accent: #ffffff;",
    ] {
        assert!(
            tokens.contains(declaration),
            "live tokens must promote {declaration}"
        );
    }

    // Density, semantic status, and syntax aliases were controls in the study,
    // not selected treatments.
    for unchanged in [
        "--row-pad: 8px 14px;",
        "--row-pad: 4px 12px;",
        "--success: #6dd28a;",
        "--success: #1a7f37;",
        "--tok-string: var(--success);",
        "--tok-type: var(--info);",
    ] {
        assert!(
            tokens.contains(unchanged),
            "unselected contract must remain unchanged: {unchanged}"
        );
    }

    let styles = std::fs::read_to_string(root.join("src/cli/inspect/design-system/styles.css"))
        .expect("gallery styles exist");
    let mono_identity = styles
        .split(".large-identity-mark-mono {")
        .nth(1)
        .and_then(|rest| rest.split('}').next())
        .expect("large mono identity selector");
    let multiband_identity = styles
        .split(".large-identity-mark-multiband {")
        .nth(1)
        .and_then(|rest| rest.split('}').next())
        .expect("large multiband identity selector");
    assert!(mono_identity.contains("display: none;"));
    assert!(multiband_identity.contains("display: block;"));

    let app_css = std::fs::read_to_string(root.join("src/cli/inspect/assets/app.css"))
        .expect("live component styles exist");
    assert!(app_css.contains("url(\"/pointbreak-logo-mono.svg\")"));
    assert!(
        !app_css.contains("pointbreak-logo.svg"),
        "compact live chrome must remain mono"
    );
}

#[test]
fn design_system_final_state_has_no_temporary_visual_system() {
    let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
    assert!(
        !root.join("src/cli/inspect/design-system/variants").exists(),
        "the promoted visual system must not leave a temporary variant directory"
    );

    let bake = include_str!("../src/cli/inspect/design-system/_bodies/bake.sh");
    for forbidden in [
        "data-visual-variant",
        "bake_variant",
        "bake_comparison",
        "comparisons/",
    ] {
        assert!(
            !bake.contains(forbidden),
            "final bake must not contain {forbidden}"
        );
    }
    assert!(bake.contains("identity/large.html"));
    assert!(bake.contains("identity/large-light.html"));
    assert!(bake.contains("data/attention.html"));
    assert!(bake.contains("data/attention-light.html"));

    let review_facts =
        include_str!("../src/cli/inspect/design-system/_bodies/data-review-facts.body.html");
    for marker in ["replaced", "current", "signature valid"] {
        assert!(
            review_facts.contains(marker),
            "review-facts comparison preserves {marker}"
        );
    }
    let attention =
        include_str!("../src/cli/inspect/design-system/_bodies/data-attention.body.html");
    assert!(attention.contains("stale-assessment"));
    assert!(attention.contains("accepted · current"));

    let large_identity =
        include_str!("../src/cli/inspect/design-system/_bodies/identity-large.body.html");
    assert!(
        large_identity.contains("<svg class=\"large-identity-mark large-identity-mark-multiband\"")
    );
    assert!(!large_identity.contains("<img"));
}

#[test]
fn design_system_soft_operational_dark_study_stays_gallery_only() {
    let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
    let study = root.join("src/cli/inspect/design-system/studies/soft-operational-dark");
    for required in ["README.md", "tokens.css", "audit.mjs", "bake.sh"] {
        assert!(
            study.join(required).is_file(),
            "soft operational study must include {required}"
        );
    }

    let study_tokens = std::fs::read_to_string(study.join("tokens.css"))
        .expect("soft operational study tokens exist");
    assert!(
        study_tokens.contains("data-tone=\"study-baseline\""),
        "study must retain the accepted pre-trial baseline"
    );
    for held_constant in [
        "--accent",
        "--success",
        "--warning",
        "--danger",
        "--diff-add-bg",
        "--tok-keyword",
        "--row-pad",
    ] {
        assert!(
            !study_tokens.contains(held_constant),
            "study must not override held-constant token {held_constant}"
        );
    }

    let live_tokens = include_str!("../src/cli/inspect/assets/tokens.css");
    let live_styles = include_str!("../src/cli/inspect/assets/app.css");
    let canonical_bake = include_str!("../src/cli/inspect/design-system/_bodies/bake.sh");
    for live_source in [live_tokens, live_styles, canonical_bake] {
        assert!(
            !live_source.contains("soft-operational"),
            "the gallery-only study must not enter live tokens, styles, or the canonical bake"
        );
    }
}

#[test]
fn design_system_contrast_audit_gates_every_syntax_tinted_row_pair() {
    let audit = include_str!("../src/cli/inspect/design-system/contrast-check.mjs");
    for marker in [
        "add row",
        "delete row",
        "emphasized add",
        "emphasized delete",
    ] {
        assert!(audit.contains(marker), "final audit must cover {marker}");
    }
    assert!(
        !audit.contains("result.diagnostic") && !audit.contains("diagnostic = false"),
        "syntax/tinted-row pairs must be release gates, not diagnostics"
    );
    assert!(!audit.contains("--variant"));

    let tokens = include_str!("../src/cli/inspect/assets/tokens.css");
    for correction in [
        "--diff-add-bg: #f3fbf3;",
        "--diff-del-bg: #fff8f6;",
        "--emph-add-bg: #e0ffe0;",
        "--emph-del-bg: #fff2e6;",
    ] {
        assert!(
            tokens.contains(correction),
            "light diff correction must include {correction}"
        );
    }
}

#[test]
fn review_visual_promotion_leaves_terminal_palettes_compatibility_frozen() {
    let terminal = include_str!("../src/cli/theme.rs");
    let readme = include_str!("../src/cli/inspect/design-system/README.md");
    assert!(readme.contains("remain compatibility-frozen"));
    assert!(readme.contains("not mechanically follow"));
    for pinned in [
        "\\x1b[38;2;90;169;230m",  // existing dark function color
        "\\x1b[48;2;0;96;0m",      // existing dark add emphasis
        "\\x1b[38;2;3;105;161m",   // existing light function color
        "\\x1b[48;2;160;239;160m", // existing light add emphasis
    ] {
        assert!(
            terminal.contains(pinned),
            "terminal compatibility pin must remain {pinned:?}"
        );
    }
}

#[test]
fn design_system_gallery_keeps_dag_edges_and_current_copy_in_sync() {
    let styles = include_str!("../src/cli/inspect/design-system/styles.css");
    let data_cards = include_str!("../src/cli/inspect/design-system/_bodies/data-cards.body.html");

    assert!(
        styles.contains("--dag-edge"),
        "gallery DAG styles should carry the same default edge token as the live inspector"
    );
    let edge_block = styles
        .split(".dag-edge {")
        .nth(1)
        .and_then(|rest| rest.split('}').next())
        .expect(".dag-edge block");
    assert!(
        edge_block.contains("stroke: var(--dag-edge)")
            && !edge_block.contains("stroke: var(--border)"),
        "gallery DAG edges should not fall back to only the quiet border token: {edge_block}"
    );
    let arrow_block = styles
        .split(".dag-arrow-head {")
        .nth(1)
        .and_then(|rest| rest.split('}').next())
        .expect(".dag-arrow-head block");
    assert!(
        arrow_block.contains("fill: var(--dag-edge)")
            && !arrow_block.contains("fill: var(--border)"),
        "gallery DAG arrowheads should share the stronger edge token: {arrow_block}"
    );
    assert!(
        data_cards.contains("current in thread"),
        "gallery revision-card examples should use the live current-state wording"
    );
    assert!(
        !data_cards.contains(">head</span>") && !data_cards.contains("revision thread · head "),
        "gallery examples should avoid the old bare head copy"
    );
}

// The theme flip, the OS-preference default, and the localStorage round-trip are
// runtime client behavior; with no JS execution harness in the served envelope they
// cannot be unit-tested. These assert the served-copy contracts that the wiring is
// present — stable, user-visible strings and attributes — over the HTTP harness.
#[test]
fn tokens_css_carries_a_light_theme_override_block() {
    let (_repo, inspector) = served_asset_inspector();
    let tokens = inspector.get_text("/tokens.css");
    // The light theme is a semantic-alias override, not a second :root.
    assert!(
        tokens.contains("[data-theme=\"light\"]"),
        "tokens.css carries the light-theme alias override block"
    );
    // color-scheme is declared so native controls/scrollbars match the theme.
    assert!(
        tokens.contains("color-scheme"),
        "tokens.css declares color-scheme"
    );
}

#[test]
fn topbar_exposes_an_accessible_theme_toggle() {
    let (_repo, inspector) = served_asset_inspector();
    let index = inspector.get_text("/");
    // A stable, user-visible accessible name for the control (assert the aria
    // label, a durable contract — not the button's id). The label now names the
    // control and carries its current value (`Color theme: <mode>`), so assert the
    // durable prefix — the value after it is runtime state.
    assert!(
        index.contains("aria-label=\"Color theme:"),
        "the topbar carries an accessible theme toggle"
    );
}

// The rendered glyphs/shapes and the density flip are runtime CSS/DOM behavior;
// these assert the served-copy CSS contracts that the redundancy layer and the
// tokens are present, over the HTTP harness.
#[test]
fn status_palette_has_a_non_color_redundancy_layer() {
    let (_repo, inspector) = served_asset_inspector();
    let app_css = inspector.get_text("/app.css");
    // Color is not the only channel: each status carries a glyph via ::before content.
    assert!(
        app_css.contains("::before") && app_css.contains("content:"),
        "status classes carry a per-state glyph so meaning never rides on hue alone"
    );
    // Head vs superseded differs in border style, not only hue.
    assert!(
        app_css.contains("dashed"),
        "superseded revisions read as dashed, a shape cue beyond color"
    );
    // ID-heavy mono columns get tabular figures + slashed zero.
    assert!(
        app_css.contains("tabular-nums") && app_css.contains("slashed-zero"),
        "mono/id columns disambiguate 0/O and align digits"
    );
}

#[test]
fn positive_advisory_states_use_text_not_checkmark_glyphs() {
    let (_repo, inspector) = served_asset_inspector();
    let app_css = inspector.get_text("/app.css");
    let gallery_css = include_str!("../src/cli/inspect/design-system/styles.css");
    let gallery_bodies = [
        include_str!("../src/cli/inspect/design-system/_bodies/data-diff.body.html"),
        include_str!("../src/cli/inspect/design-system/_bodies/data-review-facts.body.html"),
        include_str!("../src/cli/inspect/design-system/_bodies/data-timeline.body.html"),
        include_str!("../src/cli/inspect/design-system/_bodies/feedback-diagnostics.body.html"),
    ]
    .join("\n");

    for (label, css) in [("app", app_css.as_str()), ("gallery", gallery_css)] {
        assert!(
            !css.contains("content: \"\""),
            "{label} CSS should not use a positive checkmark glyph"
        );
        for selector in [
            ".fact-status.passed::before",
            ".fact-status.responded::before",
            ".fact-status.current::before",
            ".verdict-accepted .verdict-value::before",
            ".verdict-accepted_with_follow_up .verdict-value::before",
            ".s-added::before",
        ] {
            assert!(
                !css.contains(selector),
                "{label} CSS should leave positive state labels text-only: {selector}"
            );
        }
        // The signature readback is the one positive state that leads with a
        // marker: a neutral middot (never a checkmark, guarded above) so a valid
        // timeline row still carries a status mark alongside the non-positive
        // glyphs. The served inspector and the gallery mirror stay in sync on it.
        assert!(
            css.contains(".verify-valid::before") && css.contains("content: \"·\""),
            "{label} signature readback leads valid rows with a neutral middot, not a checkmark"
        );
        for glyph in [
            "content: \"\"",
            "content: \"!\"",
            "content: \"?\"",
            "content: \"~\"",
            "content: \"\"",
        ] {
            assert!(
                css.contains(glyph),
                "{label} CSS keeps non-positive status glyph redundancy: {glyph}"
            );
        }
    }

    for label in [
        "accepted",
        "passed",
        "responded",
        "current",
        "signature valid",
        "added",
    ] {
        assert!(
            gallery_bodies.contains(label),
            "gallery examples keep the positive state text label visible: {label}"
        );
    }
}

#[test]
fn tokens_css_carries_the_type_scale() {
    let (_repo, inspector) = served_asset_inspector();
    let tokens = inspector.get_text("/tokens.css");
    for step in ["--fs-xs", "--fs-sm", "--fs-md", "--fs-base"] {
        assert!(
            tokens.contains(step),
            "tokens.css carries the {step} type-scale step"
        );
    }
}

#[test]
fn topbar_exposes_a_density_toggle() {
    let (_repo, inspector) = served_asset_inspector();
    let index = inspector.get_text("/");
    // The label names the control and carries its current value
    // (`Density: <mode>`); assert the durable prefix, the value is runtime state.
    assert!(
        index.contains("aria-label=\"Density:"),
        "the topbar carries an accessible comfortable/compact density toggle"
    );
}

// The advisory / read-only framing is rendered DOM text, not a `title`-only tooltip.
// It moved from a persistent top-bar badge into the store-identity popover note
// (issue #391 follow-up): the badge was redundant on a wholly read-only tool, but the
// substantive posture — recorded state only, reader-relative verification — stays in
// the served index.html as a real `<p>`, not hidden behind a `title` attribute.
#[test]
fn advisory_framing_is_rendered_text_not_tooltip_only() {
    let (_repo, inspector) = served_asset_inspector();
    let index = inspector.get_text("/");

    assert!(
        index.contains("never gates writes") && index.contains("reader-relative"),
        "the store-identity popover carries the read-only / advisory framing as rendered text"
    );
}

#[test]
fn api_history_windows_with_limit_and_continues_via_offset() {
    let store = representative_store();
    let inspector = Inspector::spawn(store.repo.path());

    let full = inspector.get_json("/api/history");
    let total = full["entries"].as_array().unwrap().len();
    let event_count = full["eventCount"].clone();
    assert!(
        total >= 2,
        "representative store should yield multiple history entries, got {total}"
    );

    let page1 = inspector.get_json("/api/history?limit=1");
    assert_eq!(page1["entries"].as_array().unwrap().len(), 1);
    assert_eq!(page1["offset"], 0);
    // Identity always reports the full event set, never the window.
    assert_eq!(page1["eventCount"], event_count);
    assert_eq!(page1["matchCount"], total);

    // The window is positional: the next page is offset=1. No opaque cursor.
    let page2 = inspector.get_json("/api/history?limit=1&offset=1");
    assert_eq!(page2["entries"].as_array().unwrap().len(), 1);
    assert_eq!(page2["offset"], 1);
    // Page two continues strictly after page one — no overlap.
    assert_ne!(
        page2["entries"][0]["eventId"],
        page1["entries"][0]["eventId"]
    );
    // The endpoint no longer carries an opaque cursor — paging is positional.
    assert!(full.as_object().unwrap().get("nextCursor").is_none());
    assert!(page1.as_object().unwrap().get("nextCursor").is_none());
}

#[test]
fn api_history_rejects_malformed_window_params() {
    let store = representative_store();
    let inspector = Inspector::spawn(store.repo.path());

    // A non-numeric limit is a usage error.
    assert!(
        inspector
            .get_error("/api/history?limit=abc")
            .0
            .contains("400")
    );
    // A non-numeric offset is a usage error too.
    assert!(
        inspector
            .get_error("/api/history?offset=abc")
            .0
            .contains("400")
    );
    // A stray `cursor=` is not a recognized param — it is ignored, not a 400.
    assert_eq!(
        inspector.get_json("/api/history?cursor=whatever")["matchCount"],
        inspector.get_json("/api/history")["matchCount"]
    );
}

#[test]
fn api_history_q_filters_entries_and_reports_facets_and_match_count() {
    let store = representative_store();
    let inspector = Inspector::spawn(store.repo.path());

    let full = inspector.get_json("/api/history");
    let observations = entries_of_type(&full, "review_observation_recorded").len();
    assert!(observations >= 1, "store should have observations");

    let filtered = inspector.get_json("/api/history?type=review_observation_recorded");
    // The page is observations only, and matchCount is the filtered (post-type) size.
    assert!(
        filtered["entries"]
            .as_array()
            .unwrap()
            .iter()
            .all(|entry| entry["eventType"] == "review_observation_recorded")
    );
    assert_eq!(filtered["matchCount"], observations);
    // Facets still report ALL types — they exclude the `type` page filter (INV-3).
    assert_eq!(
        filtered["facets"]["review_observation_recorded"],
        observations
    );
    assert!(
        filtered["facets"]["review_assessment_recorded"]
            .as_u64()
            .unwrap_or(0)
            >= 1,
        "facets count assessments even under a type=observation page filter"
    );
}

#[test]
fn api_history_q_full_text_search_narrows_the_page() {
    let store = representative_store();
    let inspector = Inspector::spawn(store.repo.path());

    let full = inspector.get_json("/api/history");
    let total = full["matchCount"].as_u64().unwrap();

    // A `q` term present on some but not all entries narrows the page and the count.
    let filtered = inspector.get_json("/api/history?q=type%3Aobservation");
    let filtered_count = filtered["matchCount"].as_u64().unwrap();
    assert!(filtered_count <= total);
    assert!(
        filtered["entries"]
            .as_array()
            .unwrap()
            .iter()
            .all(|entry| entry["eventType"] == "review_observation_recorded")
    );
}

#[test]
fn api_history_rejects_an_unsupported_qualifier_with_400() {
    let store = representative_store();
    let inspector = Inspector::spawn(store.repo.path());
    // attention: is a revision qualifier; on the event timeline it is a 400, never
    // a silently-empty page.
    let (status, body) = inspector.get_error("/api/history?q=attention%3Ax");
    assert!(status.contains("400"), "status: {status}");
    assert!(body.get("error").is_some(), "body: {body}");
}

#[test]
fn api_history_aliases_status_to_check_and_reports_a_deprecation_notice() {
    let store = representative_store();
    let inspector = Inspector::spawn(store.repo.path());
    // status:passed runs as check:passed AND rides a deprecation hint back on
    // queryNotices — not a 400.
    let filtered = inspector.get_json("/api/history?q=status%3Apassed");
    let notices = filtered["queryNotices"]
        .as_array()
        .expect("queryNotices array");
    assert!(
        !notices.is_empty(),
        "expected a deprecation notice: {filtered}"
    );
    assert!(filtered["matchCount"].as_u64().unwrap() >= 1);
    for entry in filtered["entries"].as_array().unwrap() {
        assert_eq!(entry["eventType"], "validation_check_recorded");
        assert_eq!(entry["summary"]["status"], "passed"); // the aliased filter narrowed
    }
}

#[test]
fn api_history_offset_windows_the_filtered_set() {
    let store = representative_store();
    let inspector = Inspector::spawn(store.repo.path());

    let total = inspector.get_json("/api/history")["matchCount"]
        .as_u64()
        .unwrap();
    let page = inspector.get_json("/api/history?offset=1&limit=2");
    assert_eq!(page["offset"], 1);
    assert!(page["entries"].as_array().unwrap().len() <= 2);
    assert_eq!(page["matchCount"], total);
}

#[test]
fn api_history_at_locates_the_page_and_sets_match_index() {
    let store = representative_store();
    let inspector = Inspector::spawn(store.repo.path());

    let full = inspector.get_json("/api/history");
    let target = full["entries"][0]["eventId"].as_str().unwrap().to_owned();
    let located = inspector.get_json(&format!("/api/history?limit=2&at={}", urlencode(&target)));
    assert!(located["matchIndex"].is_u64());
    assert!(
        located["entries"]
            .as_array()
            .unwrap()
            .iter()
            .any(|entry| entry["eventId"] == target.as_str())
    );
}

#[test]
fn api_history_unparamd_shape_is_unchanged_plus_additive_fields() {
    let store = representative_store();
    let inspector = Inspector::spawn(store.repo.path());

    let full = inspector.get_json("/api/history");
    let entries = full["entries"].as_array().unwrap().len();
    // Unchanged: schema + historyCount = entries.
    assert_eq!(full["schema"], "pointbreak.inspect-history");
    assert_eq!(full["historyCount"], entries);
    // Positional paging surface: facets/matchCount/offset always present, matchIndex
    // only for at=, and no opaque cursor (dropped in favor of offset/at).
    assert!(full["facets"].is_object());
    assert_eq!(full["offset"], 0);
    assert_eq!(full["matchCount"], entries);
    assert!(full.get("matchIndex").is_none() || full["matchIndex"].is_null());
    assert!(full.as_object().unwrap().get("nextCursor").is_none());
}

#[test]
fn api_history_rejects_malformed_offset_and_order() {
    let store = representative_store();
    let inspector = Inspector::spawn(store.repo.path());

    assert!(
        inspector
            .get_error("/api/history?offset=abc")
            .0
            .contains("400")
    );
    assert!(
        inspector
            .get_error("/api/history?order=sideways")
            .0
            .contains("400")
    );
}

#[test]
fn api_history_reflects_a_new_event_after_an_append() {
    let store = representative_store();
    let inspector = Inspector::spawn(store.repo.path());

    let before = inspector.get_json("/api/history")["matchCount"]
        .as_u64()
        .unwrap();

    // Append a new event: a second capture over a changed worktree records a new
    // work_object_proposed event, bumping event_log_head_marker so the projection
    // cache invalidates (INV-5).
    store.repo.write(
        "src/lib.rs",
        "pub fn value() -> u32 {\n    99\n}\n\npub fn other() -> u32 {\n    7\n}\n",
    );
    capture(store.repo.path());

    let after = inspector.get_json("/api/history")["matchCount"]
        .as_u64()
        .unwrap();
    assert!(
        after > before,
        "the cache invalidates on a new event (marker changed): {before} -> {after}"
    );
}

/// A swept note body must not kill the inspector: the revision detail hydrates
/// with `include_body` hardcoded, and the history base cache hydrates every
/// body — both previously hard-errored on a removed-and-swept blob.
#[test]
fn inspector_serves_revision_and_history_over_a_swept_body() {
    let repo = GitRepo::new();
    repo.write("src/lib.rs", "pub fn value() -> u32 { 1 }\n");
    repo.commit_all("base");
    repo.write("src/lib.rs", "pub fn value() -> u32 { 2 }\n");
    let revision_id = capture(repo.path());
    let arg = repo.path().to_str().unwrap();

    let body = "x".repeat(5000);
    let observation = shore_env(
        [
            "observation",
            "add",
            "--repo",
            arg,
            "--track",
            "agent:codex",
            "--title",
            "a large observation",
            "--body",
            &body,
        ],
        &[],
    );
    assert!(
        observation.status.success(),
        "observation add stderr:\n{}",
        String::from_utf8_lossy(&observation.stderr)
    );
    let removed = shore_env(
        ["store", "remove", "--repo", arg, "--revision", &revision_id],
        &[],
    );
    assert!(removed.status.success());
    let compacted = shore_env(["store", "compact", "--repo", arg, "--yes"], &[]);
    assert!(compacted.status.success());

    let inspector = Inspector::spawn(repo.path());

    let revision = inspector.get_json(&format!("/api/revisions/{}", urlencode(&revision_id)));
    let entry = &revision["observations"][0];
    assert!(entry.get("body").is_none());
    assert_eq!(entry["bodyContentState"], "physically_removed");

    let history = inspector.get_json("/api/history");
    assert_eq!(history["schema"], "pointbreak.inspect-history");
    assert!(
        !history["entries"].as_array().unwrap().is_empty(),
        "the always-hydrating history base cache must survive a swept body"
    );
}