edda 0.2.1

Decision memory for coding agents — CLI and TUI
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
use anyhow::Context;
use clap::Subcommand;
use std::io::Read;
use std::path::Path;

// ── CLI Schema ──

#[derive(Subcommand)]
pub enum BridgeCmd {
    /// Claude Code bridge operations
    Claude {
        #[command(subcommand)]
        cmd: BridgeClaudeCmd,
    },
    /// OpenClaw bridge operations
    Openclaw {
        #[command(subcommand)]
        cmd: BridgeOpenclawCmd,
    },
    /// Codex CLI bridge operations
    Codex {
        #[command(subcommand)]
        cmd: BridgeCodexCmd,
    },
    /// Hermes agent bridge operations
    Hermes {
        #[command(subcommand)]
        cmd: BridgeHermesCmd,
    },
    /// Cursor IDE bridge operations
    Cursor {
        #[command(subcommand)]
        cmd: BridgeCursorCmd,
    },
}

#[derive(Subcommand)]
pub enum BridgeCursorCmd {
    /// Install edda hooks into ~/.cursor/hooks.json
    Install {
        /// Custom hooks.json path (default: ~/.cursor/hooks.json)
        #[arg(long)]
        target: Option<String>,
    },
    /// Uninstall edda hooks from Cursor hooks.json
    Uninstall {
        /// Custom hooks.json path
        #[arg(long)]
        target: Option<String>,
    },
}

#[derive(Subcommand)]
pub enum BridgeCodexCmd {
    /// Install edda hooks into ~/.codex/hooks.json
    Install {
        /// Custom hooks.json path (default: ~/.codex/hooks.json)
        #[arg(long)]
        target: Option<String>,
    },
    /// Uninstall edda hooks from Codex hooks.json
    Uninstall {
        /// Custom hooks.json path
        #[arg(long)]
        target: Option<String>,
    },
}

#[derive(Subcommand)]
pub enum BridgeHermesCmd {
    /// Install edda hooks into ~/.hermes/cli-config.yaml (merges into existing hooks: block)
    Install {
        /// Custom cli-config.yaml path (default: ~/.hermes/cli-config.yaml)
        #[arg(long)]
        target: Option<String>,
    },
    /// Uninstall edda hooks from Hermes cli-config.yaml
    Uninstall {
        /// Custom cli-config.yaml path
        #[arg(long)]
        target: Option<String>,
    },
}

#[derive(Subcommand)]
pub enum BridgeClaudeCmd {
    /// Install edda hooks into .claude/settings.local.json
    Install {
        /// Skip writing edda section to .claude/CLAUDE.md
        #[arg(long)]
        no_claude_md: bool,
    },
    /// Uninstall edda hooks from .claude/settings.local.json
    Uninstall,
    /// Manually digest a session into workspace ledger
    Digest {
        /// Session ID to digest
        #[arg(long)]
        session: Option<String>,
        /// Digest all pending sessions
        #[arg(long)]
        all: bool,
    },
    /// Show active peer sessions for current project
    Peers,
    /// Claim a scope for coordination (e.g. "auth", "billing")
    Claim {
        /// Short label for this session's scope
        label: String,
        /// File path patterns this scope covers (e.g. "src/auth/*")
        #[arg(long)]
        paths: Vec<String>,
        /// Session ID (auto-inferred from active heartbeats if omitted)
        #[arg(long)]
        session: Option<String>,
    },
    /// Record a binding decision for all sessions
    Decide {
        /// Decision in key=value format (e.g. "auth.method=JWT RS256")
        decision: String,
        /// Reason for the decision
        #[arg(long)]
        reason: Option<String>,
        /// Decision keys this decision depends on (repeatable)
        #[arg(long = "refs")]
        refs: Vec<String>,
        /// Session ID (auto-inferred from active heartbeats if omitted)
        #[arg(long)]
        session: Option<String>,
        /// File glob patterns this decision governs (repeatable)
        #[arg(long = "paths")]
        paths: Vec<String>,
        /// Comma-separated tags for this decision
        #[arg(long, value_delimiter = ',')]
        tags: Vec<String>,
    },
    /// Send a request to another session
    Request {
        /// Target session label
        to: String,
        /// Request message
        message: String,
        /// Session ID (auto-inferred from active heartbeats if omitted)
        #[arg(long)]
        session: Option<String>,
    },
    /// Render write-back protocol (static teaching text)
    RenderWriteback,
    /// Render workspace context from .edda/ ledger
    RenderWorkspace {
        /// Max chars budget
        #[arg(long, default_value = "2500")]
        budget: usize,
    },
    /// Render L2 coordination protocol
    RenderCoordination {
        /// Session ID (auto-inferred if omitted)
        #[arg(long)]
        session: Option<String>,
    },
    /// Render hot pack (recent turns summary, reads last-built pack)
    RenderPack,
    /// Render active plan excerpt
    RenderPlan,
    /// Write session heartbeat for peer discovery
    HeartbeatWrite {
        /// Session label (e.g. "auth", "billing")
        #[arg(long)]
        label: String,
        /// Session ID (auto-inferred if omitted)
        #[arg(long)]
        session: Option<String>,
    },
    /// Touch heartbeat timestamp (liveness ping)
    HeartbeatTouch {
        /// Session ID (auto-inferred if omitted)
        #[arg(long)]
        session: Option<String>,
    },
    /// Remove session heartbeat
    HeartbeatRemove {
        /// Session ID (auto-inferred if omitted)
        #[arg(long)]
        session: Option<String>,
    },
    /// Review background-extracted draft decisions
    BgReview {
        /// List all pending draft decisions
        #[arg(long)]
        list: bool,
        /// Accept decisions for a session (comma-separated indices)
        #[arg(long)]
        accept: Option<String>,
        /// Reject decisions for a session (comma-separated indices)
        #[arg(long)]
        reject: Option<String>,
        /// Accept all pending decisions for a session
        #[arg(long)]
        accept_all: bool,
        /// Session ID to review
        #[arg(long)]
        session: Option<String>,
    },
}

#[derive(Subcommand)]
pub enum BridgeOpenclawCmd {
    /// Install edda OpenClaw plugin
    Install {
        /// Custom target directory (default: ~/.openclaw/extensions/edda-bridge/)
        #[arg(long)]
        target: Option<String>,
    },
    /// Uninstall edda OpenClaw plugin
    Uninstall {
        /// Custom target directory
        #[arg(long)]
        target: Option<String>,
    },
    /// Manually digest a session into workspace ledger
    Digest {
        /// Session ID to digest
        #[arg(long)]
        session: Option<String>,
        /// Digest all pending sessions
        #[arg(long)]
        all: bool,
    },
}

#[derive(Subcommand)]
pub enum HookCmd {
    /// Claude Code hook entrypoint (reads stdin JSON)
    Claude,
    /// Codex CLI hook entrypoint (reads stdin JSON)
    Codex,
    /// Hermes agent shell-hook entrypoint (reads stdin JSON)
    Hermes,
    /// OpenClaw hook entrypoint (reads stdin JSON)
    Openclaw,
    /// Cursor IDE hook entrypoint (reads stdin JSON)
    Cursor,
}

#[derive(Subcommand)]
pub enum DoctorCmd {
    /// Check Claude Code bridge health
    Claude,
    /// Check Codex bridge health
    Codex,
    /// Check Hermes bridge health
    Hermes,
    /// Check OpenClaw bridge health
    Openclaw,
    /// Check Cursor bridge health
    Cursor,
}

#[derive(Subcommand)]
pub enum IndexCmd {
    /// Verify index entries match store records
    Verify {
        /// Project ID
        #[arg(long)]
        project: String,
        /// Session ID
        #[arg(long)]
        session: String,
        /// Number of records to sample
        #[arg(long, default_value_t = 50)]
        sample: usize,
        /// Check all records
        #[arg(long)]
        all: bool,
    },
}

// ── Dispatch ──

pub fn run_bridge(cmd: BridgeCmd, repo_root: &Path) -> anyhow::Result<()> {
    match cmd {
        BridgeCmd::Claude { cmd } => match cmd {
            BridgeClaudeCmd::Install { no_claude_md } => install(repo_root, no_claude_md),
            BridgeClaudeCmd::Uninstall => uninstall(repo_root),
            BridgeClaudeCmd::Digest { session, all } => digest(repo_root, session.as_deref(), all),
            BridgeClaudeCmd::Peers => peers(repo_root),
            BridgeClaudeCmd::Claim {
                label,
                paths,
                session,
            } => claim(repo_root, &label, &paths, session.as_deref()),
            BridgeClaudeCmd::Decide {
                decision,
                reason,
                refs,
                session,
                paths,
                tags,
            } => decide(
                repo_root,
                &decision,
                reason.as_deref(),
                &refs,
                session.as_deref(),
                None,
                &paths,
                &tags,
            ),
            BridgeClaudeCmd::Request {
                to,
                message,
                session,
            } => request(repo_root, &to, &message, session.as_deref()),
            BridgeClaudeCmd::RenderWriteback => render_writeback(),
            BridgeClaudeCmd::RenderWorkspace { budget } => render_workspace(repo_root, budget),
            BridgeClaudeCmd::RenderCoordination { session } => {
                render_coordination(repo_root, session.as_deref())
            }
            BridgeClaudeCmd::RenderPack => render_pack(repo_root),
            BridgeClaudeCmd::RenderPlan => render_plan(repo_root),
            BridgeClaudeCmd::HeartbeatWrite { label, session } => {
                heartbeat_write(repo_root, &label, session.as_deref())
            }
            BridgeClaudeCmd::HeartbeatTouch { session } => {
                heartbeat_touch(repo_root, session.as_deref())
            }
            BridgeClaudeCmd::HeartbeatRemove { session } => {
                heartbeat_remove(repo_root, session.as_deref())
            }
            BridgeClaudeCmd::BgReview {
                list,
                accept,
                reject,
                accept_all,
                session,
            } => bg_review(repo_root, list, accept, reject, accept_all, session),
        },
        BridgeCmd::Openclaw { cmd } => match cmd {
            BridgeOpenclawCmd::Install { target } => {
                install_openclaw(target.as_deref().map(std::path::Path::new))
            }
            BridgeOpenclawCmd::Uninstall { target } => {
                uninstall_openclaw(target.as_deref().map(std::path::Path::new))
            }
            BridgeOpenclawCmd::Digest { session, all } => {
                digest(repo_root, session.as_deref(), all)
            }
        },
        BridgeCmd::Codex { cmd } => match cmd {
            BridgeCodexCmd::Install { target } => {
                install_codex(target.as_deref().map(std::path::Path::new))
            }
            BridgeCodexCmd::Uninstall { target } => {
                uninstall_codex(target.as_deref().map(std::path::Path::new))
            }
        },
        BridgeCmd::Hermes { cmd } => match cmd {
            BridgeHermesCmd::Install { target } => {
                install_hermes(target.as_deref().map(std::path::Path::new))
            }
            BridgeHermesCmd::Uninstall { target } => {
                uninstall_hermes(target.as_deref().map(std::path::Path::new))
            }
        },
        BridgeCmd::Cursor { cmd } => match cmd {
            BridgeCursorCmd::Install { target } => {
                install_cursor(target.as_deref().map(std::path::Path::new))
            }
            BridgeCursorCmd::Uninstall { target } => {
                uninstall_cursor(target.as_deref().map(std::path::Path::new))
            }
        },
    }
}

pub fn run_hook(cmd: HookCmd) -> anyhow::Result<()> {
    match cmd {
        HookCmd::Claude => hook_claude(),
        HookCmd::Codex => hook_codex(),
        HookCmd::Hermes => hook_hermes(),
        HookCmd::Openclaw => hook_openclaw(),
        HookCmd::Cursor => hook_cursor(),
    }
}

pub fn run_doctor(cmd: DoctorCmd, repo_root: &Path) -> anyhow::Result<()> {
    match cmd {
        DoctorCmd::Claude => doctor(repo_root),
        DoctorCmd::Codex => doctor_codex(),
        DoctorCmd::Hermes => doctor_hermes(),
        DoctorCmd::Openclaw => doctor_openclaw(),
        DoctorCmd::Cursor => doctor_cursor(),
    }
}

pub fn run_index(cmd: IndexCmd) -> anyhow::Result<()> {
    match cmd {
        IndexCmd::Verify {
            project,
            session,
            sample,
            all,
        } => index_verify(&project, &session, sample, all),
    }
}

// ── Command Implementations ──

/// `edda bridge claude install`
pub fn install(repo_root: &Path, no_claude_md: bool) -> anyhow::Result<()> {
    edda_bridge_claude::install(repo_root, no_claude_md)
}

/// `edda bridge claude uninstall`
pub fn uninstall(repo_root: &Path) -> anyhow::Result<()> {
    edda_bridge_claude::uninstall(repo_root)
}

/// `edda hook claude` — read stdin, dispatch hook
///
/// Resilience: catch_unwind + configurable timeout (EDDA_HOOK_TIMEOUT_MS).
/// On panic or timeout, exits 0 — never blocks the host agent.
pub fn hook_claude() -> anyhow::Result<()> {
    run_hook_resilient("", |stdin| {
        let r = edda_bridge_claude::hook_entrypoint_from_stdin(&stdin)?;
        Ok((r.stdout, r.stderr))
    })
}

/// Shared resilience wrapper: read stdin, spawn worker with catch_unwind + timeout.
///
/// `prefix` is prepended to debug log messages (e.g., `""` for Claude, `"OPENCLAW "` for OpenClaw).
/// `entrypoint` receives the stdin string and returns (stdout, stderr).
fn run_hook_resilient<F>(prefix: &str, entrypoint: F) -> anyhow::Result<()>
where
    F: FnOnce(String) -> anyhow::Result<(Option<String>, Option<String>)> + Send + 'static,
{
    let mut stdin_buf = String::new();
    if let Err(e) = std::io::stdin().read_to_string(&mut stdin_buf) {
        debug_log(&format!("{prefix}STDIN READ ERROR: {e}"));
        return Ok(());
    }

    debug_log(&format!(
        "{prefix}STDIN({} bytes): {}",
        stdin_buf.len(),
        &stdin_buf[..stdin_buf.len().min(200)]
    ));

    let timeout_ms = hook_timeout_ms();
    let (tx, rx) = std::sync::mpsc::channel();
    std::thread::spawn(move || {
        let result =
            std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| entrypoint(stdin_buf)));
        let _ = tx.send(result);
    });

    match rx.recv_timeout(std::time::Duration::from_millis(timeout_ms)) {
        Ok(Ok(Ok((stdout, stderr)))) => {
            if let Some(output) = &stdout {
                debug_log(&format!("{prefix}OK output({} bytes)", output.len()));
                print!("{output}");
            }
            if let Some(warning) = &stderr {
                debug_log(&format!("{prefix}WARNING: {warning}"));
                eprintln!("{warning}");
                // Exit 1 = non-blocking warning; Claude Code shows stderr to user
                // but does not feed it to the model or block the conversation.
                std::process::exit(1);
            }
            if stdout.is_none() && stderr.is_none() {
                debug_log(&format!("{prefix}OK (no output)"));
            }
            Ok(())
        }
        Ok(Ok(Err(e))) => {
            debug_log(&format!("{prefix}ERROR: {e}"));
            Ok(())
        }
        Ok(Err(panic_info)) => {
            let msg = panic_info
                .downcast_ref::<String>()
                .map(|s| s.as_str())
                .or_else(|| panic_info.downcast_ref::<&str>().copied())
                .unwrap_or("unknown panic");
            debug_log(&format!("{prefix}PANIC: {msg}"));
            Ok(())
        }
        Err(_) => {
            debug_log(&format!(
                "{prefix}TIMEOUT after {timeout_ms}ms — graceful exit"
            ));
            Ok(())
        }
    }
}

/// Hook timeout in milliseconds. Configurable via `EDDA_HOOK_TIMEOUT_MS` (default: 60s).
///
/// Raised from 10s to 60s to accommodate SessionEnd background threads that
/// make LLM API calls (bg_extract, bg_digest, bg_scan, bg_detect).  See #287.
fn hook_timeout_ms() -> u64 {
    std::env::var("EDDA_HOOK_TIMEOUT_MS")
        .ok()
        .and_then(|v| v.parse().ok())
        .unwrap_or(60_000)
}

fn debug_log(msg: &str) {
    if std::env::var_os("EDDA_DEBUG").is_none() {
        return;
    }
    use std::io::Write;
    let log_path = std::env::temp_dir().join("edda-hook-debug.log");
    if let Ok(mut f) = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(&log_path)
    {
        let ts = time::OffsetDateTime::now_utc()
            .format(&time::format_description::well_known::Rfc3339)
            .unwrap_or_default();
        let _ = writeln!(f, "[{ts}] {msg}");
    }
}

/// `edda doctor claude`
pub fn doctor(repo_root: &Path) -> anyhow::Result<()> {
    edda_bridge_claude::doctor(repo_root)
}

/// `edda bridge claude peers` — show active peer sessions
pub fn peers(repo_root: &Path) -> anyhow::Result<()> {
    let project_id = edda_store::project_id(repo_root);
    let sessions = edda_bridge_claude::peers::discover_all_sessions(&project_id);

    if sessions.is_empty() {
        println!("No active sessions.");
        return Ok(());
    }

    // Collapse stale sessions (heartbeat older than threshold) to a count so
    // dead heartbeat files do not read as live contention.
    let stale_threshold = edda_bridge_claude::peers::stale_secs();
    let (active, stale): (Vec<_>, Vec<_>) =
        sessions.iter().partition(|p| p.age_secs <= stale_threshold);

    if active.is_empty() {
        println!(
            "No active sessions ({} stale heartbeat{}).",
            stale.len(),
            if stale.len() == 1 { "" } else { "s" }
        );
        return Ok(());
    }

    println!("Active sessions ({}):\n", active.len());
    for p in &active {
        let age = edda_bridge_claude::peers::format_age(p.age_secs);
        let scope = if p.claimed_paths.is_empty() {
            String::new()
        } else {
            format!(" [{}]", p.claimed_paths.join(", "))
        };
        let label = if p.label.is_empty() {
            "(no label)".to_string()
        } else {
            p.label.clone()
        };
        println!(
            "  {}{} ({age}){scope}",
            &p.session_id[..8.min(p.session_id.len())],
            label
        );

        if !p.task_subjects.is_empty() {
            for t in &p.task_subjects {
                println!("    task: {t}");
            }
        } else if !p.focus_files.is_empty() {
            let files: Vec<&str> = p
                .focus_files
                .iter()
                .take(3)
                .map(|f| f.rsplit(['/', '\\']).next().unwrap_or(f.as_str()))
                .collect();
            println!("    focus: {}", files.join(", "));
        }
        if p.files_modified_count > 0 {
            println!("    {} files modified", p.files_modified_count);
        }
        if !p.recent_commits.is_empty() {
            for c in &p.recent_commits {
                println!("    commit: {c}");
            }
        }
    }
    if !stale.is_empty() {
        println!(
            "\n  (+{} stale session{} not shown)",
            stale.len(),
            if stale.len() == 1 { "" } else { "s" }
        );
    }
    Ok(())
}

/// `edda bridge claude claim <label>` — claim a coordination scope
pub fn claim(
    repo_root: &Path,
    label: &str,
    paths: &[String],
    cli_session: Option<&str>,
) -> anyhow::Result<()> {
    let project_id = edda_store::project_id(repo_root);
    let (session_id, _) = resolve_session_id(cli_session, &project_id, label);

    edda_bridge_claude::peers::write_claim(&project_id, &session_id, label, paths);
    println!("Claimed scope: {label}");
    if !paths.is_empty() {
        println!("  paths: {}", paths.join(", "));
    }
    println!("  session: {session_id}");
    Ok(())
}

/// `edda bridge claude decide <key=value>` — record a binding decision
///
/// Writes to both:
/// 1. Peers `coordination.jsonl` — real-time broadcast to active peers
/// 2. Workspace ledger — permanent record visible to all sessions
#[allow(clippy::too_many_arguments)]
pub fn decide(
    repo_root: &Path,
    decision: &str,
    reason: Option<&str>,
    refs: &[String],
    cli_session: Option<&str>,
    scope_str: Option<&str>,
    paths: &[String],
    tags: &[String],
) -> anyhow::Result<()> {
    let (key, value) = decision.split_once('=').ok_or_else(|| {
        anyhow::anyhow!("decision must be in key=value format (e.g. \"auth.method=JWT RS256\")")
    })?;

    let key = key.trim();
    let value = value.trim();

    // EDDA-SECRET-GUARD1 q331: scrub value + reason before ANY persistence
    // (peer broadcast, ledger, coordination log). Deterministic zero-LLM.
    let (safe_value, value_hits) = edda_core::secret_guard::redact(value);
    let value = safe_value.as_str();
    let (safe_reason, reason_hits) = match reason {
        Some(r) => {
            let (out, hits) = edda_core::secret_guard::redact(r);
            (Some(out), hits)
        }
        None => (None, Vec::new()),
    };
    let reason: Option<&str> = safe_reason.as_deref();
    let all_hits = value_hits.len() + reason_hits.len();
    if all_hits > 0 {
        let kinds: Vec<_> = value_hits
            .iter()
            .chain(reason_hits.iter())
            .map(|h| h.kind)
            .collect();
        eprintln!(
            "⚠ secret-guard: redacted {all_hits} secret pattern(s) before writing decision ({})",
            kinds.join(", ")
        );
    }

    let project_id = edda_store::project_id(repo_root);
    let (session_id, label) = resolve_session_id(cli_session, &project_id, "cli");

    // L2 conflict check (coordination.jsonl) — before writing
    if let Some(conflict) =
        edda_bridge_claude::peers::find_binding_conflict(&project_id, key, value)
    {
        eprintln!(
            "\u{26a0} Conflict: key \"{key}\" already decided as \"{}\" by {} ({})",
            conflict.existing_value, conflict.by_label, conflict.ts
        );
        eprintln!("  Recording your decision \"{key}={value}\" — consider resolving with the other agent.");
        // Postmortem supply line: SELECTOR3 病一——same label = own progression,
        // not a cross-agent conflict; only record when actors differ. Best-effort, never blocks.
        let _ = edda_postmortem::signals::record_conflict_signal_if_cross_actor(
            &project_id,
            key,
            &conflict.by_label,
            &label,
        );
    }

    // 1. Broadcast to peers (real-time)
    edda_bridge_claude::peers::write_binding(&project_id, &session_id, &label, key, value);

    // 2. Write to workspace ledger (permanent)
    let ledger = edda_ledger::Ledger::open(repo_root).context("cmd_bridge: opening ledger")?;
    let _lock = edda_ledger::lock::WorkspaceLock::acquire(&ledger.paths)?;
    let branch = ledger.head_branch()?;
    let parent_hash = ledger.last_event_hash()?;

    // Use resolved label as actor (not hardcoded "system")
    let actor = if session_id.starts_with("cli-") {
        "system"
    } else {
        &label
    };
    let scope = scope_str
        .filter(|s| *s != "local")
        .map(|s| s.parse::<edda_core::types::DecisionScope>())
        .transpose()
        .map_err(|e| anyhow::anyhow!("{e}"))?;
    let dp = edda_core::types::DecisionPayload {
        key: key.to_string(),
        value: value.to_string(),
        reason: reason.map(|r| r.to_string()),
        scope,
        authority: None,
        affected_paths: if paths.is_empty() {
            None
        } else {
            Some(paths.to_vec())
        },
        tags: if tags.is_empty() {
            None
        } else {
            Some(tags.to_vec())
        },
        review_after: None,
        reversibility: None,
        village_id: None,
    };
    let mut event =
        edda_core::event::new_decision_event(&branch, parent_hash.as_deref(), actor, &dp)?;

    // Check for prior decision with same key → supersede via provenance (only if value differs)
    let prior = ledger.find_active_decision(&branch, key)?;
    if let Some(prior_row) = &prior {
        if prior_row.value != value {
            eprintln!(
                "\u{26a0} Conflict: key \"{key}\" previously decided as \"{}\" in this workspace",
                prior_row.value
            );
            eprintln!("  Recording new value \"{value}\" (supersedes prior decision)");
            event.refs.provenance.push(edda_core::types::Provenance {
                target: prior_row.event_id.clone(),
                rel: edda_core::types::rel::SUPERSEDES.to_string(),
                note: Some(format!("key '{}' re-decided", key)),
            });
            // Postmortem supply line: best-effort, never blocks the decide.
            let _ = edda_postmortem::signals::record_decision_signal(
                &project_id,
                edda_postmortem::signals::SignalKind::Superseded,
                key,
            );
        }
    }

    // Add depends_on provenance for each --refs key
    for ref_key in refs {
        if let Some(ref_row) = ledger.find_active_decision(&branch, ref_key)? {
            event.refs.provenance.push(edda_core::types::Provenance {
                target: ref_row.event_id.clone(),
                rel: edda_core::types::rel::DEPENDS_ON.to_string(),
                note: Some(ref_key.to_string()),
            });
        } else {
            eprintln!("\u{26a0} ref '{ref_key}' not found, skipping");
        }
    }

    // Re-finalize after payload/refs mutation
    edda_core::event::finalize_event(&mut event)?;
    ledger.append_event(&event)?;

    // Insert dependency edges
    let domain = edda_core::decision::extract_domain(key);

    // Explicit refs → dep edges
    for ref_key in refs {
        // Only insert if the ref key actually exists
        if ledger.find_active_decision(&branch, ref_key)?.is_some() {
            ledger.insert_dep(key, ref_key, "explicit", Some(&event.event_id))?;
        }
    }

    // Auto-link: star-shaped within same domain
    let same_domain = ledger.active_decisions(Some(&domain), None, None, None)?;
    for d in &same_domain {
        if d.key != key {
            ledger.insert_dep(key, &d.key, "auto_domain", Some(&event.event_id))?;
        }
    }

    println!("Decision recorded: {key} = {value}");
    if let Some(r) = reason {
        println!("  reason: {r}");
    }
    if let Some(s) = scope {
        println!("  scope: {s}");
    }
    if !paths.is_empty() {
        println!("  paths: {}", paths.join(", "));
    }
    if !tags.is_empty() {
        println!("  tags: {}", tags.join(", "));
    }

    // Refresh derived markdown views (log.md / main.md / commit.md) so operators
    // reading the ledger by eye see the decision immediately, not only after the
    // next `edda commit` / `edda rebuild`. Same best-effort pattern as
    // edda-serve::api::drafts.rs:508 — failure never blocks a successful decide.
    let _ = edda_derive::rebuild_branch(&ledger, &branch);

    Ok(())
}

/// `edda bridge claude request <to> <message>` — send cross-agent request
pub fn request(
    repo_root: &Path,
    to: &str,
    message: &str,
    cli_session: Option<&str>,
) -> anyhow::Result<()> {
    let project_id = edda_store::project_id(repo_root);
    let (session_id, from_label) = resolve_session_id(cli_session, &project_id, "cli");

    edda_bridge_claude::peers::write_request(&project_id, &session_id, &from_label, to, message);
    println!("Request sent to [{to}]: \"{message}\"");
    Ok(())
}

/// `edda request-ack <from>` — acknowledge a pending request
pub fn request_ack(
    repo_root: &Path,
    from_label: &str,
    cli_session: Option<&str>,
) -> anyhow::Result<()> {
    let project_id = edda_store::project_id(repo_root);
    let (session_id, _label) = resolve_session_id(cli_session, &project_id, "cli");

    edda_bridge_claude::peers::write_request_ack(&project_id, &session_id, from_label);
    println!("Acknowledged request from [{from_label}]");
    Ok(())
}

/// Resolve session identity via 4-tier fallback:
///
/// 1. `--session` CLI flag (explicit override)
/// 2. `EDDA_SESSION_ID` env var (conductor path, user override)
/// 3. Heartbeat inference (auto-detect sole active session)
/// 4. `"cli-{fallback_label}"` (genuine CLI usage)
fn resolve_session_id(
    cli_session: Option<&str>,
    project_id: &str,
    fallback_label: &str,
) -> (String, String) {
    let env_label = std::env::var("EDDA_SESSION_LABEL")
        .ok()
        .filter(|v| !v.is_empty());

    // Tier 1: explicit --session flag
    if let Some(sid) = cli_session.filter(|s| !s.is_empty()) {
        let label = env_label.unwrap_or_else(|| fallback_label.to_string());
        return (sid.to_string(), label);
    }

    // Tier 2: EDDA_SESSION_ID env var
    if let Ok(sid) = std::env::var("EDDA_SESSION_ID") {
        if !sid.is_empty() {
            let label = env_label.unwrap_or_else(|| fallback_label.to_string());
            return (sid, label);
        }
    }

    // Tier 3: heartbeat inference (sole active session)
    if let Some((sid, label)) = edda_bridge_claude::peers::infer_session_id(project_id) {
        return (sid, label);
    }

    // Tier 4: fallback
    let label = env_label.unwrap_or_else(|| fallback_label.to_string());
    (format!("cli-{fallback_label}"), label)
}

/// `edda bridge claude digest --session <id>` or `--all`
pub fn digest(repo_root: &Path, session: Option<&str>, all: bool) -> anyhow::Result<()> {
    let project_id = edda_store::project_id(repo_root);
    let cwd = repo_root.to_str().unwrap_or(".");

    if let Some(session_id) = session {
        println!("Digesting session {session_id}...");
        let event_id =
            edda_bridge_claude::digest::digest_session_manual(&project_id, session_id, cwd, true)?;
        println!("  Written: {event_id}");
        return Ok(());
    }

    if all {
        let pending = edda_bridge_claude::digest::find_all_pending_sessions(&project_id);
        if pending.is_empty() {
            println!("No pending sessions to digest.");
            return Ok(());
        }
        println!("Found {} pending sessions", pending.len());
        for session_id in &pending {
            print!("  Digesting {session_id}...");
            match edda_bridge_claude::digest::digest_session_manual(
                &project_id,
                session_id,
                cwd,
                true,
            ) {
                Ok(event_id) => println!(" OK ({event_id})"),
                Err(e) => println!(" FAILED: {e}"),
            }
        }
        return Ok(());
    }

    anyhow::bail!("must specify --session <id> or --all")
}

/// `edda index verify --project <id> --session <id> [--sample N] [--all]`
pub fn index_verify(
    project_id: &str,
    session_id: &str,
    sample: usize,
    all: bool,
) -> anyhow::Result<()> {
    let project_dir = edda_store::project_dir(project_id);
    let index_path = project_dir
        .join("index")
        .join(format!("{session_id}.jsonl"));
    let store_path = project_dir
        .join("transcripts")
        .join(format!("{session_id}.jsonl"));

    if !index_path.exists() {
        anyhow::bail!("index file not found: {}", index_path.display());
    }
    if !store_path.exists() {
        anyhow::bail!("store file not found: {}", store_path.display());
    }

    let max_lines = if all { usize::MAX } else { sample * 2 };
    let records = edda_index::read_index_tail(&index_path, max_lines, 64 * 1024 * 1024)?;

    let check_count = if all {
        records.len()
    } else {
        sample.min(records.len())
    };

    // Sample evenly from the records
    let step = if check_count == 0 {
        1
    } else {
        (records.len() as f64 / check_count as f64).ceil() as usize
    };

    let mut checked = 0;
    let mut mismatches = 0;

    for (i, rec) in records.iter().enumerate() {
        if !all && i % step != 0 && checked >= check_count {
            continue;
        }
        if checked >= check_count {
            break;
        }

        let fetched = edda_index::fetch_store_line(&store_path, rec.store_offset, rec.store_len)?;
        let parsed: serde_json::Value = serde_json::from_slice(&fetched)?;
        let fetched_uuid = parsed.get("uuid").and_then(|v| v.as_str()).unwrap_or("");

        if fetched_uuid != rec.uuid {
            println!(
                "MISMATCH at index record {}: expected uuid={}, got uuid={}",
                i, rec.uuid, fetched_uuid
            );
            mismatches += 1;
        }
        checked += 1;
    }

    if mismatches > 0 {
        anyhow::bail!("{mismatches} mismatches found in {checked} checks");
    }

    println!("OK: {checked} index records verified, 0 mismatches");
    Ok(())
}

// ── Render Commands ──

/// `edda bridge claude render-writeback`
pub fn render_writeback() -> anyhow::Result<()> {
    println!("{}", edda_bridge_claude::render::writeback());
    Ok(())
}

/// `edda bridge claude render-workspace`
pub fn render_workspace(repo_root: &Path, budget: usize) -> anyhow::Result<()> {
    let cwd = repo_root.to_str().unwrap_or(".");
    match edda_bridge_claude::render::workspace(cwd, budget) {
        Some(s) => println!("{s}"),
        None => println!("(no workspace context)"),
    }
    Ok(())
}

/// `edda bridge claude render-coordination`
pub fn render_coordination(repo_root: &Path, cli_session: Option<&str>) -> anyhow::Result<()> {
    let project_id = edda_store::project_id(repo_root);
    let (session_id, _) = resolve_session_id(cli_session, &project_id, "cli");
    match edda_bridge_claude::render::coordination(&project_id, &session_id) {
        Some(s) => println!("{s}"),
        None => println!("(no coordination context)"),
    }
    Ok(())
}

/// `edda bridge claude render-pack`
pub fn render_pack(repo_root: &Path) -> anyhow::Result<()> {
    let project_id = edda_store::project_id(repo_root);
    match edda_bridge_claude::render::pack(&project_id) {
        Some(s) => println!("{s}"),
        None => println!("(no hot pack available)"),
    }
    Ok(())
}

/// `edda bridge claude render-plan`
pub fn render_plan(repo_root: &Path) -> anyhow::Result<()> {
    let project_id = edda_store::project_id(repo_root);
    match edda_bridge_claude::render::plan(Some(&project_id)) {
        Some(s) => println!("{s}"),
        None => println!("(no active plan)"),
    }
    Ok(())
}

// ── Heartbeat Commands ──

/// `edda bridge claude heartbeat-write`
pub fn heartbeat_write(
    repo_root: &Path,
    label: &str,
    cli_session: Option<&str>,
) -> anyhow::Result<()> {
    let project_id = edda_store::project_id(repo_root);
    let (session_id, _) = resolve_session_id(cli_session, &project_id, label);
    let _ = edda_store::ensure_dirs(&project_id);
    edda_bridge_claude::peers::write_heartbeat_minimal(
        &project_id,
        &session_id,
        label,
        repo_root.to_str().unwrap_or("."),
    );
    println!("Heartbeat written: {label} ({session_id})");
    Ok(())
}

/// `edda bridge claude heartbeat-touch`
pub fn heartbeat_touch(repo_root: &Path, cli_session: Option<&str>) -> anyhow::Result<()> {
    let project_id = edda_store::project_id(repo_root);
    let (session_id, _) = resolve_session_id(cli_session, &project_id, "cli");
    edda_bridge_claude::peers::touch_heartbeat(&project_id, &session_id);
    println!("Heartbeat touched: {session_id}");
    Ok(())
}

/// `edda bridge claude heartbeat-remove`
pub fn heartbeat_remove(repo_root: &Path, cli_session: Option<&str>) -> anyhow::Result<()> {
    let project_id = edda_store::project_id(repo_root);
    let (session_id, _) = resolve_session_id(cli_session, &project_id, "cli");
    edda_bridge_claude::peers::remove_heartbeat(&project_id, &session_id);
    println!("Heartbeat removed: {session_id}");
    Ok(())
}

// ── Background Decision Extraction ──

/// `edda bridge claude bg-review`
pub fn bg_review(
    repo_root: &Path,
    list: bool,
    accept: Option<String>,
    reject: Option<String>,
    accept_all: bool,
    session: Option<String>,
) -> anyhow::Result<()> {
    let project_id = edda_store::project_id(repo_root);

    if list {
        let drafts = edda_bridge_claude::bg_extract::list_pending_drafts(&project_id)?;
        if drafts.is_empty() {
            println!("No pending draft decisions.");
            return Ok(());
        }
        for draft in &drafts {
            println!(
                "\n── Session: {} (extracted: {}, model: {}) ──",
                draft.session_id, draft.extracted_at, draft.model
            );
            for (i, d) in draft.decisions.iter().enumerate() {
                let status_marker = match d.status {
                    edda_bridge_claude::bg_extract::DraftStatus::Pending => "",
                    edda_bridge_claude::bg_extract::DraftStatus::Accepted => "",
                    edda_bridge_claude::bg_extract::DraftStatus::Rejected => "",
                };
                let kind_label = match d.kind {
                    edda_bridge_claude::bg_extract::DecisionKind::Extraction => "extraction",
                    edda_bridge_claude::bg_extract::DecisionKind::Enhancement => "enhancement",
                };
                let reason_str = d.reason.as_deref().unwrap_or("-");
                println!(
                    "  [{i}] {status_marker} [{kind_label}] {}={} (confidence: {:.0}%)",
                    d.key,
                    d.value,
                    d.confidence * 100.0
                );
                if d.kind == edda_bridge_claude::bg_extract::DecisionKind::Enhancement {
                    let orig = d.original_reason.as_deref().unwrap_or("(none)");
                    println!("      original reason: {orig}");
                    println!("      enhanced reason: {reason_str}");
                } else {
                    println!("      reason: {reason_str}");
                }
                println!("      evidence: {}", d.evidence);
            }
        }
        return Ok(());
    }

    let session_id = session
        .as_deref()
        .ok_or_else(|| anyhow::anyhow!("--session is required for accept/reject operations"))?;

    if accept_all {
        let accepted =
            edda_bridge_claude::bg_extract::accept_all_decisions(&project_id, session_id)?;
        if accepted.is_empty() {
            println!("No pending decisions to accept.");
            return Ok(());
        }
        // Write accepted decisions to workspace ledger
        write_accepted_to_ledger(repo_root, &accepted)?;
        println!("Accepted {} decisions.", accepted.len());
        return Ok(());
    }

    if let Some(indices_str) = accept {
        let indices = parse_indices(&indices_str)?;
        let accepted =
            edda_bridge_claude::bg_extract::accept_decisions(&project_id, session_id, &indices)?;
        if accepted.is_empty() {
            println!("No decisions accepted (indices may be invalid or already processed).");
            return Ok(());
        }
        write_accepted_to_ledger(repo_root, &accepted)?;
        println!("Accepted {} decisions.", accepted.len());
        return Ok(());
    }

    if let Some(indices_str) = reject {
        let indices = parse_indices(&indices_str)?;
        edda_bridge_claude::bg_extract::reject_decisions(&project_id, session_id, &indices)?;
        println!("Rejected {} decisions.", indices.len());
        return Ok(());
    }

    // Default: list if no action specified
    println!("Usage: edda bridge claude bg-review --list");
    println!("       edda bridge claude bg-review --session <sid> --accept-all");
    println!("       edda bridge claude bg-review --session <sid> --accept 0,1,2");
    println!("       edda bridge claude bg-review --session <sid> --reject 3");
    Ok(())
}

fn write_accepted_to_ledger(
    repo_root: &Path,
    decisions: &[edda_bridge_claude::bg_extract::ExtractedDecision],
) -> anyhow::Result<()> {
    let ledger = edda_ledger::Ledger::open(repo_root)
        .context("cmd_bridge::write_accepted_to_ledger: opening ledger")?;
    let _lock = edda_ledger::lock::WorkspaceLock::acquire(&ledger.paths)?;
    let branch = ledger.head_branch()?;

    for d in decisions {
        let parent_hash = ledger.last_event_hash()?;
        let payload = edda_core::types::DecisionPayload {
            key: d.key.clone(),
            value: d.value.clone(),
            reason: d.reason.clone(),
            scope: None,
            authority: None,
            affected_paths: None,
            tags: None,
            review_after: None,
            reversibility: None,
            village_id: None,
        };

        let actor = match d.kind {
            edda_bridge_claude::bg_extract::DecisionKind::Enhancement => "edda-bg/reason-enhancer",
            edda_bridge_claude::bg_extract::DecisionKind::Extraction => {
                "edda-bg/decision-extractor"
            }
        };

        let mut event =
            edda_core::event::new_decision_event(&branch, parent_hash.as_deref(), actor, &payload)?;

        // For enhancements, supersede the original decision
        if d.kind == edda_bridge_claude::bg_extract::DecisionKind::Enhancement {
            if let Ok(Some(prior)) = ledger.find_active_decision(&branch, &d.key) {
                event.refs.provenance.push(edda_core::types::Provenance {
                    target: prior.event_id.clone(),
                    rel: edda_core::types::rel::SUPERSEDES.to_string(),
                    note: Some(format!(
                        "reason enhanced from: {}",
                        d.original_reason.as_deref().unwrap_or("(none)")
                    )),
                });
            }
        }

        ledger.append_event(&event)?;
    }

    Ok(())
}

fn parse_indices(s: &str) -> anyhow::Result<Vec<usize>> {
    s.split(',')
        .map(|part| {
            part.trim()
                .parse::<usize>()
                .map_err(|_| anyhow::anyhow!("Invalid index: {}", part.trim()))
        })
        .collect()
}

// ── OpenClaw Bridge ──

/// `edda bridge openclaw install`
pub fn install_openclaw(target: Option<&Path>) -> anyhow::Result<()> {
    edda_bridge_openclaw::install(target)
}

/// `edda bridge openclaw uninstall`
pub fn uninstall_openclaw(target: Option<&Path>) -> anyhow::Result<()> {
    edda_bridge_openclaw::uninstall(target)
}

/// `edda hook openclaw` — read stdin, dispatch hook
///
/// Resilience: catch_unwind + configurable timeout (EDDA_HOOK_TIMEOUT_MS).
/// On panic or timeout, exits 0 — never blocks the host agent.
pub fn hook_openclaw() -> anyhow::Result<()> {
    run_hook_resilient("OPENCLAW ", |stdin| {
        let r = edda_bridge_openclaw::hook_entrypoint_from_stdin(&stdin)?;
        Ok((r.stdout, r.stderr))
    })
}

/// `edda doctor openclaw`
pub fn doctor_openclaw() -> anyhow::Result<()> {
    edda_bridge_openclaw::doctor()
}

/// `edda bridge codex install`
pub fn install_codex(target: Option<&Path>) -> anyhow::Result<()> {
    edda_bridge_codex::install(target).map(|_| ())
}

/// `edda bridge codex uninstall`
pub fn uninstall_codex(target: Option<&Path>) -> anyhow::Result<()> {
    edda_bridge_codex::uninstall(target)
}

/// `edda hook codex` — read stdin, dispatch hook
pub fn hook_codex() -> anyhow::Result<()> {
    let mut stdin = String::new();
    std::io::stdin().read_to_string(&mut stdin)?;
    let r = edda_bridge_codex::hook_entrypoint_from_stdin(&stdin)?;
    if let Some(out) = r.stdout {
        println!("{out}");
    }
    if let Some(err) = r.stderr {
        eprintln!("{err}");
    }
    Ok(())
}

/// `edda doctor codex`
pub fn doctor_codex() -> anyhow::Result<()> {
    edda_bridge_codex::doctor()
}

/// `edda bridge hermes install`
pub fn install_hermes(target: Option<&Path>) -> anyhow::Result<()> {
    edda_bridge_hermes::install(target).map(|_| ())
}

/// `edda bridge hermes uninstall`
pub fn uninstall_hermes(target: Option<&Path>) -> anyhow::Result<()> {
    edda_bridge_hermes::uninstall(target)
}

/// `edda hook hermes` — read stdin, dispatch hook
pub fn hook_hermes() -> anyhow::Result<()> {
    let mut stdin = String::new();
    std::io::stdin().read_to_string(&mut stdin)?;
    let r = edda_bridge_hermes::hook_entrypoint_from_stdin(&stdin)?;
    if let Some(out) = r.stdout {
        println!("{out}");
    }
    if let Some(err) = r.stderr {
        eprintln!("{err}");
    }
    Ok(())
}

/// `edda doctor hermes`
pub fn doctor_hermes() -> anyhow::Result<()> {
    edda_bridge_hermes::doctor()
}

/// `edda bridge cursor install`
pub fn install_cursor(target: Option<&Path>) -> anyhow::Result<()> {
    edda_bridge_cursor::install(target).map(|_| ())
}

/// `edda bridge cursor uninstall`
pub fn uninstall_cursor(target: Option<&Path>) -> anyhow::Result<()> {
    edda_bridge_cursor::uninstall(target)
}

/// `edda hook cursor` — read stdin, dispatch hook
pub fn hook_cursor() -> anyhow::Result<()> {
    run_hook_resilient("CURSOR ", |stdin| {
        let r = edda_bridge_cursor::hook_entrypoint_from_stdin(&stdin)?;
        Ok((r.stdout, r.stderr))
    })
}

/// `edda doctor cursor`
pub fn doctor_cursor() -> anyhow::Result<()> {
    edda_bridge_cursor::doctor()
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicU64, Ordering};

    static TEST_COUNTER: AtomicU64 = AtomicU64::new(0);

    fn setup_workspace() -> (std::path::PathBuf, edda_ledger::Ledger) {
        let n = TEST_COUNTER.fetch_add(1, Ordering::SeqCst);
        let tmp = std::env::temp_dir().join(format!("edda_bridge_test_{}_{n}", std::process::id()));
        let _ = std::fs::remove_dir_all(&tmp);
        let paths = edda_ledger::EddaPaths::discover(&tmp);
        edda_ledger::ledger::init_workspace(&paths).unwrap();
        edda_ledger::ledger::init_head(&paths, "main").unwrap();
        edda_ledger::ledger::init_branches_json(&paths, "main").unwrap();
        let ledger = edda_ledger::Ledger::open(&tmp).unwrap();
        (tmp, ledger)
    }

    #[test]
    fn find_active_decision_returns_value() {
        let (tmp, ledger) = setup_workspace();
        let branch = ledger.head_branch().unwrap();
        let parent_hash = ledger.last_event_hash().unwrap();

        // Write a decision event with structured fields
        let tags = vec!["decision".to_string()];
        let mut event = edda_core::event::new_note_event(
            &branch,
            parent_hash.as_deref(),
            "system",
            "db.engine: postgres",
            &tags,
        )
        .unwrap();
        event.payload["decision"] = serde_json::json!({"key": "db.engine", "value": "postgres"});
        edda_core::event::finalize_event(&mut event).unwrap();
        ledger.append_event(&event).unwrap();

        let result = ledger.find_active_decision(&branch, "db.engine").unwrap();
        assert!(result.is_some(), "should find active decision");
        let row = result.unwrap();
        assert!(!row.event_id.is_empty());
        assert_eq!(row.value, "postgres");

        let _ = std::fs::remove_dir_all(&tmp);
    }

    #[test]
    fn find_active_decision_no_match() {
        let (tmp, ledger) = setup_workspace();
        let branch = ledger.head_branch().unwrap();

        let result = ledger
            .find_active_decision(&branch, "nonexistent.key")
            .unwrap();
        assert!(result.is_none(), "should not find anything");

        let _ = std::fs::remove_dir_all(&tmp);
    }

    // ── Integration: decide() end-to-end (Issue #148 Gaps 1, 2) ──

    #[test]
    fn decide_writes_binding_to_coordination_log() {
        let (tmp, _ledger) = setup_workspace();
        let pid = edda_store::project_id(&tmp);
        let _ = edda_store::ensure_dirs(&pid);
        // Clean coordination log
        let state_dir = edda_store::project_dir(&pid).join("state");
        let _ = std::fs::remove_file(state_dir.join("coordination.jsonl"));

        std::env::set_var("EDDA_SESSION_ID", "test-decide-bind-s1");
        std::env::set_var("EDDA_SESSION_LABEL", "auth");

        decide(
            &tmp,
            "db.engine=postgres",
            Some("need JSONB"),
            &[],
            None,
            None,
            &[],
            &[],
        )
        .unwrap();

        // Verify binding was written via L2 conflict check API
        let conflict = edda_bridge_claude::peers::find_binding_conflict(&pid, "db.engine", "OTHER");
        assert!(
            conflict.is_some(),
            "should find existing binding via conflict check"
        );
        let c = conflict.unwrap();
        assert_eq!(c.existing_value, "postgres");
        // Verify no conflict with same value (idempotent)
        let no_conflict =
            edda_bridge_claude::peers::find_binding_conflict(&pid, "db.engine", "postgres");
        assert!(no_conflict.is_none(), "same value should not conflict");

        std::env::remove_var("EDDA_SESSION_ID");
        std::env::remove_var("EDDA_SESSION_LABEL");
        let _ = std::fs::remove_dir_all(&tmp);
        let _ = std::fs::remove_dir_all(edda_store::project_dir(&pid));
    }

    #[test]
    fn decide_writes_structured_ledger_event() {
        let (tmp, ledger) = setup_workspace();
        let pid = edda_store::project_id(&tmp);
        let _ = edda_store::ensure_dirs(&pid);

        std::env::set_var("EDDA_SESSION_ID", "test-decide-ledger-s2");
        std::env::set_var("EDDA_SESSION_LABEL", "billing");

        decide(
            &tmp,
            "auth.method=JWT RS256",
            Some("stateless auth"),
            &[],
            None,
            None,
            &[],
            &[],
        )
        .unwrap();

        let events = ledger.iter_events().unwrap();
        assert_eq!(events.len(), 1, "should have 1 event");
        let e = &events[0];
        assert_eq!(e.event_type, "note");

        // Tags
        let tags = e.payload.get("tags").and_then(|v| v.as_array()).unwrap();
        assert!(tags.iter().any(|t| t.as_str() == Some("decision")));

        // Structured decision object
        let dec = e.payload.get("decision").unwrap();
        assert_eq!(dec["key"].as_str().unwrap(), "auth.method");
        assert_eq!(dec["value"].as_str().unwrap(), "JWT RS256");
        assert_eq!(dec["reason"].as_str().unwrap(), "stateless auth");

        std::env::remove_var("EDDA_SESSION_ID");
        std::env::remove_var("EDDA_SESSION_LABEL");
        let _ = std::fs::remove_dir_all(&tmp);
        let _ = std::fs::remove_dir_all(edda_store::project_dir(&pid));
    }

    #[test]
    fn decide_supersedes_prior_decision_same_key() {
        let (tmp, ledger) = setup_workspace();
        let pid = edda_store::project_id(&tmp);
        let _ = edda_store::ensure_dirs(&pid);

        std::env::set_var("EDDA_SESSION_ID", "test-decide-super-s3");
        std::env::set_var("EDDA_SESSION_LABEL", "infra");

        decide(&tmp, "db.engine=SQLite", None, &[], None, None, &[], &[]).unwrap();
        decide(
            &tmp,
            "db.engine=PostgreSQL",
            Some("need JSONB"),
            &[],
            None,
            None,
            &[],
            &[],
        )
        .unwrap();

        let events = ledger.iter_events().unwrap();
        assert_eq!(events.len(), 2, "should have 2 events");

        let first_id = &events[0].event_id;
        let second = &events[1];

        // Second event should supersede the first
        assert!(
            !second.refs.provenance.is_empty(),
            "second event should have provenance"
        );
        let prov = &second.refs.provenance[0];
        assert_eq!(prov.target, *first_id, "should point to first event");
        assert_eq!(prov.rel, edda_core::types::rel::SUPERSEDES);

        std::env::remove_var("EDDA_SESSION_ID");
        std::env::remove_var("EDDA_SESSION_LABEL");
        let _ = std::fs::remove_dir_all(&tmp);
        let _ = std::fs::remove_dir_all(edda_store::project_dir(&pid));
    }

    // ── Integration: resolve_session_id 4-tier fallback (Issue #148 Gap 4) ──

    #[test]
    fn resolve_session_id_tiers() {
        let pid = "test_resolve_sid_tiers";
        let _ = edda_store::ensure_dirs(pid);

        // Clear env to avoid interference
        std::env::remove_var("EDDA_SESSION_ID");
        std::env::remove_var("EDDA_SESSION_LABEL");

        // Tier 1: explicit cli_session
        let (sid, label) = resolve_session_id(Some("explicit-sid"), pid, "cli");
        assert_eq!(sid, "explicit-sid");
        assert_eq!(label, "cli");

        // Tier 2: EDDA_SESSION_ID env
        std::env::set_var("EDDA_SESSION_ID", "env-sid");
        let (sid, _) = resolve_session_id(None, pid, "cli");
        assert_eq!(sid, "env-sid");
        std::env::remove_var("EDDA_SESSION_ID");

        // Tier 3: heartbeat inference (single active session)
        // Clean state dir first to avoid interference from concurrent sessions
        let state_dir = edda_store::project_dir(pid).join("state");
        if state_dir.exists() {
            for entry in std::fs::read_dir(&state_dir).unwrap() {
                let entry = entry.unwrap();
                if entry
                    .file_name()
                    .to_str()
                    .is_some_and(|n| n.starts_with("session."))
                {
                    let _ = std::fs::remove_file(entry.path());
                }
            }
        }
        let _ = std::fs::create_dir_all(&state_dir);
        let now = time::OffsetDateTime::now_utc();
        let now_str = now
            .format(&time::format_description::well_known::Rfc3339)
            .unwrap();
        let hb = serde_json::json!({
            "session_id": "inferred-sess",
            "started_at": now_str,
            "last_heartbeat": now_str,
            "label": "worker",
            "focus_files": [],
            "active_tasks": [],
            "files_modified_count": 0,
            "total_edits": 0,
            "recent_commits": []
        });
        std::fs::write(
            state_dir.join("session.inferred-sess.json"),
            serde_json::to_string_pretty(&hb).unwrap(),
        )
        .unwrap();
        let (sid, label) = resolve_session_id(None, pid, "cli");
        assert_eq!(sid, "inferred-sess", "should infer from sole heartbeat");
        assert_eq!(label, "worker", "should use heartbeat label");
        let _ = std::fs::remove_file(state_dir.join("session.inferred-sess.json"));

        // Tier 4: fallback (no heartbeats, no env)
        let (sid, label) = resolve_session_id(None, pid, "cli");
        assert_eq!(sid, "cli-cli");
        assert_eq!(label, "cli");

        // Tier 1 wins over Tier 2
        std::env::set_var("EDDA_SESSION_ID", "env-sid");
        let (sid, _) = resolve_session_id(Some("explicit-wins"), pid, "cli");
        assert_eq!(sid, "explicit-wins", "tier 1 should beat tier 2");
        std::env::remove_var("EDDA_SESSION_ID");

        let _ = std::fs::remove_dir_all(edda_store::project_dir(pid));
    }

    // ── Render & Heartbeat CLI tests (Issue #15) ──

    #[test]
    fn render_writeback_contains_protocol() {
        let output = edda_bridge_claude::render::writeback();
        assert!(
            output.contains("Write-Back Protocol"),
            "should contain header"
        );
        assert!(output.contains("edda decide"), "should teach edda decide");
        assert!(output.contains("edda note"), "should teach edda note");
    }

    #[test]
    fn render_workspace_with_ledger() {
        let (tmp, _ledger) = setup_workspace();
        let cwd = tmp.to_str().unwrap();
        let result = edda_bridge_claude::render::workspace(cwd, 2500);
        assert!(
            result.is_some(),
            "workspace with ledger should produce output"
        );
        let text = result.unwrap();
        assert!(
            text.contains("Project") || text.contains("Branch"),
            "should contain workspace sections"
        );
        let _ = std::fs::remove_dir_all(&tmp);
    }

    #[test]
    fn render_workspace_no_ledger() {
        let result = edda_bridge_claude::render::workspace("/nonexistent/path", 2500);
        assert!(result.is_none(), "no workspace should return None");
    }

    #[test]
    fn render_coordination_solo_no_bindings() {
        let pid = "test_render_coord_solo";
        let _ = edda_store::ensure_dirs(pid);
        let result = edda_bridge_claude::render::coordination(pid, "solo-session");
        // Solo with no bindings → None
        assert!(
            result.is_none(),
            "solo session with no bindings should return None"
        );
        let _ = std::fs::remove_dir_all(edda_store::project_dir(pid));
    }

    #[test]
    fn render_pack_no_pack_file() {
        let pid = "test_render_pack_empty";
        let _ = edda_store::ensure_dirs(pid);
        let result = edda_bridge_claude::render::pack(pid);
        assert!(result.is_none(), "no hot.md should return None");
        let _ = std::fs::remove_dir_all(edda_store::project_dir(pid));
    }

    #[test]
    fn heartbeat_write_touch_remove_lifecycle() {
        let pid = "test_hb_lifecycle";
        let sid = "sess-lifecycle-1";
        let _ = edda_store::ensure_dirs(pid);

        // Write
        edda_bridge_claude::peers::write_heartbeat_minimal(pid, sid, "worker", ".");
        let state_dir = edda_store::project_dir(pid).join("state");
        let hb_path = state_dir.join(format!("session.{sid}.json"));
        assert!(hb_path.exists(), "heartbeat file should exist after write");

        // Verify label
        let content: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(&hb_path).unwrap()).unwrap();
        assert_eq!(content["label"].as_str().unwrap(), "worker");
        assert_eq!(content["session_id"].as_str().unwrap(), sid);

        // Touch
        let _mtime_before = std::fs::metadata(&hb_path).unwrap().modified().unwrap();
        std::thread::sleep(std::time::Duration::from_millis(50));
        edda_bridge_claude::peers::touch_heartbeat(pid, sid);
        let content_after: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(&hb_path).unwrap()).unwrap();
        // last_heartbeat string should have changed
        assert_ne!(
            content["last_heartbeat"].as_str().unwrap(),
            content_after["last_heartbeat"].as_str().unwrap(),
            "touch should update last_heartbeat"
        );

        // Remove
        edda_bridge_claude::peers::remove_heartbeat(pid, sid);
        assert!(
            !hb_path.exists(),
            "heartbeat file should be gone after remove"
        );

        let _ = std::fs::remove_dir_all(edda_store::project_dir(pid));
    }

    // ── Hook resilience tests (#83) ──

    #[test]
    fn catch_unwind_recovers_from_panic() {
        // Verify catch_unwind pattern works with panicking closures
        let (tx, rx) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(
                || -> anyhow::Result<String> {
                    panic!("test panic in hook");
                },
            ));
            let _ = tx.send(result);
        });

        let outcome = rx.recv_timeout(std::time::Duration::from_secs(5));
        assert!(outcome.is_ok(), "channel should receive");
        let inner = outcome.unwrap();
        assert!(inner.is_err(), "should be a caught panic");
        let panic_info = inner.unwrap_err();
        let msg = panic_info
            .downcast_ref::<&str>()
            .copied()
            .unwrap_or("unknown");
        assert_eq!(msg, "test panic in hook");
    }

    #[test]
    fn timeout_fires_on_slow_hook() {
        let (tx, rx) = std::sync::mpsc::channel::<anyhow::Result<String>>();
        std::thread::spawn(move || {
            std::thread::sleep(std::time::Duration::from_secs(60));
            let _ = tx.send(Ok("too late".to_string()));
        });

        let outcome = rx.recv_timeout(std::time::Duration::from_millis(50));
        assert!(
            outcome.is_err(),
            "should timeout before slow hook completes"
        );
    }

    #[test]
    fn hook_timeout_ms_defaults_to_60s() {
        std::env::remove_var("EDDA_HOOK_TIMEOUT_MS");
        assert_eq!(hook_timeout_ms(), 60_000);
    }

    #[test]
    fn hook_timeout_ms_reads_env() {
        std::env::set_var("EDDA_HOOK_TIMEOUT_MS", "5000");
        assert_eq!(hook_timeout_ms(), 5000);
        std::env::remove_var("EDDA_HOOK_TIMEOUT_MS");
    }
}