galdr 0.15.0

Record & Replay for agent skills — capture a session's tool calls and distill them into a reproducible skill. Local-first.
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
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
//! End-to-end tests that drive the compiled `galdr` binary.
//!
//! Each test runs in its own temporary `HOME`, so `~/.galdr` and `~/.agents` are
//! isolated and the tests are hermetic and parallel-safe. The binary path comes
//! from `CARGO_BIN_EXE_galdr`, which cargo sets for integration tests.

use std::io::{Read, Write};
use std::net::TcpStream;
use std::path::{Path, PathBuf};
use std::process::{Command, Output, Stdio};

fn bin() -> &'static str {
    env!("CARGO_BIN_EXE_galdr")
}

/// An isolated `HOME` with a `galdr` command builder.
struct Sandbox {
    home: tempfile::TempDir,
}

impl Sandbox {
    fn new() -> Self {
        Self {
            home: tempfile::tempdir().unwrap(),
        }
    }

    fn home(&self) -> &Path {
        self.home.path()
    }

    fn cmd(&self) -> Command {
        let mut command = Command::new(bin());
        command.env("HOME", self.home.path());
        command
    }

    fn run(&self, args: &[&str]) -> Output {
        self.cmd().args(args).output().unwrap()
    }

    /// Feeds a PostToolUse event to the sensor on stdin.
    fn hook(&self, json: &str, fail: bool) -> Output {
        let mut command = self.cmd();
        command.arg("hook");
        if fail {
            command.env("GALDR_HOOK_FAIL", "1");
        }
        let mut child = command
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .unwrap();
        child
            .stdin
            .take()
            .unwrap()
            .write_all(json.as_bytes())
            .unwrap();
        child.wait_with_output().unwrap()
    }

    fn span_lines(&self, rec_id: &str) -> usize {
        let path = self
            .home()
            .join(".galdr/spans")
            .join(format!("{rec_id}.jsonl"));
        std::fs::read_to_string(path)
            .map(|s| s.lines().filter(|l| !l.trim().is_empty()).count())
            .unwrap_or(0)
    }

    /// The rec_id of the in-progress recording (read from the `active` flag,
    /// since `recordings/` is only written on stop).
    fn active_rec_id(&self) -> String {
        let raw = std::fs::read_to_string(self.home().join(".galdr/active")).unwrap();
        let value: serde_json::Value = serde_json::from_str(&raw).unwrap();
        value["rec_id"].as_str().unwrap().to_string()
    }

    fn recording_ids(&self) -> Vec<String> {
        let dir = self.home().join(".galdr/recordings");
        let mut ids: Vec<String> = std::fs::read_dir(dir)
            .map(|entries| {
                entries
                    .flatten()
                    .filter_map(|entry| {
                        let path = entry.path();
                        if path.extension()?.to_str()? == "json" {
                            Some(path.file_stem()?.to_str()?.to_string())
                        } else {
                            None
                        }
                    })
                    .collect()
            })
            .unwrap_or_default();
        ids.sort();
        ids
    }

    /// Records a sequence of events under `name` and returns the rec_id.
    fn record(&self, name: &str, events: &[&str]) -> String {
        let before = self.recording_ids();
        assert!(self.run(&["rec", "start", name]).status.success());
        for event in events {
            assert!(self.hook(event, false).status.success());
        }
        assert!(self.run(&["rec", "stop"]).status.success());
        self.recording_ids()
            .into_iter()
            .find(|id| !before.contains(id))
            .expect("a new recording id")
    }

    fn skill_md(&self, skill_name: &str) -> String {
        let path = self
            .home()
            .join(".agents/skills")
            .join(skill_name)
            .join("SKILL.md");
        std::fs::read_to_string(path).unwrap()
    }
}

fn stdout(output: &Output) -> String {
    String::from_utf8_lossy(&output.stdout).into_owned()
}

fn stderr(output: &Output) -> String {
    String::from_utf8_lossy(&output.stderr).into_owned()
}

const BASH_STATUS: &str =
    r#"{"tool_name":"Bash","tool_input":{"command":"git status"},"tool_response":{}}"#;

fn write_human_recording(sb: &Sandbox, rec_id: &str, name: &str, value: serde_json::Value) {
    let root = sb.home().join(".galdr");
    std::fs::create_dir_all(root.join("spans")).unwrap();
    std::fs::create_dir_all(root.join("recordings")).unwrap();
    let event = serde_json::json!({
        "ts": "2026-06-30T00:00:00Z",
        "seq": 0,
        "tool_name": "human.browser.input",
        "tool_input": {},
        "tool_response": {},
        "event_kind": "human",
        "human": {
            "source": {
                "kind": "browser",
                "url": "https://example.test/issues/new",
                "title": "New issue"
            },
            "action": "human.browser.input",
            "target": {
                "primary": {
                    "kind": "label",
                    "value": "Issue title"
                },
                "label": "Issue title"
            },
            "value": value,
            "verification_hint": "Confirm the issue was saved."
        }
    });
    std::fs::write(
        root.join("spans").join(format!("{rec_id}.jsonl")),
        format!("{}\n", serde_json::to_string(&event).unwrap()),
    )
    .unwrap();
    let recording = serde_json::json!({
        "rec_id": rec_id,
        "name": name,
        "started_at": "2026-06-30T00:00:00Z",
        "ended_at": "2026-06-30T00:01:00Z",
        "steps": 1,
        "cwd": null
    });
    std::fs::write(
        root.join("recordings").join(format!("{rec_id}.json")),
        serde_json::to_string_pretty(&recording).unwrap(),
    )
    .unwrap();
}

fn active_browser_port(sb: &Sandbox) -> u16 {
    let raw =
        std::fs::read_to_string(sb.home().join(".galdr/observe/browser-active.json")).unwrap();
    let value: serde_json::Value = serde_json::from_str(&raw).unwrap();
    value["port"].as_u64().unwrap() as u16
}

fn post_browser_event(port: u16, event: serde_json::Value) {
    let body = serde_json::to_string(&event).unwrap();
    let mut stream = TcpStream::connect(("127.0.0.1", port)).unwrap();
    let request = format!(
        "POST /event HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{}",
        body.len(),
        body
    );
    stream.write_all(request.as_bytes()).unwrap();
    let mut response = String::new();
    stream.read_to_string(&mut response).unwrap();
    assert!(
        response.starts_with("HTTP/1.1 204"),
        "unexpected response: {response}"
    );
}

#[test]
fn json_output_is_machine_readable() {
    // The CLI is the AI-first surface: every --json flag must emit a single,
    // parseable JSON document an agent can consume without scraping a table.
    let sb = Sandbox::new();
    let id = sb.record("json task", &[BASH_STATUS]);

    let refined = sb.home().join("r.md");
    std::fs::write(
        &refined,
        format!(
            "---\nname: galdr-json-task\ndescription: \"json\"\n---\n\n## Provenance\n- rec_id: `{id}`\n\n## Goal\nx\n## Procedure\ny\n## Success criteria\nz\n"
        ),
    )
    .unwrap();
    assert!(
        sb.cmd()
            .args(["distill", &id, "--from"])
            .arg(&refined)
            .output()
            .unwrap()
            .status
            .success()
    );

    let parse = |args: &[&str]| -> serde_json::Value {
        let out = sb.run(args);
        assert!(out.status.success(), "{args:?} failed");
        serde_json::from_str(&stdout(&out))
            .unwrap_or_else(|e| panic!("{args:?} did not emit valid JSON: {e}"))
    };

    // list → array with our recording
    let list = parse(&["list", "--json"]);
    assert!(
        list.as_array()
            .unwrap()
            .iter()
            .any(|r| r["rec_id"] == id.as_str())
    );

    // show → object with steps
    let show = parse(&["show", &id, "--json"]);
    assert_eq!(show["recording"]["name"], "json task");
    assert_eq!(show["steps"].as_array().unwrap().len(), 1);

    // skills → array carrying the origin classification
    let skills = parse(&["skills", "--json"]);
    let skill = skills
        .as_array()
        .unwrap()
        .iter()
        .find(|s| s["skill_name"] == "galdr-json-task")
        .expect("the distilled skill is listed");
    assert_eq!(skill["origin"], "galdr");

    // harnesses → array, always non-empty (the known set)
    let harnesses = parse(&["harnesses", "--json"]);
    assert!(!harnesses.as_array().unwrap().is_empty());
    assert!(
        harnesses
            .as_array()
            .unwrap()
            .iter()
            .any(|h| h["key"] == "claude")
    );

    // outcome list → object with usage/labels keys
    assert!(
        sb.run(&[
            "outcome",
            "usage",
            "--skill",
            "galdr-json-task",
            "--rec",
            &id,
            "--outcome",
            "success",
        ])
        .status
        .success()
    );
    let outcomes = parse(&["outcome", "list", "--json"]);
    assert!(outcomes["usage"].is_array());
    assert!(outcomes["labels"].is_array());
}

#[test]
fn default_distill_writes_an_unauthored_draft() {
    // A replay of the tool calls is not yet a skill: the default hands the agent a
    // faithful draft to author — status draft, real steps, an authoring marker — and
    // prints the brief that tells the agent what to add and how to install it.
    let sb = Sandbox::new();
    let id = sb.record(
        "deploy preview",
        &[
            BASH_STATUS,
            r#"{"tool_name":"Write","tool_input":{"file_path":"/repo/out.txt"},"tool_response":{}}"#,
        ],
    );
    let out = sb.run(&["distill", &id]);
    assert!(out.status.success());
    let said = stdout(&out);
    assert!(said.contains("author the real skill"), "{said}");
    assert!(said.contains("galdr distill --from"), "{said}");

    let skill = sb.skill_md("galdr-deploy-preview");
    assert!(skill.contains("galdr:unauthored"), "draft marker:\n{skill}");
    for section in ["## When to use", "## Steps", "## Verification"] {
        assert!(skill.contains(section), "missing {section}:\n{skill}");
    }
    // It is catalogued as a draft, pending authoring — not final.
    let listing = stdout(&sb.run(&["skills"]));
    assert!(
        listing.contains("draft"),
        "should list as draft:\n{listing}"
    );
}

#[test]
fn fast_distill_produces_a_complete_usable_skill() {
    // `--fast` is the mechanical one-shot: a complete, valid skill in the open-standard
    // anatomy, installed as final — no authoring pass, no draft.
    let sb = Sandbox::new();
    let id = sb.record(
        "deploy preview",
        &[
            BASH_STATUS,
            r#"{"tool_name":"Write","tool_input":{"file_path":"/repo/out.txt"},"tool_response":{}}"#,
        ],
    );
    assert!(sb.run(&["distill", &id, "--fast"]).status.success());

    let skill = sb.skill_md("galdr-deploy-preview");
    for section in ["## When to use", "## Inputs", "## Steps", "## Verification"] {
        assert!(skill.contains(section), "missing {section}:\n{skill}");
    }
    assert!(!skill.contains("galdr:unauthored"));
    assert!(!skill.contains("[galdr DRAFT]"));
    assert!(!skill.contains("TODO(agent)"));
    // It scores as a complete, ready skill — not a draft.
    let listing = stdout(&sb.run(&["skills"]));
    assert!(listing.contains("final"));
    assert!(listing.contains("ready"));
}

#[test]
fn distill_name_chooses_the_skill_name() {
    // galdr supplies the mechanism; the caller brings the naming intelligence. `--name`
    // installs under a chosen, memorable name instead of the mechanical galdr-<slug>.
    let sb = Sandbox::new();
    let id = sb.record("whatever the recording was called", &[BASH_STATUS]);
    assert!(
        sb.run(&["distill", &id, "--fast", "--name", "rust-greenlight"])
            .status
            .success()
    );
    let md = sb.skill_md("rust-greenlight");
    assert!(md.contains("name: rust-greenlight"), "{md}");
    assert!(
        !sb.home()
            .join(".agents/skills/galdr-whatever-the-recording-was-called")
            .exists(),
        "the mechanical name must not also be created"
    );
    // It still validates and is classified as a galdr skill (origin is content-based,
    // not the name prefix), so dropping the prefix is safe.
    assert!(sb.run(&["validate", "rust-greenlight"]).status.success());
}

#[test]
fn validate_passes_clean_skills_and_refuses_bad_content() {
    // The gate is reachable from the CLI: a clean distilled skill validates, a file
    // carrying a personal path is refused, and --all --json is machine-readable.
    let sb = Sandbox::new();
    let id = sb.record("validate demo", &[BASH_STATUS]);
    assert!(sb.run(&["distill", &id]).status.success());

    let ok = sb.run(&["validate", "galdr-validate-demo"]);
    assert!(
        ok.status.success(),
        "a clean distilled skill must pass: {}",
        String::from_utf8_lossy(&ok.stderr)
    );

    let all = sb.run(&["validate", "--all", "--json"]);
    assert!(all.status.success());
    let parsed: serde_json::Value = serde_json::from_str(&stdout(&all)).unwrap();
    assert!(parsed.is_array(), "--json emits an array: {}", stdout(&all));

    // A file with a personal path is a hard security failure (exit non-zero).
    let bad = sb.home().join("bad.md");
    std::fs::write(
        &bad,
        "---\nname: galdr-bad\ndescription: \"x\"\n---\n\n## When to use\n\nx\n\n## Steps\n\n1. **Read** — /Users/alice/secret.txt\n\n## Verification\n\ny\n",
    )
    .unwrap();
    let refused = sb
        .cmd()
        .args(["validate", "--file"])
        .arg(&bad)
        .output()
        .unwrap();
    assert!(
        !refused.status.success(),
        "a personal path must fail the gate"
    );
}

#[test]
fn setup_codex_check_and_print_work() {
    let sb = Sandbox::new();
    let missing = stdout(&sb.run(&["setup", "codex", "--check"]));
    assert!(missing.contains("not found"));

    let snippet = stdout(&sb.run(&["setup", "codex", "--print"]));
    assert!(snippet.contains("PostToolUse"));
    assert!(snippet.contains("galdr hook"));
    // Codex skips an untrusted hook, so `--print` must spell out the trust step.
    assert!(
        snippet.contains("/hooks"),
        "print must explain trusting the hook"
    );

    let hooks = sb.home().join(".codex/hooks.json");
    std::fs::create_dir_all(hooks.parent().unwrap()).unwrap();
    std::fs::write(
        &hooks,
        r#"{"hooks":{"PostToolUse":[{"matcher":".*","hooks":[{"type":"command","command":"galdr hook"}]}]}}"#,
    )
    .unwrap();
    let configured = stdout(&sb.run(&["setup", "codex", "--check"]));
    assert!(configured.contains("is present"));
}

#[test]
fn setup_cursor_check_and_print_work() {
    let sb = Sandbox::new();
    let missing = stdout(&sb.run(&["setup", "cursor", "--check"]));
    assert!(missing.contains("not found"));

    let snippet = stdout(&sb.run(&["setup", "cursor", "--print"]));
    assert!(snippet.contains("postToolUse"));
    assert!(snippet.contains("galdr hook"));

    let hooks = sb.home().join(".cursor/hooks.json");
    std::fs::create_dir_all(hooks.parent().unwrap()).unwrap();
    std::fs::write(&hooks, snippet).unwrap();
    let configured = stdout(&sb.run(&["setup", "cursor", "--check"]));
    assert!(configured.contains("is present"));
}

#[test]
fn a_cursor_event_records_with_mapped_fields() {
    // Cursor's postToolUse payload renames two fields: `tool_output` (a JSON-stringified
    // string) for the result, and `conversation_id` for the session. The sensor maps both.
    let sb = Sandbox::new();
    let cursor_event = r#"{"tool_name":"Bash","tool_input":{"command":"ls"},"tool_output":"{\"exit_code\":0}","conversation_id":"conv-abc","cwd":"/x"}"#;
    let id = sb.record("cursor task", &[cursor_event]);
    assert_eq!(sb.span_lines(&id), 1);
    let span = std::fs::read_to_string(sb.home().join(".galdr/spans").join(format!("{id}.jsonl")))
        .unwrap();
    assert!(
        span.contains(r#""exit_code":0"#),
        "tool_output is parsed into tool_response: {span}"
    );
    assert!(
        span.contains("conv-abc"),
        "conversation_id maps to session_id: {span}"
    );
}

#[test]
fn distilled_skill_is_linked_into_installed_harnesses() {
    // The make-or-break for "R/R for Claude Code": a distilled skill must become
    // discoverable in the harness it was recorded in, not dead-end in the open
    // standard root the harness never reads.
    let sb = Sandbox::new();
    // Stand up a Claude Code skills dir so the harness is "installed" and known.
    std::fs::create_dir_all(sb.home().join(".claude/skills")).unwrap();

    let id = sb.record("link task", &[BASH_STATUS]);
    let refined = sb.home().join("r.md");
    std::fs::write(
        &refined,
        format!(
            "---\nname: galdr-link-task\ndescription: \"link\"\n---\n\n## Provenance\n- rec_id: `{id}`\n\n## Goal\nx\n## Procedure\ny\n## Success criteria\nz\n"
        ),
    )
    .unwrap();
    assert!(
        sb.cmd()
            .args(["distill", &id, "--from"])
            .arg(&refined)
            .output()
            .unwrap()
            .status
            .success()
    );

    // The skill is now reachable through the Claude Code skills directory.
    let linked = sb.home().join(".claude/skills/galdr-link-task/SKILL.md");
    assert!(
        linked.exists(),
        "the distilled skill must be discoverable in ~/.claude/skills"
    );
    // And it resolves back to the canonical open-standard copy.
    let canonical = sb.home().join(".agents/skills/galdr-link-task/SKILL.md");
    assert!(canonical.exists());
}

#[test]
fn link_never_clobbers_a_real_skill_already_in_the_harness() {
    let sb = Sandbox::new();
    // A user's own, hand-authored skill of the same name already lives in Claude Code.
    let existing = sb.home().join(".claude/skills/galdr-keepme");
    std::fs::create_dir_all(&existing).unwrap();
    std::fs::write(existing.join("SKILL.md"), "real user content").unwrap();

    let id = sb.record("keepme", &[BASH_STATUS]);
    let refined = sb.home().join("r.md");
    std::fs::write(
        &refined,
        format!(
            "---\nname: galdr-keepme\ndescription: \"x\"\n---\n\n## Provenance\n- rec_id: `{id}`\n\n## Goal\nx\n## Procedure\ny\n## Success criteria\nz\n"
        ),
    )
    .unwrap();
    assert!(
        sb.cmd()
            .args(["distill", &id, "--from"])
            .arg(&refined)
            .output()
            .unwrap()
            .status
            .success()
    );

    // The user's real file is untouched (not replaced by a symlink).
    let content =
        std::fs::read_to_string(sb.home().join(".claude/skills/galdr-keepme/SKILL.md")).unwrap();
    assert_eq!(content, "real user content");
    assert!(
        !sb.home()
            .join(".claude/skills/galdr-keepme")
            .symlink_metadata()
            .unwrap()
            .file_type()
            .is_symlink()
    );

    // `galdr link --json` reports the conflict rather than silently failing.
    let out = sb.run(&["link", "--skill", "galdr-keepme", "--json"]);
    let results: serde_json::Value = serde_json::from_str(&stdout(&out)).unwrap();
    assert!(
        results
            .as_array()
            .unwrap()
            .iter()
            .any(|r| r["harness"] == "Claude Code" && r["status"] == "conflict")
    );
}

#[test]
fn link_rejects_path_traversal_in_skill_name() {
    // `galdr link --skill ../x` must not escape the skills root to create a symlink
    // at an arbitrary sibling path.
    let sb = Sandbox::new();
    let out = sb.run(&["link", "--skill", "../evil"]);
    assert!(
        !out.status.success(),
        "path-traversal skill name must be rejected"
    );
    let err = String::from_utf8_lossy(&out.stderr);
    assert!(
        err.contains("path separator") || err.contains("invalid skill name"),
        "{err}"
    );
    // Nothing got created outside the skills dir.
    assert!(!sb.home().join(".claude/evil").exists());
}

#[test]
fn export_redact_scrubs_secrets_from_every_file_not_just_raw() {
    // The worst redaction bug: --redact scrubbed raw.redacted.jsonl but left the
    // secret in steps.md (the Bash command summary). It must scrub all files.
    let sb = Sandbox::new();
    let id = sb.record(
        "leaky",
        &[r#"{"tool_name":"Bash","tool_input":{"command":"curl -H 'Authorization: Bearer ghp_SECRETtoken123' https://api"},"tool_response":{}}"#],
    );
    let out = sb.home().join("exp");
    assert!(
        sb.cmd()
            .args(["export", &id, "--out"])
            .arg(&out)
            .arg("--redact")
            .output()
            .unwrap()
            .status
            .success()
    );
    for file in ["steps.md", "raw.redacted.jsonl"] {
        let content = std::fs::read_to_string(out.join(file)).unwrap();
        assert!(
            !content.contains("ghp_SECRETtoken123"),
            "{file} still leaks the secret:\n{content}"
        );
    }
    assert!(
        std::fs::read_to_string(out.join("steps.md"))
            .unwrap()
            .contains("[REDACTED]")
    );
}

#[test]
fn galdr_root_is_locked_to_the_owner() {
    // Spans hold raw tool data; another local user must not be able to read them.
    let sb = Sandbox::new();
    sb.record("private", &[BASH_STATUS]);
    let meta = std::fs::metadata(sb.home().join(".galdr")).unwrap();
    use std::os::unix::fs::PermissionsExt;
    assert_eq!(
        meta.permissions().mode() & 0o077,
        0,
        "~/.galdr must be 0700 (no group/other access)"
    );
}

#[test]
fn hook_survives_an_oversized_payload() {
    // A hostile/huge stdin must not crash the sensor; it caps the read and drops the
    // (truncated, unparseable) event, still exiting 0.
    let sb = Sandbox::new();
    assert!(sb.run(&["rec", "start", "big"]).status.success());
    let id = sb.active_rec_id();
    let huge = format!(
        r#"{{"tool_name":"Bash","tool_input":{{"command":"{}"}},"tool_response":{{}}}}"#,
        "A".repeat(2_000_000)
    );
    let out = sb.hook(&huge, false);
    assert!(out.status.success(), "the sensor must always exit 0");
    // A 2 MB payload is under the cap, so it records; the point is it does not crash.
    assert!(sb.span_lines(&id) <= 1);
}

#[test]
fn computer_use_screenshots_are_dropped_but_actions_recorded() {
    // galdr captures an agent's Computer Use as tool calls, but the screenshot (a big
    // base64 image, possibly sensitive) is dropped from the span — only the action stays.
    let sb = Sandbox::new();
    assert!(sb.run(&["rec", "start", "gui task"]).status.success());
    let id = sb.active_rec_id();
    let blob = "iVBORw0KGgoAAAANSUhEUg".repeat(80);
    let shot = format!(
        r#"{{"tool_name":"mcp__computer-use__computer","tool_input":{{"action":"screenshot"}},"tool_response":{{"type":"image","source":{{"type":"base64","media_type":"image/png","data":"{blob}"}}}},"session_id":"s1"}}"#
    );
    assert!(sb.hook(&shot, false).status.success());
    assert!(
        sb.hook(
            r#"{"tool_name":"mcp__computer-use__computer","tool_input":{"action":"type","text":"42.50"},"tool_response":{},"session_id":"s1"}"#,
            false,
        )
        .status
        .success()
    );
    assert!(sb.run(&["rec", "stop"]).status.success());

    let span = std::fs::read_to_string(sb.home().join(".galdr/spans").join(format!("{id}.jsonl")))
        .unwrap();
    assert!(
        !span.contains("iVBORw0KGgo"),
        "the screenshot base64 must be dropped"
    );
    assert!(span.contains("stripped screenshot"));

    // The actions read cleanly in `show`.
    let show = stdout(&sb.run(&["show", &id]));
    assert!(show.contains("screenshot"));
    assert!(show.contains("type \"42.50\""), "got: {show}");
}

#[test]
fn a_typed_secret_is_redacted_from_the_distilled_skill() {
    // A Computer Use `type` of a token must not be promoted into the installed,
    // shareable SKILL.md (Inputs or Steps).
    let sb = Sandbox::new();
    let id = sb.record(
        "login flow",
        &[
            r#"{"tool_name":"mcp__computer-use__computer","tool_input":{"action":"type","text":"ghp_SUPERSECRETtoken123"},"tool_response":{}}"#,
        ],
    );
    assert!(sb.run(&["distill", &id]).status.success());
    let skill = sb.skill_md("galdr-login-flow");
    assert!(
        !skill.contains("ghp_SUPERSECRETtoken123"),
        "secret leaked into skill:\n{skill}"
    );
    assert!(skill.contains("[REDACTED]"));
}

#[test]
fn sensor_never_breaks_the_session() {
    let sb = Sandbox::new();

    // No active recording: a no-op, still exit 0.
    assert!(sb.hook(BASH_STATUS, false).status.success());

    assert!(sb.run(&["rec", "start", "demo"]).status.success());
    let id = sb.active_rec_id();

    // Active recording: appends and exits 0.
    assert!(sb.hook(BASH_STATUS, false).status.success());
    assert_eq!(sb.span_lines(&id), 1);

    // Forced internal failure: still exit 0, and nothing appended.
    let failed = sb.hook(BASH_STATUS, true);
    assert!(failed.status.success(), "the sensor must always exit 0");
    assert_eq!(sb.span_lines(&id), 1, "a failed hook must not append");
}

#[test]
fn recording_scopes_to_the_session_that_started_it() {
    // A single global `active` flag means every concurrent agent session's hook
    // sees this recording. The sensor must bind to the starting session and refuse
    // events from another session, so a parallel session in another project cannot
    // leak its tool calls into this span.
    let sb = Sandbox::new();
    assert!(sb.run(&["rec", "start", "scoped"]).status.success());
    let id = sb.active_rec_id();

    // First event carrying a session id binds the recording (no cwd → binds).
    assert!(
        sb.hook(
            r#"{"tool_name":"Bash","tool_input":{"command":"mine-1"},"tool_response":{},"session_id":"mine"}"#,
            false,
        )
        .status
        .success()
    );
    // A different session's event, in another directory, must be dropped.
    assert!(
        sb.hook(
            r#"{"tool_name":"Bash","tool_input":{"command":"leak"},"tool_response":{},"session_id":"other","cwd":"/elsewhere"}"#,
            false,
        )
        .status
        .success()
    );
    // The bound session keeps recording.
    assert!(
        sb.hook(
            r#"{"tool_name":"Read","tool_input":{"file_path":"/x"},"tool_response":{},"session_id":"mine"}"#,
            false,
        )
        .status
        .success()
    );

    assert_eq!(
        sb.span_lines(&id),
        2,
        "only the bound session's events record"
    );
    let span = std::fs::read_to_string(sb.home().join(".galdr/spans").join(format!("{id}.jsonl")))
        .unwrap();
    assert!(
        !span.contains("leak"),
        "the foreign session's command must not leak in: {span}"
    );
    assert!(!span.contains("\"other\""));
}

#[test]
fn record_list_show_work_without_a_daemon() {
    let sb = Sandbox::new();
    let id = sb.record(
        "demo task",
        &[
            BASH_STATUS,
            r#"{"tool_name":"Write","tool_input":{"file_path":"/tmp/out.md"},"tool_response":{}}"#,
        ],
    );

    let list = sb.run(&["list"]);
    assert!(list.status.success());
    let listing = stdout(&list);
    assert!(
        listing.contains("demo task"),
        "list shows the name: {listing}"
    );
    assert!(listing.contains("2 steps"), "list shows the step count");

    let show = sb.run(&["show", &id]);
    assert!(show.status.success());
    let detail = stdout(&show);
    assert!(detail.contains("Bash"));
    assert!(detail.contains("Write"));
    assert!(detail.contains("git status"));
}

#[test]
fn distill_from_installs_and_skills_lists_provenance() {
    let sb = Sandbox::new();
    let id = sb.record("demo", &[BASH_STATUS]);

    // Install a finished skill through the sanctioned --from path. A distilled
    // skill keeps its provenance line, so the rebuilt catalog can link it back.
    let refined = sb.home().join("refined.md");
    std::fs::write(
        &refined,
        format!(
            "---\nname: galdr-demo\ndescription: \"does a thing\"\n---\n\n## Provenance\n- rec_id: `{id}`\n\n## Goal\nx\n## Procedure\ny\n## Success criteria\nz\n"
        ),
    )
    .unwrap();
    let install = sb
        .cmd()
        .args(["distill", &id, "--from"])
        .arg(&refined)
        .output()
        .unwrap();
    assert!(install.status.success());

    let skills = sb.run(&["skills"]);
    assert!(skills.status.success());
    let listing = stdout(&skills);
    assert!(
        listing.contains("galdr-demo"),
        "skills lists the skill: {listing}"
    );
    // Provenance links to the recording, not flagged orphan.
    assert!(listing.contains(&id));
    assert!(!listing.contains("orphan"));
}

#[test]
fn reindex_rebuilds_the_catalog_from_disk() {
    let sb = Sandbox::new();
    sb.record("demo", &[BASH_STATUS]);

    let reindex = sb.run(&["reindex"]);
    assert!(reindex.status.success());
    assert!(stdout(&reindex).contains("catalog rebuilt"));
    // The catalog file now exists and was rebuilt from disk.
    assert!(sb.home().join(".galdr/catalog.sqlite").exists());

    let list = sb.run(&["list"]);
    assert!(list.status.success());
    assert!(stdout(&list).contains("demo"));
}

#[test]
fn human_events_reindex_show_distill_and_export() {
    let sb = Sandbox::new();
    write_human_recording(
        &sb,
        "01HUMAN",
        "human issue form",
        serde_json::json!({
            "policy": "redacted",
            "kind": "text",
            "chars": 24
        }),
    );

    let reindex = sb.run(&["reindex"]);
    assert!(reindex.status.success(), "{}", stderr(&reindex));

    let show = sb.run(&["show", "01HUMAN", "--json"]);
    assert!(show.status.success(), "{}", stderr(&show));
    let detail: serde_json::Value = serde_json::from_str(&stdout(&show)).unwrap();
    assert_eq!(detail["steps"][0]["event_kind"], "human");
    assert_eq!(
        detail["steps"][0]["summary"],
        "type into \"Issue title\" (text, 24 chars)"
    );

    let distill = sb.run(&["distill", "01HUMAN", "--fast"]);
    assert!(distill.status.success(), "{}", stderr(&distill));
    let skill = sb.skill_md("galdr-human-issue-form");
    assert!(skill.contains("browser workflow"), "{skill}");
    assert!(skill.contains("type into \"Issue title\""), "{skill}");
    assert!(skill.contains("Confirm the issue was saved."), "{skill}");

    write_human_recording(
        &sb,
        "01HUMANLIT",
        "human literal",
        serde_json::json!({
            "policy": "literal",
            "value": "Visible customer escalation"
        }),
    );
    let literal_distill = sb.run(&["distill", "01HUMANLIT", "--fast"]);
    assert!(
        literal_distill.status.success(),
        "{}",
        stderr(&literal_distill)
    );
    let literal_skill = sb.skill_md("galdr-human-literal");
    assert!(
        !literal_skill.contains("Visible customer escalation"),
        "literal typed text leaked into skill:\n{literal_skill}"
    );
    assert!(
        literal_skill
            .contains("- `<Issue title>` — text for Issue title at step 1 (27 chars recorded)"),
        "{literal_skill}"
    );

    let out = sb.home().join("human-export");
    let export = sb
        .cmd()
        .args(["export", "01HUMANLIT", "--out"])
        .arg(&out)
        .arg("--redact")
        .output()
        .unwrap();
    assert!(export.status.success(), "{}", stderr(&export));
    let raw = std::fs::read_to_string(out.join("raw.redacted.jsonl")).unwrap();
    assert!(!raw.contains("Visible customer escalation"), "{raw}");
    assert!(raw.contains(r#""policy":"redacted""#), "{raw}");
    assert!(raw.contains(r#""kind":"literal""#), "{raw}");
}

#[test]
fn observe_synthetic_records_a_human_trace() {
    let sb = Sandbox::new();
    let observed = sb.run(&[
        "observe",
        "synthetic",
        "synthetic human form",
        "--fixture",
        "browser-form",
    ]);
    assert!(observed.status.success(), "{}", stderr(&observed));
    let said = stdout(&observed);
    assert!(said.contains("observed \"synthetic human form\""), "{said}");

    let list = stdout(&sb.run(&["list"]));
    assert!(list.contains("synthetic human form"), "{list}");
    assert!(list.contains("4 steps"), "{list}");

    let show = sb.run(&["show", "synthetic human form", "--json"]);
    assert!(show.status.success(), "{}", stderr(&show));
    let detail: serde_json::Value = serde_json::from_str(&stdout(&show)).unwrap();
    assert_eq!(detail["recording"]["name"], "synthetic human form");
    assert_eq!(detail["steps"].as_array().unwrap().len(), 4);
    assert!(
        detail["steps"]
            .as_array()
            .unwrap()
            .iter()
            .all(|step| step["event_kind"] == "human")
    );
    assert_eq!(
        detail["steps"][0]["summary"],
        "navigate https://example.test/issues/new"
    );
    assert_eq!(
        detail["steps"][1]["summary"],
        "type into \"Issue title\" (text, 24 chars)"
    );
    assert_eq!(
        detail["steps"][2]["summary"],
        "select \"Priority\" = \"High\""
    );
    assert_eq!(
        detail["steps"][3]["summary"],
        "click button \"Create issue\""
    );

    let distill = sb.run(&["distill", "synthetic human form", "--fast"]);
    assert!(distill.status.success(), "{}", stderr(&distill));
    let skill = sb.skill_md("galdr-synthetic-human-form");
    assert!(skill.contains("browser workflow"), "{skill}");
    assert!(
        skill.contains("navigate https://example.test/issues/new"),
        "{skill}"
    );
    assert!(skill.contains("select \"Priority\" = \"High\""), "{skill}");
    assert!(
        skill.contains("Confirm the created issue page is open or a success message appears."),
        "{skill}"
    );
}

#[test]
fn observe_browser_collector_records_loopback_events() {
    let sb = Sandbox::new();
    let start = sb.run(&[
        "observe",
        "browser",
        "start",
        "browser collector",
        "--url",
        "https://example.test/form",
        "--no-open",
    ]);
    assert!(start.status.success(), "{}", stderr(&start));
    let port = active_browser_port(&sb);

    post_browser_event(
        port,
        serde_json::json!({
            "ts": "2026-06-30T00:00:00Z",
            "action": "human.browser.navigate",
            "source": {
                "kind": "browser",
                "url": "https://example.test/form",
                "title": "Demo form"
            }
        }),
    );
    post_browser_event(
        port,
        serde_json::json!({
            "ts": "2026-06-30T00:00:01Z",
            "action": "human.browser.input",
            "source": {
                "kind": "browser",
                "url": "https://example.test/form",
                "title": "Demo form"
            },
            "target": {
                "primary": {
                    "kind": "label",
                    "value": "Email"
                },
                "label": "Email"
            },
            "value": {
                "policy": "redacted",
                "kind": "text",
                "chars": 16
            }
        }),
    );

    let status = stdout(&sb.run(&["observe", "browser", "status"]));
    assert!(status.contains("events: 2"), "{status}");
    assert!(status.contains("server: up"), "{status}");

    let stop = sb.run(&["observe", "browser", "stop"]);
    assert!(stop.status.success(), "{}", stderr(&stop));
    let said = stdout(&stop);
    assert!(said.contains("stopped browser observation"), "{said}");
    assert!(said.contains("2 human steps"), "{said}");

    let show = sb.run(&["show", "browser collector", "--json"]);
    assert!(show.status.success(), "{}", stderr(&show));
    let detail: serde_json::Value = serde_json::from_str(&stdout(&show)).unwrap();
    assert_eq!(detail["steps"].as_array().unwrap().len(), 2);
    assert_eq!(detail["steps"][0]["event_kind"], "human");
    assert_eq!(
        detail["steps"][0]["summary"],
        "navigate https://example.test/form"
    );
    assert_eq!(
        detail["steps"][1]["summary"],
        "type into \"Email\" (text, 16 chars)"
    );
}

#[test]
fn recording_writes_keep_an_existing_catalog_current_without_a_daemon() {
    let sb = Sandbox::new();
    sb.record("first", &[BASH_STATUS]);
    assert!(sb.run(&["reindex"]).status.success());

    let second = sb.record(
        "second",
        &[r#"{"tool_name":"Read","tool_input":{"file_path":"/tmp/input.md"},"tool_response":{}}"#],
    );

    let list = sb.run(&["list"]);
    assert!(list.status.success());
    let listing = stdout(&list);
    assert!(
        listing.contains("second"),
        "list should not read a stale catalog: {listing}"
    );

    let show = sb.run(&["show", &second]);
    assert!(show.status.success());
    let detail = stdout(&show);
    assert!(
        detail.contains("/tmp/input.md"),
        "show should include the newly indexed step: {detail}"
    );
}

#[test]
fn skill_writes_keep_an_existing_catalog_current_without_a_daemon() {
    let sb = Sandbox::new();
    let id = sb.record("stale catalog", &[BASH_STATUS]);
    assert!(sb.run(&["reindex"]).status.success());

    let refined = sb.home().join("refined.md");
    std::fs::write(
        &refined,
        format!(
            "---\nname: galdr-stale-catalog\ndescription: \"stale catalog check\"\n---\n\n## Provenance\n- rec_id: `{id}`\n\n## Goal\nx\n## Procedure\ny\n## Success criteria\nz\n"
        ),
    )
    .unwrap();
    let install = sb
        .cmd()
        .args(["distill", &id, "--from"])
        .arg(&refined)
        .output()
        .unwrap();
    assert!(install.status.success());

    let skills = sb.run(&["skills"]);
    assert!(skills.status.success());
    let listing = stdout(&skills);
    assert!(
        listing.contains("galdr-stale-catalog"),
        "skills should not read a stale catalog: {listing}"
    );
    assert!(listing.contains(&id));
}

#[test]
fn draft_distill_keeps_an_existing_catalog_current_without_a_daemon() {
    let sb = Sandbox::new();
    let id = sb.record("draft catalog", &[BASH_STATUS]);
    assert!(sb.run(&["reindex"]).status.success());

    let draft = sb.run(&["distill", &id]);
    assert!(draft.status.success());

    let skills = sb.run(&["skills"]);
    assert!(skills.status.success());
    let listing = stdout(&skills);
    assert!(
        listing.contains("galdr-draft-catalog"),
        "draft distillation should update an existing catalog: {listing}"
    );
    assert!(listing.contains(&id));
}

#[test]
fn parametrize_emit_keeps_an_existing_catalog_current_without_a_daemon() {
    let sb = Sandbox::new();
    let write = |path: &str| {
        format!(
            r#"{{"tool_name":"Write","tool_input":{{"file_path":"{path}"}},"tool_response":{{}}}}"#
        )
    };
    let a = sb.record("ship", &[BASH_STATUS, &write("/repo-a/out.md")]);
    let b = sb.record("ship", &[BASH_STATUS, &write("/repo-b/out.md")]);
    assert!(sb.run(&["reindex"]).status.success());

    let emit = sb.run(&["parametrize", &a, &b, "--emit"]);
    assert!(emit.status.success());

    let skills = sb.run(&["skills"]);
    assert!(skills.status.success());
    let listing = stdout(&skills);
    assert!(
        listing.contains("galdr-ship-param"),
        "parametrize should update an existing catalog: {listing}"
    );
    assert!(listing.contains(&a));
}

#[test]
fn parametrize_emits_a_templated_skill() {
    let sb = Sandbox::new();
    let write = |path: &str| {
        format!(
            r#"{{"tool_name":"Write","tool_input":{{"file_path":"{path}"}},"tool_response":{{}}}}"#
        )
    };
    let a = sb.record("ship", &[BASH_STATUS, &write("/repo-a/out.md")]);
    let b = sb.record("ship", &[BASH_STATUS, &write("/repo-b/out.md")]);

    let emit = sb.run(&["parametrize", &a, &b, "--emit"]);
    assert!(
        emit.status.success(),
        "{}",
        String::from_utf8_lossy(&emit.stderr)
    );

    let skill = sb.skill_md("galdr-ship-param");
    assert!(skill.contains("## Parameters"));
    assert!(skill.contains("## Procedure (parametrized)"));
    assert!(skill.contains("{{OUT}}"), "the output path is templated");
    assert!(
        !skill.contains("LOW-CONFIDENCE"),
        "a clean alignment is high confidence"
    );
}

#[test]
fn parametrize_marks_divergent_recordings_low_confidence() {
    let sb = Sandbox::new();
    let a = sb.record(
        "task",
        &[
            BASH_STATUS,
            r#"{"tool_name":"Read","tool_input":{"file_path":"/a.rs"},"tool_response":{}}"#,
        ],
    );
    let b = sb.record(
        "task",
        &[r#"{"tool_name":"Glob","tool_input":{"pattern":"*.rs"},"tool_response":{}}"#],
    );

    assert!(sb.run(&["parametrize", &a, &b, "--emit"]).status.success());
    let skill = sb.skill_md("galdr-task-param");
    assert!(skill.contains("LOW-CONFIDENCE"));
    assert!(skill.contains("## Alignment notes"));
}

#[test]
fn distill_auto_falls_back_to_a_complete_skill_without_an_engine() {
    let sb = Sandbox::new();
    let id = sb.record("auto demo", &[BASH_STATUS]);

    // No MLX server and no Python mlx_lm: --auto must fall back to a usable, complete
    // skill (not a dead-end draft) and exit 0.
    let auto = sb.run(&["distill", &id, "--auto"]);
    assert!(
        auto.status.success(),
        "--auto must exit 0 even with no engine"
    );
    let skill = sb.skill_md("galdr-auto-demo");
    assert!(skill.contains("galdr-auto-demo"));
    // The fallback is complete: the open-standard anatomy, no draft markers.
    assert!(skill.contains("## When to use"));
    assert!(skill.contains("## Verification"));
    assert!(!skill.contains("[galdr DRAFT]"));
}

#[test]
fn diff_reports_constants_and_parameters() {
    let sb = Sandbox::new();
    let write = |path: &str| {
        format!(
            r#"{{"tool_name":"Write","tool_input":{{"file_path":"{path}"}},"tool_response":{{}}}}"#
        )
    };
    let a = sb.record("ship", &[BASH_STATUS, &write("/repo-a/out.md")]);
    let b = sb.record("ship", &[BASH_STATUS, &write("/repo-b/out.md")]);

    let diff = sb.run(&["diff", &a, &b]);
    assert!(diff.status.success());
    let report = stdout(&diff);
    assert!(report.contains("confidence: HIGH"));
    assert!(report.contains("OUT"), "the output path is a parameter");
    assert!(report.contains("Constants:"));
}

#[test]
fn suggest_surfaces_repeated_tasks_and_dedupes_distilled_ones() {
    let sb = Sandbox::new();
    let write = |path: &str| {
        format!(
            r#"{{"tool_name":"Write","tool_input":{{"file_path":"{path}"}},"tool_response":{{}}}}"#
        )
    };
    // Two runs of the same shape (Bash + a Write), different paths, plus a distinct
    // one-off that must not be reported as repeated.
    let a = sb.record("ship", &[BASH_STATUS, &write("/repo-a/out.md")]);
    let _b = sb.record("ship", &[BASH_STATUS, &write("/repo-b/out.md")]);
    let _c = sb.record("oneoff", &[BASH_STATUS]);

    let parse = |args: &[&str]| -> serde_json::Value {
        let out = sb.run(args);
        assert!(out.status.success(), "{args:?} failed");
        serde_json::from_str(&stdout(&out))
            .unwrap_or_else(|e| panic!("{args:?} did not emit valid JSON: {e}"))
    };

    // At the default threshold (2) only the repeated shape surfaces, counted twice.
    let opps = parse(&["suggest", "--json"]);
    let arr = opps.as_array().expect("an array of opportunities");
    assert_eq!(arr.len(), 1, "only the repeated shape is an opportunity");
    assert_eq!(arr[0]["count"], 2);
    let recs = arr[0]["recordings"].as_array().unwrap();
    assert_eq!(recs.len(), 2);

    // Distilling one run of the shape dedupes it out: nothing repeated remains.
    assert!(sb.run(&["distill", &a]).status.success());
    let after = parse(&["suggest", "--json"]);
    assert!(
        after.as_array().unwrap().is_empty(),
        "an installed skill dedupes its shape out of the opportunities"
    );
}

#[test]
fn bare_galdr_shows_a_friendly_overview() {
    // `galdr` with no subcommand is a human at a terminal — show a home screen, not a
    // clap usage error. Piped (not a TTY), the output is plain text with no ANSI codes.
    let sb = Sandbox::new();
    sb.record("demo-task", &[BASH_STATUS]);

    let out = sb.run(&[]);
    assert!(out.status.success(), "bare `galdr` must exit 0");
    let text = stdout(&out);
    assert!(text.contains("galdr"), "{text}");
    assert!(text.contains("next"), "shows next steps: {text}");
    assert!(text.contains("galdr rec start"), "{text}");
    assert!(
        text.contains("1 recordings"),
        "reflects the catalog: {text}"
    );
    assert!(
        !text.contains('\u{1b}'),
        "no ANSI escapes when piped: {text:?}"
    );
}

#[test]
fn recording_references_resolve_without_a_ulid() {
    // The human DX: never type a 26-char id. `distill`/`show` default to the most
    // recent recording and also accept a recording name.
    let sb = Sandbox::new();
    let older = sb.record("weekly-report", &[BASH_STATUS]);
    let newest = sb.record("ship-preview", &[BASH_STATUS]);

    // `galdr distill` with no argument distills the most recent recording.
    assert!(sb.run(&["distill"]).status.success());
    let skill = sb.skill_md("galdr-ship-preview");
    assert!(
        skill.contains(&newest),
        "the newest recording was distilled"
    );

    // `galdr show <name>` resolves by name (and is not the newest here).
    let shown = sb.run(&["show", "weekly-report", "--json"]);
    assert!(shown.status.success());
    let detail: serde_json::Value = serde_json::from_str(&stdout(&shown)).unwrap();
    assert_eq!(detail["recording"]["rec_id"], older.as_str());

    // The full id still works, and a miss fails with guidance, not a cryptic id error.
    assert!(sb.run(&["show", &newest]).status.success());
    let miss = sb.run(&["show", "does-not-exist"]);
    assert!(!miss.status.success());
    assert!(stderr(&miss).contains("galdr list"));
}

#[test]
fn suggest_and_bench_render_human_reports() {
    let sb = Sandbox::new();
    // Empty install: both report nothing to do, in words, without panicking.
    assert!(sb.run(&["suggest"]).status.success());
    assert!(stdout(&sb.run(&["suggest"])).contains("No repeated"));
    assert!(stdout(&sb.run(&["bench"])).contains("No replay outcomes"));

    // A repeated shape surfaces in the human suggest table.
    let write = |path: &str| {
        format!(
            r#"{{"tool_name":"Write","tool_input":{{"file_path":"{path}"}},"tool_response":{{}}}}"#
        )
    };
    let id = sb.record("ship", &[BASH_STATUS, &write("/a/out.md")]);
    sb.record("ship", &[BASH_STATUS, &write("/b/out.md")]);
    let suggest = stdout(&sb.run(&["suggest"]));
    assert!(suggest.contains("Skill opportunities"), "{suggest}");
    assert!(suggest.contains("galdr distill"), "{suggest}");

    // A recorded outcome surfaces in the human bench table.
    let refined = sb.home().join("s.md");
    std::fs::write(
        &refined,
        format!(
            "---\nname: galdr-ship\ndescription: \"ship\"\n---\n\n## Provenance\n- rec_id: `{id}`\n\n## Goal\nx\n## Procedure\ny\n## Success criteria\nz\n"
        ),
    )
    .unwrap();
    assert!(
        sb.cmd()
            .args(["distill", &id, "--from"])
            .arg(&refined)
            .output()
            .unwrap()
            .status
            .success()
    );
    assert!(
        sb.run(&[
            "outcome",
            "usage",
            "--skill",
            "galdr-ship",
            "--rec",
            &id,
            "--outcome",
            "success",
        ])
        .status
        .success()
    );
    let bench = stdout(&sb.run(&["bench"]));
    assert!(bench.contains("Replay reliability"), "{bench}");
    assert!(bench.contains("galdr-ship"), "{bench}");
}

#[test]
fn rec_control_rejects_double_start_and_orphan_stop() {
    let sb = Sandbox::new();
    // Stopping with nothing active is an error, not a silent success.
    let stop = sb.run(&["rec", "stop"]);
    assert!(!stop.status.success());
    assert!(stderr(&stop).contains("no active recording"));

    // Status with nothing active reports it cleanly (exit 0).
    let status = sb.run(&["rec", "status"]);
    assert!(status.status.success());
    assert!(stdout(&status).contains("no active recording"));

    // First start succeeds; a second start while one is active is refused.
    assert!(sb.run(&["rec", "start", "one"]).status.success());
    let again = sb.run(&["rec", "start", "two"]);
    assert!(!again.status.success());
    assert!(stderr(&again).contains("already active"));

    // Stop succeeds and a second stop is an orphan error again.
    assert!(sb.run(&["rec", "stop"]).status.success());
    assert!(!sb.run(&["rec", "stop"]).status.success());
}

#[test]
fn a_corrupt_active_flag_is_treated_as_not_recording() {
    let sb = Sandbox::new();
    // Establish ~/.galdr by starting and stopping once.
    assert!(sb.run(&["rec", "start", "seed"]).status.success());
    assert!(sb.run(&["rec", "stop"]).status.success());
    // Corrupt the active flag: the sensor and control must treat it as "no recording"
    // (the safe side), not crash.
    std::fs::write(sb.home().join(".galdr/active"), "}{ not json").unwrap();
    let status = sb.run(&["rec", "status"]);
    assert!(status.status.success());
    assert!(stdout(&status).contains("no active recording"));
    // And a fresh start works despite the garbage flag.
    assert!(sb.run(&["rec", "start", "fresh"]).status.success());
}

#[test]
fn list_is_empty_on_a_fresh_install() {
    let sb = Sandbox::new();
    let out = sb.run(&["list"]);
    assert!(out.status.success());
    assert!(stdout(&out).contains("no recordings yet"));
}

#[test]
fn bench_reports_replay_hit_rate_from_recorded_outcomes() {
    let sb = Sandbox::new();
    let id = sb.record("bench", &[BASH_STATUS]);
    let refined = sb.home().join("bench.md");
    std::fs::write(
        &refined,
        format!(
            "---\nname: galdr-bench\ndescription: \"bench task\"\n---\n\n## Provenance\n- rec_id: `{id}`\n\n## Goal\nx\n## Procedure\ny\n## Success criteria\nz\n"
        ),
    )
    .unwrap();
    assert!(
        sb.cmd()
            .args(["distill", &id, "--from"])
            .arg(&refined)
            .output()
            .unwrap()
            .status
            .success()
    );

    // Two recorded replays of the skill: one clean, one failed after a retry.
    let record_outcome = |outcome: &str, retries: &str| {
        sb.run(&[
            "outcome",
            "usage",
            "--skill",
            "galdr-bench",
            "--rec",
            &id,
            "--outcome",
            outcome,
            "--retries",
            retries,
        ])
    };
    assert!(record_outcome("success", "0").status.success());
    assert!(record_outcome("failed", "1").status.success());

    let out = sb.run(&["bench", "--json"]);
    assert!(out.status.success());
    let report: serde_json::Value = serde_json::from_str(&stdout(&out)).unwrap();
    assert_eq!(report["total_replays"], 2);
    assert_eq!(report["overall_success_rate"], 0.5);
    let skill = report["skills"]
        .as_array()
        .unwrap()
        .iter()
        .find(|s| s["skill_name"] == "galdr-bench")
        .expect("galdr-bench in the report");
    assert_eq!(skill["uses"], 2);
    assert_eq!(skill["success"], 1);
    assert_eq!(skill["failed"], 1);
    assert_eq!(skill["success_rate"], 0.5);
    assert_eq!(skill["avg_retries"], 0.5);
}

#[test]
fn rec_status_and_capture_policy_work() {
    let sb = Sandbox::new();
    assert!(stdout(&sb.run(&["rec", "status"])).contains("no active recording"));

    std::fs::create_dir_all(sb.home().join(".galdr")).unwrap();
    std::fs::write(
        sb.home().join(".galdr/config.json"),
        r#"{"capture":{"deny_tools":["Secret"],"deny_cwd_prefixes":["/private"],"max_response_chars":12}}"#,
    )
    .unwrap();

    assert!(sb.run(&["rec", "start", "capture"]).status.success());
    let id = sb.active_rec_id();
    assert!(
        sb.hook(
            r#"{"tool_name":"Secret","tool_input":{"value":"x"},"tool_response":{"token":"abc"}}"#,
            false,
        )
        .status
        .success()
    );
    assert_eq!(sb.span_lines(&id), 0, "denied tools are not recorded");

    assert!(
        sb.hook(
            r#"{"tool_name":"Bash","tool_input":{"command":"echo hi"},"tool_response":{"stdout":"abcdefghijklmnopqrstuvwxyz"},"cwd":"/tmp"}"#,
            false,
        )
        .status
        .success()
    );
    assert_eq!(sb.span_lines(&id), 1);
    let span = std::fs::read_to_string(sb.home().join(".galdr/spans").join(format!("{id}.jsonl")))
        .unwrap();
    assert!(span.contains("galdr_truncated"));

    let status = stdout(&sb.run(&["rec", "status"]));
    assert!(status.contains("active recording: capture"));
    assert!(status.contains("steps: 1"));
}

#[test]
fn skills_catalog_reports_status_readiness_and_delta() {
    let sb = Sandbox::new();
    let id = sb.record("readiness", &[BASH_STATUS]);

    // The default distill writes a faithful draft (status draft) until an agent
    // authors it and installs the final version with --from.
    assert!(sb.run(&["distill", &id]).status.success());
    let draft_listing = stdout(&sb.run(&["skills"]));
    assert!(draft_listing.contains("galdr-readiness"));
    assert!(draft_listing.contains("draft"));
    assert!(draft_listing.contains("readiness"));

    let refined = sb.home().join("refined.md");
    std::fs::write(
        &refined,
        format!(
            "---\nname: galdr-readiness\ndescription: \"readiness check\"\n---\n\n## Provenance\n- rec_id: `{id}`\n\n## Goal\nx\n## Procedure\ny\n## Success criteria\nz\n"
        ),
    )
    .unwrap();
    let install = sb
        .cmd()
        .args(["distill", &id, "--from"])
        .arg(&refined)
        .output()
        .unwrap();
    assert!(install.status.success());

    let final_listing = stdout(&sb.run(&["skills"]));
    assert!(final_listing.contains("final"));
    assert!(
        final_listing.contains("(+"),
        "readiness delta should show the final skill improved: {final_listing}"
    );

    let evaluations = stdout(&sb.run(&["evaluations", "--skill", "galdr-readiness"]));
    assert!(evaluations.contains("readiness_lint"));
    assert!(evaluations.contains("galdr-readiness"));
}

#[test]
fn outcome_usage_and_labels_survive_reindex() {
    let sb = Sandbox::new();
    let id = sb.record("outcome", &[BASH_STATUS]);
    let refined = sb.home().join("outcome.md");
    std::fs::write(
        &refined,
        format!(
            "---\nname: galdr-outcome\ndescription: \"outcome capture\"\n---\n\n## Provenance\n- rec_id: `{id}`\n\n## Goal\nx\n## Procedure\ny\n## Success criteria\nz\n"
        ),
    )
    .unwrap();
    let install = sb
        .cmd()
        .args(["distill", &id, "--from"])
        .arg(&refined)
        .output()
        .unwrap();
    assert!(install.status.success());

    let usage = sb.run(&[
        "outcome",
        "usage",
        "--skill",
        "galdr-outcome",
        "--rec",
        &id,
        "--task-kind",
        "smoke",
        "--outcome",
        "success",
        "--retries",
        "1",
        "--manual-interventions",
        "2",
        "--notes",
        "worked after one retry",
    ]);
    assert!(usage.status.success());
    assert!(stdout(&usage).contains("usage recorded"));

    let label = sb.run(&[
        "outcome",
        "label",
        "--skill",
        "galdr-outcome",
        "--rec",
        &id,
        "--evaluator",
        "human",
        "--label",
        "accepted",
        "--confidence",
        "0.9",
        "--notes",
        "reviewed",
    ]);
    assert!(label.status.success());
    assert!(stdout(&label).contains("outcome recorded"));

    let usage_log = sb.home().join(".galdr/outcomes/skill_usage.jsonl");
    let outcome_log = sb.home().join(".galdr/outcomes/skill_outcomes.jsonl");
    assert!(
        std::fs::read_to_string(usage_log)
            .unwrap()
            .contains("success")
    );
    assert!(
        std::fs::read_to_string(outcome_log)
            .unwrap()
            .contains("accepted")
    );

    assert!(sb.run(&["reindex"]).status.success());
    let listing = stdout(&sb.run(&["outcome", "list", "--skill", "galdr-outcome"]));
    assert!(listing.contains("success"));
    assert!(listing.contains("accepted"));
    assert!(listing.contains("interventions  2"));
}

#[test]
fn distill_from_rejects_unfinished_skills() {
    let sb = Sandbox::new();
    let id = sb.record("unfinished", &[BASH_STATUS]);
    let bad = sb.home().join("bad.md");
    std::fs::write(
        &bad,
        "---\nname: galdr-unfinished\ndescription: \"bad\"\n---\n\n## Goal\nx\n## Procedure\ny\n",
    )
    .unwrap();
    let install = sb
        .cmd()
        .args(["distill", &id, "--from"])
        .arg(&bad)
        .output()
        .unwrap();
    assert!(!install.status.success());
    assert!(String::from_utf8_lossy(&install.stderr).contains("Success criteria"));
}

#[test]
fn setup_claude_check_and_print_work_without_mutating_settings() {
    let sb = Sandbox::new();
    let missing = stdout(&sb.run(&["setup", "claude", "--check"]));
    assert!(missing.contains("settings not found"));

    let snippet = stdout(&sb.run(&["setup", "claude", "--print"]));
    assert!(snippet.contains("PostToolUse"));
    assert!(snippet.contains("galdr hook"));

    let settings = sb.home().join(".claude/settings.json");
    std::fs::create_dir_all(settings.parent().unwrap()).unwrap();
    std::fs::write(&settings, snippet).unwrap();
    let configured = stdout(&sb.run(&["setup", "claude", "--check"]));
    assert!(configured.contains("is configured"));
}

#[test]
fn export_omits_raw_by_default_and_can_write_redacted_raw() {
    let sb = Sandbox::new();
    let id = sb.record(
        "export",
        &[r#"{"tool_name":"Bash","tool_input":{"command":"deploy","api_key":"secret-key"},"tool_response":{"token":"secret-token","ok":true}}"#],
    );

    let out = sb.home().join("export-default");
    let export = sb
        .cmd()
        .args(["export", &id, "--out"])
        .arg(&out)
        .output()
        .unwrap();
    assert!(export.status.success());
    assert!(out.join("recording.json").exists());
    assert!(out.join("steps.md").exists());
    assert!(out.join("skills.json").exists());
    assert!(out.join("usage.json").exists());
    assert!(out.join("outcomes.json").exists());
    assert!(!out.join("raw.jsonl").exists());

    let redacted = sb.home().join("export-redacted");
    let export = sb
        .cmd()
        .args(["export", &id, "--out"])
        .arg(&redacted)
        .arg("--redact")
        .output()
        .unwrap();
    assert!(export.status.success());
    let raw = std::fs::read_to_string(redacted.join("raw.redacted.jsonl")).unwrap();
    assert!(raw.contains("[REDACTED]"));
    assert!(!raw.contains("secret-token"));
    assert!(!raw.contains("secret-key"));
}

#[test]
fn doctor_passes_when_claude_hook_is_configured() {
    let sb = Sandbox::new();
    let settings = sb.home().join(".claude/settings.json");
    std::fs::create_dir_all(settings.parent().unwrap()).unwrap();
    std::fs::write(
        &settings,
        r#"{"hooks":{"PostToolUse":[{"hooks":[{"type":"command","command":"galdr hook"}]}]}}"#,
    )
    .unwrap();
    let doctor = sb.run(&["doctor"]);
    assert!(
        doctor.status.success(),
        "{}\n{}",
        stdout(&doctor),
        String::from_utf8_lossy(&doctor.stderr)
    );
    assert!(stdout(&doctor).contains("doctor: ok"));
}

/// Optional daemon round-trip. Kept robust (generous polling, guaranteed
/// teardown) but isolated to its own temp HOME so it never disturbs the others.
#[test]
fn daemon_indexes_and_answers_queries() {
    let sb = Sandbox::new();
    let pidfile = sb.home().join(".galdr/galdrd.pid");
    let socket = sb.home().join(".galdr/galdrd.sock");

    assert!(stdout(&sb.run(&["daemon", "status"])).contains("daemon stopped"));
    assert!(sb.run(&["daemon", "--detach"]).status.success());

    // A guard that kills the daemon on the way out, even if an assert fails.
    struct Guard(PathBuf);
    impl Drop for Guard {
        fn drop(&mut self) {
            if let Ok(pid) = std::fs::read_to_string(&self.0)
                && let Ok(pid) = pid.trim().parse::<i32>()
            {
                let _ = Command::new("kill")
                    .arg(pid.to_string())
                    .stdout(Stdio::null())
                    .stderr(Stdio::null())
                    .status();
            }
        }
    }
    let _guard = Guard(pidfile.clone());

    // Wait for the socket to appear (up to ~5s).
    let mut ready = false;
    for _ in 0..100 {
        if socket.exists() {
            ready = true;
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(50));
    }
    assert!(ready, "daemon socket never appeared");
    assert!(stdout(&sb.run(&["daemon", "status"])).contains("daemon running"));

    sb.record("daemon demo", &[BASH_STATUS]);
    // Give the close notification a moment to be indexed.
    std::thread::sleep(std::time::Duration::from_millis(200));

    let list = sb.run(&["list"]);
    assert!(list.status.success());
    assert!(
        stdout(&list).contains("daemon demo"),
        "the daemon-backed catalog should list the recording"
    );

    let stop = sb.run(&["daemon", "stop"]);
    assert!(stop.status.success());
    assert!(stdout(&stop).contains("daemon stopped"));
}