deciduous 1.0.9

Decision graph tooling for AI-assisted development. Track every goal, decision, and outcome. Survive context loss. Query your reasoning.
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
//! Multi-user sync through real git: a bare origin, several clones, the real
//! `deciduous` binary as the CLI and as the registered merge driver.
//!
//! `sync_integration.rs` stands in for git by calling `merge-record` by hand.
//! These tests do not: they commit, push and `git pull` between clones, so
//! what they check is what a team actually sees, including the cases where
//! git does something other than what one would expect (a failed merge
//! driver leaves no conflict markers).

use serde_json::Value;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use tempfile::TempDir;

const BIN: &str = env!("CARGO_BIN_EXE_deciduous");

/// A shared origin and a scratch home. Every clone lives under one TempDir.
struct Team {
    root: TempDir,
}

/// One developer's clone.
struct Dev {
    name: String,
    dir: PathBuf,
    home: PathBuf,
    /// PATH for every process this developer runs. By default the
    /// directory holding the deciduous under test comes first, so git
    /// finds the merge driver the way it would after `cargo install`.
    path: String,
}

/// git and a shell, and no deciduous: an installed one (Homebrew, cargo)
/// must never stand in for the binary under test.
fn base_path() -> String {
    let git = Command::new("sh")
        .args(["-c", "command -v git"])
        .output()
        .unwrap();
    let git = String::from_utf8_lossy(&git.stdout).trim().to_string();
    let git_dir = Path::new(&git).parent().unwrap().display().to_string();
    assert!(
        !Path::new(&git_dir).join("deciduous").exists(),
        "git shares a directory with an installed deciduous ({git_dir})"
    );
    format!("{git_dir}:/usr/bin:/bin:/usr/sbin:/sbin")
}

fn with_bin_on_path() -> String {
    let bin_dir = Path::new(BIN).parent().unwrap();
    format!("{}:{}", bin_dir.display(), base_path())
}

impl Team {
    fn new() -> Self {
        let root = TempDir::new().unwrap();
        let origin = root.path().join("origin.git");
        let out = Command::new("git")
            .args(["init", "--bare", "-q", "-b", "main"])
            .arg(&origin)
            .output()
            .unwrap();
        assert!(
            out.status.success(),
            "{}",
            String::from_utf8_lossy(&out.stderr)
        );
        Self { root }
    }

    fn origin(&self) -> PathBuf {
        self.root.path().join("origin.git")
    }

    /// The first developer: creates the project, runs `deciduous sync` once
    /// (which creates the graph file and registers the driver), commits the
    /// setup and pushes it.
    fn founder(&self, name: &str) -> Dev {
        let dev = self.dev(name);
        fs::create_dir_all(&dev.dir).unwrap();
        dev.git(&["init", "-q", "-b", "main"]);
        dev.configure();
        fs::create_dir_all(dev.dir.join(".deciduous")).unwrap();
        fs::write(
            dev.dir.join(".gitattributes"),
            ".deciduous/graph.json merge=deciduous linguist-generated=true\n",
        )
        .unwrap();
        fs::write(
            dev.dir.join(".gitignore"),
            ".deciduous/*.db\n.deciduous/*.db-*\n",
        )
        .unwrap();
        dev.ok(&["sync"]);
        dev.commit_all("setup");
        dev.git(&["remote", "add", "origin", self.origin().to_str().unwrap()]);
        dev.git(&["push", "-q", "-u", "origin", "main"]);
        dev
    }

    /// Everyone else clones and syncs once.
    fn join(&self, name: &str) -> Dev {
        let dev = self.dev(name);
        let out = Command::new("git")
            .args(["clone", "-q"])
            .arg(self.origin())
            .arg(&dev.dir)
            .env("HOME", &dev.home)
            .output()
            .unwrap();
        assert!(
            out.status.success(),
            "{}",
            String::from_utf8_lossy(&out.stderr)
        );
        dev.configure();
        dev.ok(&["sync"]);
        dev
    }

    fn dev(&self, name: &str) -> Dev {
        let home = self.root.path().join("homes").join(name);
        fs::create_dir_all(&home).unwrap();
        Dev {
            name: name.to_string(),
            dir: self.root.path().join(name),
            home,
            path: with_bin_on_path(),
        }
    }
}

impl Dev {
    /// The same clone, to change how its processes run (e.g. PATH).
    fn clone_handle(&self) -> Dev {
        Dev {
            name: self.name.clone(),
            dir: self.dir.clone(),
            home: self.home.clone(),
            path: self.path.clone(),
        }
    }

    fn configure(&self) {
        self.git(&["config", "user.name", &self.name]);
        self.git(&[
            "config",
            "user.email",
            &format!("{}@example.test", self.name),
        ]);
        self.git(&["config", "pull.rebase", "false"]);
        self.git(&["config", "commit.gpgsign", "false"]);
    }

    fn cmd(&self, program: &str) -> Command {
        let mut c = Command::new(program);
        c.current_dir(&self.dir)
            .env("HOME", &self.home)
            .env("PATH", &self.path)
            .env("DECIDUOUS_NO_SERVER", "1")
            .env("GIT_CONFIG_NOSYSTEM", "1")
            .env_remove("DECIDUOUS_DB_PATH")
            .env_remove("DECIDUOUS_MCP_TOKEN")
            .env_remove("DECIDUOUS_API_TOKEN")
            .env_remove("XDG_CONFIG_HOME")
            .env_remove("GIT_DIR")
            .env_remove("GIT_WORK_TREE");
        c
    }

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

    fn ok(&self, args: &[&str]) -> String {
        let out = self.run(args);
        assert!(
            out.status.success(),
            "[{}] deciduous {:?} failed:\n{}\n{}",
            self.name,
            args,
            String::from_utf8_lossy(&out.stdout),
            String::from_utf8_lossy(&out.stderr)
        );
        String::from_utf8_lossy(&out.stdout).to_string()
    }

    fn fails(&self, args: &[&str]) -> (String, String) {
        let out = self.run(args);
        assert!(
            !out.status.success(),
            "[{}] deciduous {:?} should have failed:\n{}",
            self.name,
            args,
            String::from_utf8_lossy(&out.stdout)
        );
        (
            String::from_utf8_lossy(&out.stdout).to_string(),
            String::from_utf8_lossy(&out.stderr).to_string(),
        )
    }

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

    fn git(&self, args: &[&str]) -> String {
        let out = self.git_out(args);
        assert!(
            out.status.success(),
            "[{}] git {:?} failed:\n{}\n{}",
            self.name,
            args,
            String::from_utf8_lossy(&out.stdout),
            String::from_utf8_lossy(&out.stderr)
        );
        String::from_utf8_lossy(&out.stdout).to_string()
    }

    fn commit_all(&self, msg: &str) {
        self.git(&[
            "add",
            ".gitattributes",
            ".gitignore",
            ".deciduous/graph.json",
        ]);
        let out = self.git_out(&["commit", "-q", "-m", msg]);
        // Nothing to commit is fine: the graph may already be committed.
        let text = String::from_utf8_lossy(&out.stdout);
        assert!(
            out.status.success() || text.contains("nothing to commit"),
            "[{}] commit failed: {}{}",
            self.name,
            text,
            String::from_utf8_lossy(&out.stderr)
        );
    }

    fn commit_graph(&self, msg: &str) {
        self.git(&["add", ".deciduous/graph.json"]);
        self.git(&["commit", "-q", "-m", msg]);
    }

    fn graph_path(&self) -> PathBuf {
        self.dir.join(".deciduous").join("graph.json")
    }

    fn graph_text(&self) -> String {
        fs::read_to_string(self.graph_path()).unwrap()
    }

    fn doc(&self) -> Value {
        serde_json::from_str(&self.graph_text()).unwrap()
    }

    fn write_doc(&self, doc: &Value) {
        let mut s = serde_json::to_string_pretty(doc).unwrap();
        s.push('\n');
        fs::write(self.graph_path(), s).unwrap();
    }

    /// Add a node and return its local id.
    fn add(&self, node_type: &str, title: &str, extra: &[&str]) -> i32 {
        let mut args = vec!["add", node_type, title];
        args.extend_from_slice(extra);
        let out = self.ok(&args);
        out.split_whitespace()
            .nth(2)
            .and_then(|s| s.parse().ok())
            .unwrap_or_else(|| panic!("no id in: {out}"))
    }

    fn change_id(&self, id: i32) -> String {
        let shown: Value =
            serde_json::from_str(&self.ok(&["show", &id.to_string(), "--json"])).unwrap();
        shown["change_id"]
            .as_str()
            .or_else(|| shown["node"]["change_id"].as_str())
            .unwrap_or_else(|| panic!("no change_id in {shown}"))
            .to_string()
    }

    /// Nodes as the CLI reports them: (change_id, title, status).
    fn nodes(&self) -> Vec<Value> {
        let graph: Value = serde_json::from_str(&self.ok(&["graph"])).unwrap();
        graph["nodes"].as_array().cloned().unwrap_or_default()
    }

    fn node_by_title(&self, title: &str) -> Option<Value> {
        self.nodes().into_iter().find(|n| n["title"] == title)
    }
}

/// A node record as it sits in graph.json, for seeding teammates' records.
fn node_record(change_id: &str, title: &str, updated_at: &str) -> Value {
    serde_json::json!({
        "change_id": change_id,
        "node_type": "goal",
        "title": title,
        "status": "pending",
        "created_at": "2026-01-01T00:00:00+00:00",
        "updated_at": updated_at,
        "author": "teammate",
    })
}

// ============================================================================
// G3: a change_id prefix made of digits
// ============================================================================

#[test]
fn a_digit_only_change_id_prefix_is_never_silently_a_local_id() {
    let team = Team::new();
    let alice = team.founder("alice");
    let one = alice.add("goal", "local one", &[]);
    let two = alice.add("goal", "local two", &[]);
    assert_eq!((one, two), (1, 2));

    // A teammate's nodes arrive through the graph file. About 15% of
    // change_ids start with four digits and 2.5% with eight.
    let mut doc = alice.doc();
    let nodes = doc["nodes"].as_object_mut().unwrap();
    for (cid, title) in [
        ("0002abcd-1111-4111-8111-111111111111", "teammate target"),
        ("37650685-2222-4222-8222-222222222222", "all digits"),
        ("c0ffee00", "short id"),
        ("c0ffee00-4444-4444-8444-444444444444", "long id"),
    ] {
        nodes.insert(
            cid.into(),
            node_record(cid, title, "2026-01-02T00:00:00+00:00"),
        );
    }
    alice.write_doc(&doc);
    let out = alice.ok(&["sync"]);
    assert!(out.contains("4 nodes imported"), "{out}");

    // "0002" is local #2 and the prefix of the teammate's node. Deleting
    // either on a guess would tombstone it for everyone.
    let (_, err) = alice.fails(&["delete", "0002"]);
    assert!(err.contains("#2") && err.contains("local two"), "{err}");
    assert!(
        err.contains("0002abcd") && err.contains("teammate target"),
        "{err}"
    );
    assert!(alice.node_by_title("local two").is_some());
    assert!(alice.node_by_title("teammate target").is_some());

    // Exactly the CHANGE column string, which is all digits: the node, not
    // "Node #37650685 not found".
    let shown = alice.ok(&["show", "37650685"]);
    assert!(shown.contains("all digits"), "{shown}");

    // `#` always means a local id; short numbers are local ids.
    assert!(alice.ok(&["show", "#2"]).contains("local two"));
    assert!(alice.ok(&["show", "2"]).contains("local two"));
    // A four-digit number with no matching change_id is still an id.
    let (_, err) = alice.fails(&["show", "9999"]);
    assert!(err.contains("9999"), "{err}");

    // A change_id that is a prefix of another is reachable by its full id.
    let shown = alice.ok(&["show", "c0ffee00"]);
    assert!(shown.contains("short id"), "{shown}");
    let shown = alice.ok(&["show", "c0ffee00-4444"]);
    assert!(shown.contains("long id"), "{shown}");
}

// ============================================================================
// G4: fields this version does not know about
// ============================================================================

#[test]
fn fields_this_version_does_not_know_survive_every_write_and_merge() {
    let team = Team::new();
    let alice = team.founder("alice");
    let goal = alice.add("goal", "Ship it", &[]);
    let action = alice.add("action", "Write it", &[]);
    alice.ok(&["link", &goal.to_string(), &action.to_string(), "-r", "how"]);
    let goal_cid = alice.change_id(goal);

    // A newer deciduous (or a teammate's tool) wrote fields we do not model.
    let mut doc = alice.doc();
    doc["documents"] = serde_json::json!({"d1": {"node": goal_cid, "sha": "abc"}});
    let node = &mut doc["nodes"][&goal_cid];
    node["priority"] = "p1".into();
    node["reviewers"] = serde_json::json!(["bob", "carol"]);
    let edge_key = doc["edges"]
        .as_object()
        .unwrap()
        .keys()
        .next()
        .unwrap()
        .clone();
    doc["edges"][&edge_key]["confidence_note"] = "strong".into();
    alice.write_doc(&doc);
    alice.commit_graph("fields from the future");
    alice.git(&["push", "-q"]);

    // Unrelated writes on the same machine.
    alice.add("observation", "Unrelated", &[]);
    alice.ok(&["status", &goal.to_string(), "active"]);
    alice.ok(&["prompt", &goal.to_string(), "why"]);
    let doc = alice.doc();
    assert_eq!(doc["nodes"][&goal_cid]["priority"], "p1", "{doc:#}");
    assert_eq!(doc["nodes"][&goal_cid]["reviewers"][1], "carol", "{doc:#}");
    assert_eq!(doc["nodes"][&goal_cid]["status"], "active", "{doc:#}");
    assert_eq!(
        doc["edges"][&edge_key]["confidence_note"], "strong",
        "{doc:#}"
    );
    assert_eq!(doc["documents"]["d1"]["sha"], "abc", "{doc:#}");

    // Sync agrees with itself: the extra fields are not "differences" that
    // re-import on every run.
    alice.ok(&["sync"]);
    let out = alice.ok(&["sync", "--check"]);
    assert!(out.contains("already agree"), "{out}");
    alice.commit_graph("unrelated work");

    // Through a real merge with a teammate who touched the same records.
    let bob = team.join("bob");
    bob.ok(&["status", &goal_cid[..8], "completed"]);
    bob.add("goal", "Bob's own", &[]);
    bob.commit_graph("bob");
    bob.git(&["push", "-q"]);
    alice.git(&["pull", "-q", "--no-edit"]);
    let doc = alice.doc();
    assert_eq!(doc["nodes"][&goal_cid]["priority"], "p1", "{doc:#}");
    assert_eq!(
        doc["edges"][&edge_key]["confidence_note"], "strong",
        "{doc:#}"
    );
    assert_eq!(doc["documents"]["d1"]["sha"], "abc", "{doc:#}");
    alice.ok(&["sync"]);
    let doc = alice.doc();
    assert_eq!(doc["nodes"][&goal_cid]["priority"], "p1", "{doc:#}");
    assert_eq!(doc["nodes"][&goal_cid]["status"], "completed", "{doc:#}");
    assert_eq!(doc["documents"]["d1"]["sha"], "abc", "{doc:#}");
}

// ============================================================================
// G1: a record stamped in the future
// ============================================================================

fn status_of(dev: &Dev, reference: &str) -> String {
    let shown: Value = serde_json::from_str(&dev.ok(&["show", reference, "--json"])).unwrap();
    shown["status"]
        .as_str()
        .or_else(|| shown["node"]["status"].as_str())
        .unwrap_or_else(|| panic!("no status in {shown}"))
        .to_string()
}

#[test]
fn a_local_edit_is_never_reverted_by_a_future_updated_at() {
    let team = Team::new();
    let alice = team.founder("alice");

    // Backdating is for archaeology, but nothing stops a date ahead of now.
    let dated = alice.add("action", "dated", &["--date", "2099-01-01"]);
    let out = alice.ok(&["status", &dated.to_string(), "completed"]);
    assert!(out.to_lowercase().contains("updated"), "{out}");
    alice.ok(&["prompt", &dated.to_string(), "the real prompt"]);
    let out = alice.ok(&["sync"]);
    assert_eq!(status_of(&alice, &dated.to_string()), "completed", "{out}");
    let rec = alice.doc()["nodes"][alice.change_id(dated)].clone();
    assert_eq!(rec["status"], "completed", "{rec:#}");
    assert_eq!(rec["metadata"]["prompt"], "the real prompt", "{rec:#}");
    let out = alice.ok(&["sync", "--check"]);
    assert!(out.contains("already agree"), "{out}");

    // Deleting it sticks too: a tombstone older than the record's
    // updated_at used to lose to it, and the node came back.
    let doomed = alice.add("action", "doomed", &["--date", "2099-01-01"]);
    let doomed_cid = alice.change_id(doomed);
    alice.ok(&["delete", &doomed.to_string()]);
    alice.ok(&["sync"]);
    assert!(
        alice.node_by_title("doomed").is_none(),
        "deleted node came back"
    );
    assert!(
        alice.doc()["nodes"][&doomed_cid]["deleted_at"].is_string(),
        "{:#}",
        alice.doc()["nodes"][&doomed_cid]
    );

    // A teammate whose clock runs a day ahead.
    let goal = alice.add("goal", "Shared goal", &[]);
    let goal_cid = alice.change_id(goal);
    alice.commit_graph("goal");
    alice.git(&["push", "-q"]);
    let bob = team.join("bob");
    let mut doc = bob.doc();
    let tomorrow = (chrono_like_now_plus_days(1)).to_string();
    doc["nodes"][&goal_cid]["status"] = "active".into();
    doc["nodes"][&goal_cid]["updated_at"] = tomorrow.clone().into();
    bob.write_doc(&doc);
    bob.ok(&["sync"]);
    bob.commit_graph("skewed clock");
    bob.git(&["push", "-q"]);

    alice.git(&["pull", "-q", "--no-edit"]);
    alice.ok(&["sync"]);
    assert_eq!(status_of(&alice, &goal.to_string()), "active");
    // Alice decides later, by her clock and by causality.
    alice.ok(&["status", &goal.to_string(), "superseded"]);
    alice.ok(&["sync"]);
    assert_eq!(status_of(&alice, &goal.to_string()), "superseded");
    alice.commit_graph("supersede");
    alice.git(&["push", "-q"]);
    bob.git(&["pull", "-q", "--no-edit"]);
    bob.ok(&["sync"]);
    assert_eq!(status_of(&bob, &goal_cid[..8]), "superseded");
}

/// RFC 3339 timestamp `days` from now.
fn chrono_like_now_plus_days(days: i64) -> String {
    (chrono::Utc::now() + chrono::Duration::days(days)).to_rfc3339()
}

// ============================================================================
// G2: the merge driver fails, and git does not leave markers behind
// ============================================================================

fn titles(dev: &Dev) -> Vec<String> {
    let mut t: Vec<String> = dev
        .nodes()
        .iter()
        .map(|n| n["title"].as_str().unwrap().to_string())
        .collect();
    t.sort();
    t
}

fn unmerged(dev: &Dev) -> String {
    dev.git(&["ls-files", "-u", "--", ".deciduous/graph.json"])
}

#[test]
fn a_merge_driver_that_is_not_on_path_is_caught_and_finished_by_sync() {
    let team = Team::new();
    let alice = team.founder("alice");
    let shared = alice.add("goal", "Shared", &[]);
    alice.commit_graph("shared");
    alice.git(&["push", "-q"]);

    let bob = team.join("bob");
    bob.ok(&["status", &alice.change_id(shared)[..8], "completed"]);
    bob.add("goal", "Bob only", &[]);
    bob.commit_graph("bob");
    bob.git(&["push", "-q"]);

    alice.add("goal", "Alice only", &[]);
    alice.commit_graph("alice");

    // A GUI client or CI job: git is on PATH, deciduous is not. Git runs the
    // driver, the shell says "command not found", and git leaves our side
    // in the file with no markers and the index unmerged.
    let gui = Dev {
        path: base_path(),
        ..alice.clone_handle()
    };
    let out = gui.git_out(&["pull", "--no-edit"]);
    assert!(!out.status.success());
    let text = format!(
        "{}{}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(text.contains("CONFLICT"), "{text}");
    assert!(!alice.graph_text().contains("<<<<<<<"));
    assert!(!unmerged(&alice).is_empty());

    // The check must not call this clean: committing now drops Bob's work.
    let (out, _) = alice.fails(&["sync", "--check"]);
    assert!(out.contains("unmerged"), "{out}");

    // sync does the merge the driver should have done, from git's own three
    // versions, and marks the file resolved.
    let out = alice.ok(&["sync"]);
    assert!(out.contains("unmerged"), "{out}");
    assert!(unmerged(&alice).is_empty(), "still unmerged after sync");
    assert_eq!(
        titles(&alice),
        ["Alice only", "Bob only", "Shared"],
        "{out}"
    );
    assert_eq!(status_of(&alice, &shared.to_string()), "completed");
    alice.git(&["commit", "-q", "--no-edit"]);
    let out = alice.ok(&["sync", "--check"]);
    assert!(out.contains("already agree"), "{out}");
}

#[test]
fn a_committed_conflict_does_not_break_every_later_merge() {
    let team = Team::new();
    let alice = team.founder("alice");
    alice.add("goal", "Base", &[]);
    alice.commit_graph("base");
    alice.git(&["push", "-q"]);

    // Carol's clone has no driver registered (she cloned but never ran
    // deciduous), so her merge leaves markers, and she commits them.
    let carol = team.join("carol");
    carol.git(&["config", "--remove-section", "merge.deciduous"]);
    let bob = team.join("bob");
    // Both change the same record, so the text merge collides.
    bob.ok(&["status", "1", "active"]);
    bob.add("goal", "Bob first", &[]);
    bob.commit_graph("bob first");
    bob.git(&["push", "-q"]);
    carol.ok(&["status", "1", "completed"]);
    carol.add("goal", "Carol first", &[]);
    carol.commit_graph("carol first");
    let out = carol.git_out(&["pull", "--no-edit"]);
    assert!(
        !out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stdout)
    );
    assert!(
        carol.graph_text().contains("<<<<<<<"),
        "{}{}\n{}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr),
        carol.graph_text()
    );
    carol.git(&["add", ".deciduous/graph.json"]);
    carol.git(&["commit", "-q", "--no-edit"]);
    carol.git(&["push", "-q"]);

    // Alice and Bob both build on the conflicted commit.
    bob.git(&["pull", "-q", "--no-edit"]);
    bob.ok(&["sync"]);
    bob.add("goal", "Bob after", &[]);
    bob.commit_graph("bob after");
    alice.git(&["pull", "-q", "--no-edit"]);
    alice.ok(&["sync"]);
    alice.add("goal", "Alice after", &[]);
    alice.commit_graph("alice after");
    alice.git(&["push", "-q"]);

    // The merge base is the commit with markers. The driver used to refuse
    // it ("key must be a string"), leaving Bob's side with no markers.
    let out = bob.git_out(&["pull", "--no-edit"]);
    assert!(
        out.status.success(),
        "{}{}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr)
    );
    bob.ok(&["sync"]);
    assert_eq!(
        titles(&bob),
        [
            "Alice after",
            "Base",
            "Bob after",
            "Bob first",
            "Carol first"
        ]
    );
}

// ============================================================================
// G5: sync --check as a pre-push guard
// ============================================================================

#[test]
fn sync_check_fails_while_edges_wait_or_records_are_unreadable() {
    let team = Team::new();
    let alice = team.founder("alice");
    let goal = alice.add("goal", "Here", &[]);
    let goal_cid = alice.change_id(goal);
    let out = alice.ok(&["sync", "--check"]);
    assert!(out.contains("already agree"), "{out}");
    let clean = alice.doc();

    // An edge to a node nobody has pushed yet: a teammate forgot a commit.
    let mut doc = clean.clone();
    let missing = "99999999-0000-4000-8000-000000000000";
    let id = deciduous::edge_id(&goal_cid, missing, "leads_to");
    doc["edges"][&id] = serde_json::json!({
        "edge_id": id,
        "from_change_id": goal_cid,
        "to_change_id": missing,
        "edge_type": "leads_to",
        "created_at": "2026-01-01T00:00:00+00:00",
    });
    alice.write_doc(&doc);
    let (out, _) = alice.fails(&["sync", "--check"]);
    assert!(out.contains("waits for node 99999999"), "{out}");
    // sync itself succeeds (it did what it could) and still says so.
    let out = alice.ok(&["sync"]);
    assert!(out.contains("waits for node 99999999"), "{out}");
    alice.fails(&["sync", "--check"]);

    // A record filed under the wrong key (a bad hand edit or merge).
    let mut doc = clean.clone();
    let mut rec = doc["nodes"][&goal_cid].clone();
    rec["change_id"] = "aaaaaaaa-0000-4000-8000-000000000000".into();
    doc["nodes"]["bbbbbbbb-0000-4000-8000-000000000000"] = rec;
    alice.write_doc(&doc);
    let (out, _) = alice.fails(&["sync", "--check"]);
    assert!(out.contains("could not be read"), "{out}");

    alice.write_doc(&clean);
    let out = alice.ok(&["sync", "--check"]);
    assert!(out.contains("already agree"), "{out}");
}

// ============================================================================
// G8: an edge's rationale changes after others have the edge
// ============================================================================

fn edges(dev: &Dev) -> Vec<Value> {
    let graph: Value = serde_json::from_str(&dev.ok(&["graph"])).unwrap();
    graph["edges"].as_array().cloned().unwrap_or_default()
}

#[test]
fn a_relinked_edge_carries_its_new_rationale_to_clones_that_had_the_edge() {
    let team = Team::new();
    let alice = team.founder("alice");
    let goal = alice.add("goal", "Pick a store", &[]);
    let option = alice.add("option", "Postgres", &[]);
    alice.ok(&[
        "link",
        &goal.to_string(),
        &option.to_string(),
        "-r",
        "option",
    ]);
    alice.commit_graph("option");
    alice.git(&["push", "-q"]);

    let carol = team.join("carol");
    assert_eq!(edges(&carol)[0]["rationale"], "option");

    // Alice rewrites the rationale the only way the CLI offers.
    alice.ok(&["unlink", &goal.to_string(), &option.to_string()]);
    alice.ok(&[
        "link",
        &goal.to_string(),
        &option.to_string(),
        "-r",
        "chosen",
    ]);
    alice.commit_graph("chosen");
    alice.git(&["push", "-q"]);

    carol.git(&["pull", "-q", "--no-edit"]);
    let out = carol.ok(&["sync"]);
    let e = edges(&carol);
    assert_eq!(e.len(), 1, "{out}");
    assert_eq!(e[0]["rationale"], "chosen", "{out}");
    let out = carol.ok(&["sync", "--check"]);
    assert!(out.contains("already agree"), "{out}");

    // And back: Carol relinks again. Alice's row was re-created later than
    // the file's record (a merge keeps the earliest created_at), which must
    // not make her stale "chosen" win over Carol's newer "final".
    carol.ok(&[
        "unlink",
        &alice_cid(&alice, goal),
        &alice_cid(&alice, option),
    ]);
    carol.ok(&[
        "link",
        &alice_cid(&alice, goal),
        &alice_cid(&alice, option),
        "-r",
        "final",
    ]);
    carol.commit_graph("final");
    carol.git(&["push", "-q"]);
    alice.git(&["pull", "-q", "--no-edit"]);
    let out = alice.ok(&["sync"]);
    assert_eq!(edges(&alice)[0]["rationale"], "final", "{out}");
    let rec = alice.doc()["edges"]
        .as_object()
        .unwrap()
        .values()
        .next()
        .unwrap()
        .clone();
    assert_eq!(rec["rationale"], "final", "{rec:#}");
}

fn alice_cid(alice: &Dev, id: i32) -> String {
    alice.change_id(id)[..8].to_string()
}

// ============================================================================
// G9: a node deleted on one clone and edited on another comes back whole
// ============================================================================

#[test]
fn a_resurrected_node_comes_back_with_the_edges_and_tags_its_delete_took() {
    let team = Team::new();
    let alice = team.founder("alice");
    let goal = alice.add("goal", "Goal", &[]);
    let action = alice.add("action", "Contested", &[]);
    let other = alice.add("action", "Unrelated", &[]);
    alice.ok(&[
        "link",
        &goal.to_string(),
        &action.to_string(),
        "-r",
        "does it",
    ]);
    alice.ok(&["link", &goal.to_string(), &other.to_string(), "-r", "also"]);
    alice.ok(&["themes", "create", "infra"]);
    alice.ok(&["tag", "add", &action.to_string(), "infra"]);
    let action_cid = alice.change_id(action);
    let other_cid = alice.change_id(other);
    alice.commit_graph("graph");
    alice.git(&["push", "-q"]);
    let bob = team.join("bob");

    // Alice deletes the action (its edge and tag go with it), and
    // separately unlinks the unrelated one on purpose.
    alice.ok(&["delete", &action.to_string()]);
    alice.ok(&["unlink", &goal.to_string(), &other.to_string()]);
    alice.commit_graph("delete");
    alice.git(&["push", "-q"]);

    // Bob, not having pulled, edits the action afterwards. Edit after
    // delete wins, as documented: the node lives.
    bob.ok(&["status", &action_cid[..8], "completed"]);
    bob.commit_graph("edit");
    bob.git(&["pull", "-q", "--no-edit"]);
    let out = bob.ok(&["sync"]);
    assert!(bob.node_by_title("Contested").is_some(), "{out}");
    let e = edges(&bob);
    assert!(
        e.iter().any(|e| e["to_change_id"] == action_cid.as_str()),
        "Bob lost the edge of the node that came back: {out}\n{e:#?}"
    );
    // The deliberate unlink stays unlinked.
    assert!(
        !e.iter().any(|e| e["to_change_id"] == other_cid.as_str()),
        "{e:#?}"
    );
    let tags = bob.ok(&["tag", "list", &action_cid[..8]]);
    assert!(tags.contains("infra"), "{tags}");
    bob.git(&["push", "-q"]);

    // Alice gets it all back too.
    alice.git(&["pull", "-q", "--no-edit"]);
    let out = alice.ok(&["sync"]);
    let back = alice
        .node_by_title("Contested")
        .expect("node back on alice");
    assert_eq!(back["status"], "completed");
    let e = edges(&alice);
    assert!(
        e.iter().any(|e| e["to_change_id"] == action_cid.as_str()),
        "{out}\n{e:#?}"
    );
    assert!(!e.iter().any(|e| e["to_change_id"] == other_cid.as_str()));
    let tags = alice.ok(&["tag", "list", &action_cid[..8]]);
    assert!(tags.contains("infra"), "{tags}");
    let out = alice.ok(&["sync", "--check"]);
    assert!(out.contains("already agree"), "{out}");
}

// ============================================================================
// G10: smaller things found on the way
// ============================================================================

#[test]
fn a_record_filed_twice_under_one_key_merges_instead_of_last_wins() {
    let team = Team::new();
    let alice = team.founder("alice");
    let goal = alice.add("goal", "Twice", &[]);
    let cid = alice.change_id(goal);
    let rec = alice.doc()["nodes"][&cid].clone();

    // A bad hand merge leaves the record twice. The first copy is newer.
    let mut newer = rec.clone();
    newer["status"] = "completed".into();
    newer["updated_at"] = "2099-01-02T00:00:00+00:00".into();
    let mut older = rec.clone();
    older["updated_at"] = "2099-01-01T00:00:00+00:00".into();
    older["description"] = "only in the older copy".into();
    let text = format!(
        "{{\n  \"version\": 1,\n  \"edges\": {{}},\n  \"nodes\": {{\n    \"{cid}\": {},\n    \"{cid}\": {}\n  }}\n}}\n",
        serde_json::to_string(&newer).unwrap(),
        serde_json::to_string(&older).unwrap()
    );
    fs::write(alice.graph_path(), text).unwrap();
    let out = alice.ok(&["sync"]);
    assert_eq!(status_of(&alice, &goal.to_string()), "completed", "{out}");
    let shown = alice.ok(&["show", &goal.to_string()]);
    assert!(shown.contains("only in the older copy"), "{shown}");
}

#[test]
fn an_unreadable_graph_file_says_how_to_recover_not_to_rerun_what_failed() {
    let team = Team::new();
    let alice = team.founder("alice");
    alice.add("goal", "Here", &[]);
    fs::write(alice.graph_path(), "{\"version\": 1, \"nodes\": {").unwrap();
    let out = alice.run(&["sync"]);
    assert!(!out.status.success());
    let err = String::from_utf8_lossy(&out.stderr);
    assert!(err.contains("git checkout"), "{err}");
    assert!(!err.contains("run `deciduous sync`"), "{err}");
    // Still untouched.
    assert_eq!(alice.graph_text(), "{\"version\": 1, \"nodes\": {");
}

// ============================================================================
// Round two: what the verifiers got past the first fixes
// ============================================================================

/// Set `deleted_at` on every edge and tag record, standing in for a
/// teammate whose clock runs fast.
fn tombstone_edges_and_tags_in_2099(dev: &Dev) {
    let mut doc = dev.doc();
    for kind in ["edges", "tags"] {
        for rec in doc[kind].as_object_mut().unwrap().values_mut() {
            rec["deleted_at"] = "2099-01-01T00:00:00+00:00".into();
        }
    }
    dev.write_doc(&doc);
}

#[test]
fn a_relink_or_retag_is_never_reverted_by_a_future_tombstone() {
    let team = Team::new();
    let alice = team.founder("alice");
    let goal = alice.add("goal", "Goal", &[]);
    let opt = alice.add("option", "Opt", &[]);
    alice.ok(&["link", &goal.to_string(), &opt.to_string(), "-r", "option"]);
    alice.ok(&["themes", "create", "t"]);
    alice.ok(&["tag", "add", &goal.to_string(), "t"]);
    let goal_cid = alice_cid(&alice, goal);
    let opt_cid = alice_cid(&alice, opt);
    alice.commit_graph("graph");
    alice.git(&["push", "-q"]);
    let bob = team.join("bob");

    // Alice, with a clock in 2099, unlinks and untags.
    alice.ok(&["unlink", &goal.to_string(), &opt.to_string()]);
    alice.ok(&["tag", "remove", &goal.to_string(), "t"]);
    tombstone_edges_and_tags_in_2099(&alice);
    alice.ok(&["sync"]);
    alice.commit_graph("skewed unlink");
    alice.git(&["push", "-q"]);

    bob.git(&["pull", "-q", "--no-edit"]);
    let out = bob.ok(&["sync"]);
    assert!(edges(&bob).is_empty(), "{out}");

    // Bob puts both back exactly as they were. The write changes nothing
    // but deleted_at, and must still be stamped after the tombstone.
    bob.ok(&["link", &goal_cid, &opt_cid, "-r", "option"]);
    bob.ok(&["tag", "add", &goal_cid, "t"]);
    let out = bob.ok(&["sync"]);
    let e = edges(&bob);
    assert_eq!(e.len(), 1, "the relink was reverted: {out}");
    assert_eq!(e[0]["rationale"], "option");
    let tags = bob.ok(&["tag", "list", &goal_cid]);
    assert!(
        tags.contains('t') && !tags.contains("no themes"),
        "the retag was reverted: {out}\n{tags}"
    );
    let doc = bob.doc();
    for kind in ["edges", "tags"] {
        for rec in doc[kind].as_object().unwrap().values() {
            assert!(rec.get("deleted_at").is_none(), "{kind}: {rec:#}");
        }
    }
    let out = bob.ok(&["sync", "--check"]);
    assert!(out.contains("already agree"), "{out}");

    // And it reaches Alice.
    bob.commit_graph("relink");
    bob.git(&["push", "-q"]);
    alice.git(&["pull", "-q", "--no-edit"]);
    let out = alice.ok(&["sync"]);
    assert_eq!(edges(&alice).len(), 1, "{out}");
    let tags = alice.ok(&["tag", "list", &goal.to_string()]);
    assert!(!tags.contains("no themes"), "{out}\n{tags}");
}

/// The graph file as a merge without the driver leaves it: two sides of
/// the document between conflict markers.
fn write_conflicted(dev: &Dev, ours: &Value, theirs: &Value) {
    let text = format!(
        "<<<<<<< HEAD\n{}\n=======\n{}\n>>>>>>> theirs\n",
        serde_json::to_string_pretty(ours).unwrap(),
        serde_json::to_string_pretty(theirs).unwrap()
    );
    fs::write(dev.graph_path(), text).unwrap();
}

#[test]
fn an_edit_is_refused_while_the_graph_file_is_unreadable_instead_of_lost() {
    let team = Team::new();
    let alice = team.founder("alice");
    let dated = alice.add("action", "dated", &["--date", "2099-01-01"]);
    let cid = alice.change_id(dated);
    let doc = alice.doc();
    let mut theirs = doc.clone();
    theirs["nodes"][&cid]["description"] = "from the other side".into();
    write_conflicted(&alice, &doc, &theirs);

    // The database cannot be changed without the file following it: the
    // write would never be restamped past the 2099 record, and the sync
    // that merges the markers would revert it.
    let out = alice.run(&["status", &dated.to_string(), "completed"]);
    let err = String::from_utf8_lossy(&out.stderr);
    assert!(
        !out.status.success(),
        "status reported success on an unreadable graph file:\n{}{}",
        String::from_utf8_lossy(&out.stdout),
        err
    );
    assert!(
        err.contains("graph.json") && err.contains("conflict markers"),
        "{err}"
    );
    assert_eq!(status_of(&alice, &dated.to_string()), "pending");
    let (_, err) = alice.fails(&["add", "goal", "new while broken"]);
    assert!(err.contains("conflict markers"), "{err}");
    assert!(alice.node_by_title("new while broken").is_none());

    // Once sync has merged the file, the same edit goes through and sticks.
    alice.ok(&["sync"]);
    alice.ok(&["status", &dated.to_string(), "completed"]);
    alice.ok(&["sync"]);
    assert_eq!(status_of(&alice, &dated.to_string()), "completed");
}

/// Alice and Bob each add a node after a shared one; Bob pushes. Returns
/// Alice, with her commit made and Bob's not yet pulled.
fn diverged_alice_and_bob(team: &Team) -> Dev {
    let alice = team.founder("alice");
    alice.add("goal", "Shared", &[]);
    alice.commit_graph("shared");
    alice.git(&["push", "-q"]);
    let bob = team.join("bob");
    bob.add("goal", "Bob only", &[]);
    bob.commit_graph("bob");
    bob.git(&["push", "-q"]);
    alice.add("goal", "Alice only", &[]);
    alice.commit_graph("alice");
    alice
}

/// Run git with only git itself on PATH: the driver is "command not found".
fn git_without_driver(dev: &Dev, args: &[&str]) -> Output {
    let gui = Dev {
        path: base_path(),
        ..dev.clone_handle()
    };
    gui.git_out(args)
}

#[test]
fn a_failed_driver_merge_staged_by_hand_is_still_caught_and_finished_by_sync() {
    let team = Team::new();
    let alice = diverged_alice_and_bob(&team);
    let out = git_without_driver(&alice, &["pull", "--no-edit"]);
    assert!(!out.status.success());
    // The file parses and shows no markers, so staging it looks right.
    alice.git(&["add", ".deciduous/graph.json"]);
    assert!(unmerged(&alice).is_empty());
    assert!(!alice.graph_text().contains("Bob only"));

    // Committing now would record a merge without Bob's node.
    let (out, _) = alice.fails(&["sync", "--check"]);
    assert!(out.contains("MERGE_HEAD"), "{out}");
    let out = alice.ok(&["sync"]);
    assert!(out.contains("MERGE_HEAD"), "{out}");
    assert_eq!(
        titles(&alice),
        ["Alice only", "Bob only", "Shared"],
        "{out}"
    );
    let staged = alice.git(&["show", ":.deciduous/graph.json"]);
    assert!(
        staged.contains("Bob only"),
        "the merge result is not staged"
    );
    alice.git(&["commit", "-q", "--no-edit"]);
    let out = alice.ok(&["sync", "--check"]);
    assert!(out.contains("already agree"), "{out}");
    let committed = alice.git(&["show", "HEAD:.deciduous/graph.json"]);
    assert!(committed.contains("Bob only"));
}

#[test]
fn a_failed_driver_rebase_staged_by_hand_is_still_caught_and_finished_by_sync() {
    let team = Team::new();
    let alice = diverged_alice_and_bob(&team);
    let out = git_without_driver(&alice, &["pull", "--rebase"]);
    assert!(!out.status.success());
    alice.git(&["add", ".deciduous/graph.json"]);
    assert!(unmerged(&alice).is_empty());

    let (out, _) = alice.fails(&["sync", "--check"]);
    assert!(out.contains("REBASE_HEAD"), "{out}");
    alice.ok(&["sync"]);
    let staged = alice.git(&["show", ":.deciduous/graph.json"]);
    assert!(
        staged.contains("Bob only") && staged.contains("Alice only"),
        "{staged}"
    );
    let out = alice
        .cmd("git")
        .args(["-c", "core.editor=true", "rebase", "--continue"])
        .output()
        .unwrap();
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    let committed = alice.git(&["show", "HEAD:.deciduous/graph.json"]);
    assert!(committed.contains("Bob only") && committed.contains("Alice only"));
    let out = alice.ok(&["sync", "--check"]);
    assert!(out.contains("already agree"), "{out}");
}

#[test]
fn a_merge_stopped_on_another_file_leaves_a_driver_merged_graph_alone() {
    let team = Team::new();
    let alice = team.founder("alice");
    fs::write(alice.dir.join("notes.txt"), "base\n").unwrap();
    alice.git(&["add", "notes.txt"]);
    alice.add("goal", "Shared", &[]);
    alice.commit_graph("shared");
    alice.git(&["push", "-q"]);
    let bob = team.join("bob");
    bob.ok(&["status", "1", "completed"]);
    bob.add("goal", "Bob only", &[]);
    fs::write(bob.dir.join("notes.txt"), "bob\n").unwrap();
    bob.git(&["add", "notes.txt"]);
    bob.commit_graph("bob");
    bob.git(&["push", "-q"]);
    alice.ok(&["prompt", "1", "alice's prompt"]);
    alice.add("goal", "Alice only", &[]);
    fs::write(alice.dir.join("notes.txt"), "alice\n").unwrap();
    alice.git(&["add", "notes.txt"]);
    alice.commit_graph("alice");

    // The driver merges graph.json; notes.txt stops the merge.
    let out = alice.git_out(&["pull", "--no-edit"]);
    assert!(!out.status.success());
    assert!(unmerged(&alice).is_empty());
    let merged = alice.graph_text();
    let out = alice.ok(&["sync"]);
    assert!(!out.contains("MERGE_HEAD"), "{out}");
    assert_eq!(titles(&alice), ["Alice only", "Bob only", "Shared"]);
    assert_eq!(status_of(&alice, "1"), "completed");
    let out = alice.ok(&["sync", "--check"]);
    assert!(out.contains("already agree"), "{out}");
    // Nothing but what sync imported changed the file.
    assert_eq!(alice.graph_text(), merged);
}

#[test]
fn a_merge_whose_ancestor_will_not_parse_is_refused_not_decided_by_timestamp() {
    let team = Team::new();
    let alice = team.founder("alice");
    let goal = alice.add("goal", "A", &[]);
    let cid = alice.change_id(goal);
    let good = alice.doc();
    // Both edits are later than the node's own record: the local row must not
    // win on age. Relative to now, not a date that was the future once.
    let ours_at = (chrono::Utc::now() + chrono::Duration::hours(1)).to_rfc3339();
    let theirs_at = (chrono::Utc::now() + chrono::Duration::hours(2)).to_rfc3339();

    // A commit whose graph.json no reader can parse, not even by resolving
    // markers: the ancestor of the merge below.
    fs::write(alice.graph_path(), "{\"version\": 1, \"nodes\": {\n").unwrap();
    alice.commit_graph("broken");
    let at = |doc: &Value, field: &str, value: &str, when: &str| {
        let mut d = doc.clone();
        d["nodes"][&cid][field] = value.into();
        d["nodes"][&cid]["updated_at"] = when.into();
        d
    };
    alice.git(&["checkout", "-q", "-b", "theirs"]);
    alice.write_doc(&at(&good, "status", "completed", &theirs_at));
    alice.commit_graph("theirs: completed an hour after ours");
    alice.git(&["checkout", "-q", "main"]);
    alice.write_doc(&at(&good, "title", "OURS RENAMED", &ours_at));
    alice.commit_graph("ours: renamed");

    // Without the ancestor, every differing field would go to the newer
    // record: title "A", and our rename silently gone.
    let out = alice.git_out(&["merge", "--no-edit", "theirs"]);
    let text = format!(
        "{}{}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(
        !out.status.success(),
        "the merge went through: {text}\n{}",
        alice.graph_text()
    );
    assert!(text.contains("common ancestor"), "{text}");
    assert!(!unmerged(&alice).is_empty());

    // sync does not do behind git's back what the driver refused.
    let (out, _) = alice.fails(&["sync", "--check"]);
    assert!(out.contains("common ancestor"), "{out}");
    let (out, err) = alice.fails(&["sync"]);
    assert!(
        format!("{out}{err}").contains("common ancestor"),
        "{out}{err}"
    );
    assert!(!unmerged(&alice).is_empty());
    assert!(alice.graph_text().contains("OURS RENAMED"));

    // The same through the driver called by hand: a failure, not a note.
    let base = alice.dir.join("base.json");
    fs::write(&base, "{\"version\": 1, \"nodes\": {\n").unwrap();
    let ours = alice.dir.join("ours.json");
    let theirs = alice.dir.join("theirs.json");
    fs::write(
        &ours,
        serde_json::to_string(&at(&good, "title", "OURS RENAMED", &ours_at)).unwrap(),
    )
    .unwrap();
    fs::write(
        &theirs,
        serde_json::to_string(&at(&good, "status", "completed", &theirs_at)).unwrap(),
    )
    .unwrap();
    let out = alice.run(&[
        "merge-record",
        base.to_str().unwrap(),
        ours.to_str().unwrap(),
        theirs.to_str().unwrap(),
    ]);
    assert!(
        !out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(fs::read_to_string(&ours).unwrap().contains("OURS RENAMED"));

    // The way out the message names, taken knowingly: a two-way merge.
    let theirs_blob = alice.git(&["show", ":3:.deciduous/graph.json"]);
    fs::write(&theirs, theirs_blob).unwrap();
    alice.ok(&[
        "merge-record",
        "/dev/null",
        ".deciduous/graph.json",
        theirs.to_str().unwrap(),
    ]);
    alice.git(&["add", ".deciduous/graph.json"]);
    alice.ok(&["sync"]);
    assert_eq!(status_of(&alice, &goal.to_string()), "completed");
}

/// Seed a teammate's node into the graph file, as `git pull` would, without
/// syncing it into the database.
fn pull_teammate_node(dev: &Dev, change_id: &str, title: &str) {
    let mut doc = dev.doc();
    doc["nodes"][change_id] = node_record(change_id, title, "2026-01-02T00:00:00+00:00");
    dev.write_doc(&doc);
}

#[test]
fn a_prefix_of_a_pulled_but_unsynced_node_is_not_taken_as_a_local_id() {
    let team = Team::new();
    let alice = team.founder("alice");
    alice.add("goal", "local one", &[]);
    alice.add("goal", "local two", &[]);
    alice.add("goal", "abcd local", &[]);
    let local_abcd = alice.change_id(3);
    // After `git pull`, before `deciduous sync`.
    pull_teammate_node(
        &alice,
        "0002abcd-1111-4111-8111-111111111111",
        "teammate target",
    );

    let (_, err) = alice.fails(&["delete", "0002"]);
    assert!(
        err.contains("local two") && err.contains("0002abcd"),
        "{err}"
    );
    assert!(err.contains("deciduous sync"), "{err}");
    assert!(alice.node_by_title("local two").is_some());
    alice.fails(&["show", "0002"]);

    // A hex prefix one local node has and an unsynced one shares.
    let prefix = &local_abcd[..4];
    let twin = format!("{prefix}ffff-2222-4222-8222-222222222222");
    pull_teammate_node(&alice, &twin, "teammate twin");
    let (_, err) = alice.fails(&["status", prefix, "completed"]);
    assert!(err.contains("teammate twin"), "{err}");
    assert_eq!(status_of(&alice, "3"), "pending");
    // A prefix only the unsynced node has names it, and says to sync.
    let (_, err) = alice.fails(&["show", &twin[..9]]);
    assert!(
        err.contains("deciduous sync") && err.contains("teammate twin"),
        "{err}"
    );

    // Explicit local ids still work, and after sync the prefix is the node.
    alice.ok(&["show", "#2"]);
    alice.ok(&["sync"]);
    let shown = alice.ok(&["show", "0002a"]);
    assert!(shown.contains("teammate target"), "{shown}");
}

/// One JSON-RPC exchange with a real `deciduous mcp` process.
fn mcp_call(dev: &Dev, tool: &str, arguments: Value) -> Value {
    use std::io::{BufRead, BufReader, Write};
    let mut child = dev
        .cmd(BIN)
        .arg("mcp")
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::null())
        .spawn()
        .unwrap();
    let mut stdin = child.stdin.take().unwrap();
    let msgs = [
        serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"t","version":"0"}}}),
        serde_json::json!({"jsonrpc":"2.0","method":"notifications/initialized"}),
        serde_json::json!({"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":tool,"arguments":arguments}}),
    ];
    for m in msgs {
        writeln!(stdin, "{m}").unwrap();
    }
    drop(stdin);
    let reader = BufReader::new(child.stdout.take().unwrap());
    let mut answer = Value::Null;
    for line in reader.lines() {
        let v: Value = serde_json::from_str(&line.unwrap()).unwrap();
        if v["id"] == 2 {
            answer = v;
        }
    }
    child.wait().unwrap();
    answer
}

#[test]
fn an_mcp_node_id_is_never_truncated_to_another_node() {
    let team = Team::new();
    let alice = team.founder("alice");
    alice.add("goal", "A", &[]);
    alice.add("goal", "B", &[]);
    // 2^32 + 2 truncated to i32 is 2.
    let answer = mcp_call(
        &alice,
        "delete_node",
        serde_json::json!({"node_id": 4294967298u64, "dry_run": true}),
    );
    let text = answer.to_string();
    assert!(!text.contains("Would delete node #2"), "{text}");
    assert!(text.contains("4294967298"), "{text}");
    assert_eq!(answer["result"]["isError"], true, "{text}");

    // A digit-only CHANGE value sent as a number is looked up like the
    // string, not taken as a local id.
    let cid = "37650685-2222-4222-8222-222222222222";
    pull_teammate_node(&alice, cid, "all digits");
    alice.ok(&["sync"]);
    let answer = mcp_call(
        &alice,
        "delete_node",
        serde_json::json!({"node_id": 37650685, "dry_run": true}),
    );
    let text = answer.to_string();
    assert!(text.contains("all digits"), "{text}");
}

/// A real HTTP server on 127.0.0.1 that answers `GET /export` with `body`,
/// `/claim` and `/locate` as a server does for a repository it has no
/// record of, and anything else with an empty object, for as long as the
/// test runs.
fn serve_export(body: String) -> String {
    use std::io::{BufRead, BufReader, Read, Write};
    let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
    let url = format!("http://{}", listener.local_addr().unwrap());
    std::thread::spawn(move || {
        for stream in listener.incoming() {
            let Ok(mut stream) = stream else { continue };
            let mut reader = BufReader::new(stream.try_clone().unwrap());
            let mut request_line = String::new();
            reader.read_line(&mut request_line).unwrap_or(0);
            let mut length = 0usize;
            loop {
                let mut line = String::new();
                if reader.read_line(&mut line).unwrap_or(0) == 0 || line == "\r\n" {
                    break;
                }
                if let Some(v) = line.to_lowercase().strip_prefix("content-length:") {
                    length = v.trim().parse().unwrap_or(0);
                }
            }
            let mut sink = vec![0; length];
            let _ = reader.read_exact(&mut sink);
            let payload = if request_line.starts_with("GET /export") {
                body.clone()
            } else if request_line.starts_with("POST /claim") {
                // What a server says to a CLI that sends no repository roots.
                r#"{"claim":"unchecked"}"#.to_string()
            } else if request_line.starts_with("POST /locate") {
                r#"{"workspaces":[]}"#.to_string()
            } else {
                "{}".to_string()
            };
            let _ = write!(
                stream,
                "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{}",
                payload.len(),
                payload
            );
        }
    });
    url
}

#[test]
fn remote_pull_merges_into_graph_json_instead_of_overwriting_it() {
    let team = Team::new();
    let alice = team.founder("alice");
    let a = alice.add("goal", "A", &[]);
    let b = alice.add("action", "B", &[]);
    let c = alice.add("action", "C", &[]);
    let (a, b, c) = (a.to_string(), b.to_string(), c.to_string());
    alice.ok(&["link", &a, &b, "-r", "old"]);
    alice.ok(&["link", &a, &c, "-r", "to c"]);

    // What the server holds: this graph as it was now.
    let doc = alice.doc();
    let nodes: Vec<Value> = doc["nodes"]
        .as_object()
        .unwrap()
        .values()
        .map(|n| {
            serde_json::json!({
                "change_id": n["change_id"], "node_type": n["node_type"],
                "title": n["title"], "status": n["status"],
                "created_at": n["created_at"], "updated_at": n["updated_at"],
            })
        })
        .collect();
    let server_edges: Vec<Value> = doc["edges"]
        .as_object()
        .unwrap()
        .values()
        .map(|e| {
            serde_json::json!({
                "from_change_id": e["from_change_id"], "to_change_id": e["to_change_id"],
                "edge_type": e["edge_type"], "rationale": e["rationale"],
                "created_at": e["created_at"],
            })
        })
        .collect();
    let url = serve_export(
        serde_json::json!({"nodes": nodes, "edges": server_edges, "documents": []}).to_string(),
    );

    // Since then, locally: A -> C unlinked (removal is local only), A -> B
    // relinked with a new rationale, and a field this version does not know.
    alice.ok(&["unlink", &a, &c]);
    alice.ok(&["unlink", &a, &b]);
    alice.ok(&["link", &a, &b, "-r", "new local relink"]);
    let mut doc = alice.doc();
    for n in doc["nodes"].as_object_mut().unwrap().values_mut() {
        n["priority"] = "high".into();
    }
    alice.write_doc(&doc);
    alice.ok(&["sync"]);
    fs::write(
        alice.dir.join(".deciduous").join("config.toml"),
        format!("[remote]\nurl = \"{url}\"\nworkspace = \"w\"\n"),
    )
    .unwrap();

    let out = alice
        .cmd(BIN)
        .args(["remote", "pull"])
        .env("DECIDUOUS_MCP_TOKEN", "t")
        .output()
        .unwrap();
    let said = format!(
        "{}{}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(out.status.success(), "{said}");

    let doc = alice.doc();
    for n in doc["nodes"].as_object().unwrap().values() {
        assert_eq!(
            n["priority"], "high",
            "remote pull dropped a field: {n:#}\n{said}"
        );
    }
    let e = edges(&alice);
    assert_eq!(e.len(), 1, "the unlinked edge came back: {e:#?}\n{said}");
    assert_eq!(e[0]["rationale"], "new local relink", "{said}");
    let tomb = doc["edges"]
        .as_object()
        .unwrap()
        .values()
        .filter(|e| e["deleted_at"].is_string())
        .count();
    assert_eq!(tomb, 1, "{doc:#}");
    let out = alice.ok(&["sync", "--check"]);
    assert!(out.contains("already agree"), "{out}");
}

#[test]
fn indented_conflict_markers_are_not_sent_back_to_the_sync_that_cannot_merge_them() {
    let team = Team::new();
    let alice = team.founder("alice");
    alice.add("goal", "Here", &[]);
    // A reformatted or hand-edited conflict: the markers are not at the
    // start of a line, so they are not git's and sync cannot split them.
    let text = alice.graph_text().replacen(
        "  \"nodes\": {",
        "  \"nodes\": {\n    <<<<<<< HEAD\n    =======\n    >>>>>>> theirs",
        1,
    );
    fs::write(alice.graph_path(), &text).unwrap();
    for args in [&["sync"][..], &["sync", "--check"][..]] {
        let out = alice.run(args);
        assert!(!out.status.success());
        let said = format!(
            "{}{}",
            String::from_utf8_lossy(&out.stdout),
            String::from_utf8_lossy(&out.stderr)
        );
        assert!(!said.contains("run `deciduous sync`"), "{args:?}: {said}");
        assert!(said.contains("by hand"), "{args:?}: {said}");
    }
    assert_eq!(alice.graph_text(), text);
}

// ============================================================================
// G6 / G7: deferred. The database is shared by every branch and commit a
// clone checks out, and cannot tell a row it never exported from a row git
// took out of the file. These reproduce the findings for the chapter that
// gives the database that knowledge; run with --ignored.
// ============================================================================

#[test]
#[ignore = "G6 deferred: needs a record of which rows are unpublished local writes"]
fn a_node_added_on_a_branch_stays_on_that_branch() {
    let team = Team::new();
    let alice = team.founder("alice");
    alice.add("goal", "On main", &[]);
    alice.commit_graph("main");
    alice.git(&["checkout", "-q", "-b", "spike"]);
    alice.add("goal", "Spike", &[]);
    alice.commit_graph("spike");
    alice.git(&["checkout", "-q", "main"]);
    let out = alice.ok(&["sync"]);
    assert!(!alice.graph_text().contains("Spike"), "{out}");
    assert!(alice.git(&["status", "--porcelain"]).is_empty(), "{out}");
}

#[test]
fn sync_on_an_older_commit_leaves_the_tree_clean() {
    let team = Team::new();
    let alice = team.founder("alice");
    alice.add("goal", "First", &[]);
    alice.commit_graph("first");
    alice.add("goal", "Second", &[]);
    alice.commit_graph("second");
    alice.git(&["checkout", "-q", "HEAD~1"]);
    let before = alice.git(&["status", "--porcelain"]);
    let out = alice.ok(&["sync"]);
    assert_eq!(alice.git(&["status", "--porcelain"]), before, "{out}");
    alice.git(&["checkout", "-q", "main"]);
}

/// Model seed 7833548565119299294 (1 run in 8 on chapter 29): a value two
/// clones both took from the server (`remote pull` writes graph.json and
/// commits nothing), changed back to the ancestor's value by one of them
/// afterwards, loses to the stale copy in git's merge. The three-way merge
/// sees base "pending", ours "rejected", theirs "pending" and takes ours:
/// the later edit is indistinguishable from "did not touch the field",
/// because a record has one updated_at, not one per field.
#[test]
#[ignore = "deferred: needs per-field stamps in graph.json records (ABA on a pulled value)"]
fn model_7833_a_field_set_back_to_the_ancestors_value_survives_the_merge() {
    let team = Team::new();
    let alice = team.founder("alice");
    let goal = alice.add("goal", "G", &[]);
    let cid = alice.change_id(goal);
    alice.commit_all("G");
    alice.git(&["push", "-q", "origin", "main"]);
    let bob = team.join("bob");

    // Both take the server's "rejected", as `remote pull` would.
    let pulled = (chrono::Utc::now() + chrono::Duration::seconds(1)).to_rfc3339();
    for dev in [&alice, &bob] {
        let mut doc = dev.doc();
        doc["nodes"][&cid]["status"] = "rejected".into();
        doc["nodes"][&cid]["updated_at"] = pulled.clone().into();
        dev.write_doc(&doc);
        dev.ok(&["sync"]);
    }
    // Alice sets it back, later.
    std::thread::sleep(std::time::Duration::from_millis(1100));
    alice.ok(&["status", &goal.to_string(), "pending"]);
    alice.ok(&["sync"]);
    alice.commit_graph("alice: pending again");
    alice.git(&["push", "-q", "origin", "main"]);
    bob.commit_graph("bob: pulled rejected");
    bob.git(&["pull", "-q", "--no-rebase", "origin", "main"]);
    bob.ok(&["sync"]);
    assert_eq!(
        status_of(&bob, &cid),
        "pending",
        "alice's later edit back to the ancestor's value was lost in the merge"
    );
}