zynk 1.5.1

Portable protocol and helper CLI for multi-agent collaboration.
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
//! Agent-ergonomics command layer (ADR 040). Thin verbs that COMPOSE the
//! existing audited `send_herdr::run` path (`reply`, `send agent`) and strictly
//! read-only helpers (`whoami`/`who`, `inbox`, `thread`, `doctor`).
//!
//! Architecture spine (ADR 040 D1/D6): the send verbs resolve routing fields,
//! build a `send_herdr::SendHerdrArgs`, and call `send_herdr::run`, so the
//! persisted audit+corpus record is byte-identical to the longhand by
//! construction — no duplicated audit/corpus write logic, and no new target
//! flags on `send herdr`.

use crate::herdr_orchestration::{load_inventory, Inventory, PaneView};
use crate::{CliError, CliResult};
use clap::Args;
use std::fs;
use std::io::IsTerminal;
use std::process::Command;

/// The running agent's live Herdr context, resolved from `HERDR_PANE_ID`
/// (NOT the focused pane — a working agent's pane is frequently not focused).
#[derive(Debug, Clone)]
pub(crate) struct SelfContext {
    pub agent: String,
    pub pane_id: String,
    pub workspace_id: String,
    pub tab: Option<String>,
    pub cwd: Option<String>,
}

#[derive(Debug, Args)]
pub struct WhoamiArgs {
    #[arg(long, default_value = "table", value_enum, help = "Output format.")]
    pub format: crate::herdr_orchestration::OutputFormat,
    #[arg(long, default_value = "herdr", help = "herdr executable path.")]
    pub herdr_bin: String,
}

/// Resolve a target agent name to exactly one live pane (ADR 040 D2). Pure over
/// a loaded `Inventory` so it is unit-testable without a herdr call. Scoped to
/// `workspace` when `Some` (id, label, or number). Aborts with NO side effect on
/// 0 (no live pane) / >1 (ambiguous) matches.
pub(crate) fn resolve_target_in(
    inventory: &Inventory,
    agent: &str,
    workspace: Option<&str>,
) -> CliResult<(String, String)> {
    let candidates: Vec<&PaneView> = inventory
        .workspaces
        .iter()
        .filter(|w| match workspace {
            Some(selector) => workspace_matches(w, selector),
            None => true,
        })
        .flat_map(|w| w.tabs.iter())
        .flat_map(|t| t.panes.iter())
        .filter(|pane| pane.agent.as_deref() == Some(agent))
        .collect();

    match candidates.as_slice() {
        [one] => Ok((agent.to_string(), one.pane_id.clone())),
        [] => {
            let scope = match workspace {
                Some(w) => format!(" in workspace {w}"),
                None => String::new(),
            };
            Err(CliError::usage(format!(
                "no live pane for agent {agent}{scope}"
            )))
        }
        many => {
            let listing = many
                .iter()
                .map(|pane| format!("{}:{}", pane.workspace_id, pane.pane_id))
                .collect::<Vec<_>>()
                .join(", ");
            Err(CliError::usage(format!(
                "agent {agent} is ambiguous across live panes ({listing}); pass --to-pane <id> or --workspace"
            )))
        }
    }
}

fn workspace_matches(
    workspace: &crate::herdr_orchestration::WorkspaceView,
    selector: &str,
) -> bool {
    workspace.workspace_id == selector
        || workspace.label.as_deref() == Some(selector)
        || workspace.number.is_some_and(|n| n.to_string() == selector)
}

/// Resolve the target by loading the live inventory (ADR 040 D2: never a stored
/// pane id), then delegating to the pure `resolve_target_in`.
pub(crate) fn resolve_target(
    herdr_bin: &str,
    agent: &str,
    workspace: Option<&str>,
) -> CliResult<(String, String)> {
    let inventory = load_inventory(herdr_bin)?;
    resolve_target_in(&inventory, agent, workspace)
}

/// Resolve "me" from `HERDR_PANE_ID` via `herdr pane get <id>` (ADR 040 D2 source
/// rule). Fails loud if the env var is unset or the pane cannot be resolved.
pub(crate) fn resolve_self(herdr_bin: &str) -> CliResult<SelfContext> {
    let pane_env = std::env::var("HERDR_PANE_ID").map_err(|_| {
        CliError::failure("cannot resolve self: HERDR_PANE_ID is not set (run inside a Herdr pane)")
    })?;
    if pane_env.trim().is_empty() {
        return Err(CliError::failure(
            "cannot resolve self: HERDR_PANE_ID is empty",
        ));
    }
    let output = Command::new(herdr_bin)
        .args(["pane", "get", &pane_env])
        .output()
        .map_err(|error| {
            if error.kind() == std::io::ErrorKind::NotFound {
                CliError::with_code(127, format!("herdr CLI not found at {herdr_bin}"))
            } else {
                CliError::failure(format!("failed to run herdr pane get: {error}"))
            }
        })?;
    if !output.status.success() {
        return Err(CliError::failure(format!(
            "cannot resolve self: herdr pane get {pane_env} failed: {}",
            String::from_utf8_lossy(&output.stderr).trim()
        )));
    }
    let stdout = String::from_utf8(output.stdout)
        .map_err(|error| CliError::failure(format!("herdr pane get output not utf-8: {error}")))?;
    parse_self_from_pane_get(&stdout)
}

/// Parse the `herdr pane get` JSON envelope into a `SelfContext`. The singular
/// `herdr pane get` wraps the pane object under `result.pane`
/// (verified against real herdr): `{result: {pane: {agent, pane_id,
/// workspace_id, tab_id, cwd, foreground_cwd, focused, ...}}}`. (Distinct from
/// `pane list`, which is flat `result.panes[]`.)
fn parse_self_from_pane_get(stdout: &str) -> CliResult<SelfContext> {
    let value: serde_json::Value = serde_json::from_str(stdout).map_err(|error| {
        CliError::failure(format!("failed to parse herdr pane get JSON: {error}"))
    })?;
    let pane = &value["result"]["pane"];
    let agent = pane["agent"]
        .as_str()
        .filter(|s| !s.is_empty())
        .ok_or_else(|| {
            CliError::failure("herdr pane get JSON missing result.pane.agent (cannot resolve self)")
        })?
        .to_string();
    let pane_id = pane["pane_id"]
        .as_str()
        .filter(|s| !s.is_empty())
        .ok_or_else(|| CliError::failure("herdr pane get JSON missing result.pane.pane_id"))?
        .to_string();
    let workspace_id = pane["workspace_id"]
        .as_str()
        .filter(|s| !s.is_empty())
        .ok_or_else(|| CliError::failure("herdr pane get JSON missing result.pane.workspace_id"))?
        .to_string();
    let tab = pane["tab_id"].as_str().map(str::to_string);
    let cwd = pane["foreground_cwd"]
        .as_str()
        .or_else(|| pane["cwd"].as_str())
        .map(str::to_string);
    Ok(SelfContext {
        agent,
        pane_id,
        workspace_id,
        tab,
        cwd,
    })
}

/// `whoami` / `who` (ADR 040 D5): strictly read-only. Prints the running agent's
/// live context plus the addressable peers. Creates no `.zynk/`, no `outputs/`,
/// no DB state.
pub fn run_whoami(args: WhoamiArgs) -> CliResult<()> {
    use crate::herdr_orchestration::OutputFormat;
    let me = resolve_self(&args.herdr_bin)?;
    let inventory = load_inventory(&args.herdr_bin)?;
    let peers = peer_summary(&inventory, &me);

    match args.format {
        OutputFormat::Json => {
            let value = serde_json::json!({
                "agent": me.agent,
                "pane_id": me.pane_id,
                "workspace_id": me.workspace_id,
                "tab": me.tab,
                "cwd": me.cwd,
                "peers": peers.iter().map(|p| serde_json::json!({
                    "agent": p.agent,
                    "pane_id": p.pane_id,
                    "workspace_id": p.workspace_id,
                    "uniquely_addressable": p.uniquely_addressable,
                })).collect::<Vec<_>>(),
            });
            println!(
                "{}",
                serde_json::to_string_pretty(&value).map_err(|error| {
                    CliError::failure(format!("failed to render whoami JSON: {error}"))
                })?
            );
        }
        OutputFormat::Table => {
            println!("agent       {}", me.agent);
            println!("pane_id     {}", me.pane_id);
            println!("workspace   {}", me.workspace_id);
            println!("tab         {}", me.tab.as_deref().unwrap_or("-"));
            println!("cwd         {}", me.cwd.as_deref().unwrap_or("-"));
            println!();
            println!(
                "{:<12} {:<18} {:<12} ADDRESSABLE",
                "PEER", "PANE", "WORKSPACE"
            );
            for peer in &peers {
                println!(
                    "{:<12} {:<18} {:<12} {}",
                    peer.agent,
                    peer.pane_id,
                    peer.workspace_id,
                    if peer.uniquely_addressable {
                        "yes"
                    } else {
                        "no (ambiguous)"
                    }
                );
            }
        }
    }
    Ok(())
}

struct PeerSummary {
    agent: String,
    pane_id: String,
    workspace_id: String,
    uniquely_addressable: bool,
}

/// Other agents' panes (excluding my own pane), each flagged with whether the
/// agent name resolves to exactly one pane across all workspaces (uniquely
/// addressable by name alone).
fn peer_summary(inventory: &Inventory, me: &SelfContext) -> Vec<PeerSummary> {
    use std::collections::HashMap;
    let mut agent_counts: HashMap<&str, usize> = HashMap::new();
    for pane in all_panes(inventory) {
        if let Some(agent) = pane.agent.as_deref() {
            *agent_counts.entry(agent).or_insert(0) += 1;
        }
    }
    let mut peers = Vec::new();
    for pane in all_panes(inventory) {
        let Some(agent) = pane.agent.as_deref() else {
            continue;
        };
        if pane.pane_id == me.pane_id {
            continue;
        }
        peers.push(PeerSummary {
            agent: agent.to_string(),
            pane_id: pane.pane_id.clone(),
            workspace_id: pane.workspace_id.clone(),
            uniquely_addressable: agent_counts.get(agent).copied().unwrap_or(0) == 1,
        });
    }
    peers
}

fn all_panes(inventory: &Inventory) -> impl Iterator<Item = &PaneView> {
    inventory
        .workspaces
        .iter()
        .flat_map(|w| w.tabs.iter())
        .flat_map(|t| t.panes.iter())
}

// ---------------------------------------------------------------------------
// `zynk reply <mid>` (ADR 040 centerpiece). Routing inferred (re/to/from/pane/
// session/mode), judgment explicit (type + body required; ref never defaulted).
// Composes `send_herdr::run` so the persisted record is byte-identical (D1).
// ---------------------------------------------------------------------------

#[derive(Debug, Args)]
pub struct ReplyArgs {
    #[arg(help = "Parent message id to reply to (sets re=<mid>; routing inferred from it).")]
    pub mid: String,
    #[arg(
        long = "type",
        help = "Message type (ADR 040 D3: NEVER inferred — the default reply to a request-review is not approve)."
    )]
    pub message_type: Option<String>,
    #[arg(
        long,
        help = "Artifact reference (ADR 040 D3: NOT defaulted from the parent — a reply's artifact usually differs)."
    )]
    pub r#ref: Option<String>,
    #[arg(
        long,
        help = "Collaboration mode; defaults to the parent's mode, else the message default (ADR 040 D3)."
    )]
    pub mode: Option<String>,
    #[arg(
        long,
        help = "Reply body inline; otherwise --body-file, otherwise stdin (when not a TTY)."
    )]
    pub body: Option<String>,
    #[arg(
        long,
        help = "Reply body file ('-' reads stdin); otherwise stdin when not a TTY."
    )]
    pub body_file: Option<std::path::PathBuf>,
    #[arg(long = "reply-mid", help = "Override the auto-minted reply mid.")]
    pub reply_mid: Option<String>,
    // ADR 040 D2: a reply's target workspace is ALWAYS the parent/thread
    // workspace; there is intentionally NO --workspace override (that would
    // redirect the peer resolution off the thread). Disambiguating an ambiguous
    // parent mid is --session-id's job (P3), not a workspace override.
    #[arg(
        long,
        help = "Disambiguate the parent when the mid is reused across sessions (ADR 001): scope the parent lookup to this session. Required when a cross-session mid collision is detected."
    )]
    pub session_id: Option<String>,
    #[arg(
        long,
        default_value = "outputs",
        help = "Audit artifact root (read for the parent, written for the reply)."
    )]
    pub root: std::path::PathBuf,
    #[arg(
        long,
        help = "Live DB path for the parent lookup + reply projection; defaults to cwd .zynk/zynk.db."
    )]
    pub db: Option<std::path::PathBuf>,
    #[arg(
        long,
        help = "Force file-only (no DB for the parent lookup or the reply projection)."
    )]
    pub no_db: bool,
    #[arg(
        long,
        help = "Opt out of the audited reply (send only; no audit/corpus record)."
    )]
    pub no_audit: bool,
    #[arg(
        long,
        default_value = "agent",
        value_parser = ["agent", "operator", "helper-tool", "unknown"],
        help = "Who originated this reply, for the audit record."
    )]
    pub command_origin: String,
    #[arg(
        long,
        default_value = "full",
        help = "Redaction policy for the audited reply payload."
    )]
    pub payload_redaction_policy: String,
    #[arg(
        long,
        help = "Preview the inferred routing + composed message without sending; writes no audit/outputs (--type still required)."
    )]
    pub dry_run: bool,
    #[arg(long, default_value = "herdr", help = "herdr executable path.")]
    pub herdr_bin: String,
}

/// The parent's inferable routing/threading context (ADR 040 D3): the only
/// fields a reply derives from the parent record. The live source/target panes
/// are NOT here — they come from live Herdr at send time (D2).
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ParentContext {
    pub source_agent: String,
    pub session_id: String,
    pub mode: Option<String>,
    pub workspace_id: String,
}

pub fn run_reply(args: ReplyArgs) -> CliResult<()> {
    // ADR 040 D3: type is required (never inferred), the body is required.
    let message_type = args.message_type.clone().ok_or_else(|| {
        CliError::usage("reply requires --type (ADR 040 D3: the type is never inferred)")
    })?;

    // Lookup the parent (DB fast-path; file is the conflict authority — D7).
    // --session-id disambiguates a mid reused across sessions (ADR 001).
    let db_path = resolve_db_path(args.db.as_deref(), args.no_db);
    let parent = load_parent(
        &args.mid,
        db_path.as_deref(),
        &args.root,
        args.session_id.as_deref(),
    )?;

    // ADR 040 D2: resolve BOTH sides live, BEFORE any write. A stale source is
    // as much a byte-identity violation as a stale target, so resolve self too.
    // The target is ALWAYS scoped to the parent/thread workspace (no override) —
    // a reply must deliver within the thread, never redirect to another workspace.
    let me = resolve_self(&args.herdr_bin)?;
    let (peer_agent, peer_pane) = resolve_target(
        &args.herdr_bin,
        &parent.source_agent,
        Some(parent.workspace_id.as_str()),
    )?;

    // ADR 040 D3 mode: --mode wins, else the parent's, else the message default
    // (left to compose by passing None).
    let mode = args.mode.clone().or_else(|| parent.mode.clone());

    let body = read_body(args.body.as_deref(), args.body_file.as_deref())?;

    // Compose the SAME SendHerdrArgs the longhand would build (D1/D6). The
    // audited send requires target_address == --pane, so --pane is the peer pane.
    let send_args = build_send_args(BuildSend {
        herdr_bin: args.herdr_bin,
        me: &me,
        peer_agent: &peer_agent,
        peer_pane: &peer_pane,
        mid: args.reply_mid.clone(),
        message_type,
        re: Some(args.mid.clone()),
        r#ref: args.r#ref.clone(),
        mode,
        session_id: parent.session_id.clone(),
        body,
        command_origin: args.command_origin,
        payload_redaction_policy: args.payload_redaction_policy,
        no_audit: args.no_audit,
        dry_run: args.dry_run,
        db: args.db,
        no_db: args.no_db,
        root: args.root,
    })?;
    crate::send_herdr::run(send_args)
}

/// Resolve the effective DB path for a read+projection: `--no-db` → None;
/// `--db` → that path; default → cwd `.zynk/zynk.db` *only if it exists* (read
/// helpers and parent lookups must not auto-create it — ADR 040 D5/D7).
fn resolve_db_path(db: Option<&std::path::Path>, no_db: bool) -> Option<std::path::PathBuf> {
    if no_db {
        return None;
    }
    if let Some(db) = db {
        return Some(db.to_path_buf());
    }
    let default = std::path::Path::new(".zynk/zynk.db");
    default.exists().then(|| default.to_path_buf())
}

/// Look up the parent's inferable context by `mid` (ADR 040 D7 + P3 / ADR 001).
///
/// ADR 001:95 scopes `mid` uniqueness to `(from, active session)`, NOT globally,
/// so a mid can legitimately recur across sessions. This resolver gathers the
/// parent context PER session (across DB + `outputs/`), then:
/// - if `session` is given, scopes to that session (or errors if absent there);
/// - if the mid resolves in exactly one session, returns it;
/// - if it resolves in MORE THAN ONE session and `session` is not given, ABORTS
///   with no write, listing the candidate sessions (the caller must pass
///   `--session-id`).
///
/// The `outputs/` file is the conflict authority per session: where the DB and a
/// file disagree on an inferred field for the same session, the file wins (a
/// loud warning, never a silent stale-DB override).
pub(crate) fn load_parent(
    mid: &str,
    db: Option<&std::path::Path>,
    root: &std::path::Path,
    session: Option<&str>,
) -> CliResult<ParentContext> {
    use std::collections::BTreeMap;
    let from_db: BTreeMap<String, ParentContext> = match db {
        Some(path) if path.exists() => load_parent_candidates_from_db(mid, path)?,
        _ => BTreeMap::new(),
    };
    let from_file = load_parent_candidates_from_file(mid, root)?;

    // Merge per session, file-authoritative on disagreement.
    let mut sessions: BTreeMap<String, ParentContext> = from_db;
    for (session_id, file_ctx) in from_file {
        match sessions.get(&session_id) {
            Some(db_ctx) if *db_ctx != file_ctx => {
                eprintln!(
                    "warning: parent {mid} in session {session_id} disagrees between the DB and the outputs file; resolving from the file (ADR 027/040 D7 conflict authority)"
                );
                sessions.insert(session_id, file_ctx);
            }
            Some(_) => {} // agree; keep
            None => {
                sessions.insert(session_id, file_ctx);
            }
        }
    }

    if let Some(session) = session {
        return sessions.remove(session).ok_or_else(|| {
            CliError::usage(format!(
                "no parent message found for mid {mid:?} in session {session:?} (looked in the DB and {})",
                root.display()
            ))
        });
    }

    match sessions.len() {
        0 => Err(CliError::usage(format!(
            "no parent message found for mid {mid:?} (looked in the DB and {})",
            root.display()
        ))),
        1 => Ok(sessions.into_values().next().expect("len==1")),
        _ => {
            // ADR 001: a mid reused across sessions is ambiguous. Abort with no
            // write and require --session-id.
            let candidates = sessions.keys().cloned().collect::<Vec<_>>().join(", ");
            Err(CliError::usage(format!(
                "mid {mid:?} is ambiguous across {} sessions ({candidates}); pass --session-id <session> to disambiguate (ADR 001: a mid is unique only within a session)",
                sessions.len()
            )))
        }
    }
}

/// Per-session parent contexts for a mid from the DB (one per session_id that
/// has an audit record for the mid; the ORIGINAL send carries the routing).
fn load_parent_candidates_from_db(
    mid: &str,
    db: &std::path::Path,
) -> CliResult<std::collections::BTreeMap<String, ParentContext>> {
    let connection = crate::db::open_read_database(db)?;
    // P2b (determinism): pick the EARLIEST original-send row PER session by
    // (timestamp ASC, audit_id ASC), so source_agent/mode/workspace_id all come
    // from THAT one row — never a SQLite-arbitrary GROUP BY bare-column pick.
    // ROW_NUMBER() ranks the rows deterministically; rn=1 is the earliest.
    let mut statement = connection
        .prepare(
            "SELECT session_id, source_agent_id, mode, workspace_id FROM (
                 SELECT session_id, source_agent_id, mode, workspace_id,
                        ROW_NUMBER() OVER (
                            PARTITION BY session_id
                            ORDER BY timestamp ASC, audit_id ASC
                        ) AS rn
                 FROM audit_records WHERE mid = ?1
             ) WHERE rn = 1",
        )
        .map_err(|error| CliError::failure(format!("failed to query parent {mid}: {error}")))?;
    let rows = statement
        .query_map(rusqlite::params![mid], |row| {
            Ok((
                row.get::<_, String>(0)?,         // session_id
                row.get::<_, Option<String>>(1)?, // source_agent_id
                row.get::<_, Option<String>>(2)?, // mode
                row.get::<_, String>(3)?,         // workspace_id
            ))
        })
        .map_err(|error| CliError::failure(format!("failed to read parent {mid}: {error}")))?;
    let mut out = std::collections::BTreeMap::new();
    for row in rows {
        let (session_id, source_agent, mode, workspace_id) = row
            .map_err(|error| CliError::failure(format!("failed to read parent {mid}: {error}")))?;
        let source_agent = source_agent.ok_or_else(|| {
            CliError::failure(format!(
                "parent {mid} in session {session_id} has no source_agent in the DB; cannot infer the reply target"
            ))
        })?;
        out.insert(
            session_id.clone(),
            ParentContext {
                source_agent,
                session_id,
                mode,
                workspace_id,
            },
        );
    }
    Ok(out)
}

/// Per-session parent contexts for a mid from `<root>/sessions/*/audit.md`. The
/// ORIGINAL send (first block for the mid within a session file) carries the
/// routing. Scans EVERY session dir so a cross-session collision is detectable.
fn load_parent_candidates_from_file(
    mid: &str,
    root: &std::path::Path,
) -> CliResult<std::collections::BTreeMap<String, ParentContext>> {
    let mut out = std::collections::BTreeMap::new();
    let sessions = root.join("sessions");
    if !sessions.is_dir() {
        return Ok(out);
    }
    for entry in fs::read_dir(&sessions).map_err(|error| {
        CliError::failure(format!("failed to read {}: {error}", sessions.display()))
    })? {
        let entry = entry
            .map_err(|error| CliError::failure(format!("failed to read session dir: {error}")))?;
        let audit_path = entry.path().join("audit.md");
        if !audit_path.is_file() {
            continue;
        }
        let content = fs::read_to_string(&audit_path).map_err(|error| {
            CliError::failure(format!("failed to read {}: {error}", audit_path.display()))
        })?;
        for block in parse_audit_blocks_full(&content) {
            if block.get("mid").map(String::as_str) != Some(mid) {
                continue;
            }
            let source_agent = block.get("source_agent").cloned().ok_or_else(|| {
                CliError::failure(format!("parent {mid} record is missing source_agent"))
            })?;
            let session_id = block.get("session_id").cloned().ok_or_else(|| {
                CliError::failure(format!("parent {mid} record is missing session_id"))
            })?;
            let workspace_id = block.get("workspace_id").cloned().ok_or_else(|| {
                CliError::failure(format!("parent {mid} record is missing workspace_id"))
            })?;
            // The ORIGINAL send is the FIRST block for this (session, mid).
            out.entry(session_id.clone()).or_insert(ParentContext {
                source_agent,
                session_id,
                mode: block.get("mode").cloned(),
                workspace_id,
            });
        }
    }
    Ok(out)
}

/// Read a message body from `--body`, `--body-file <path|->`, or stdin (when not
/// a TTY). CRLF/CR normalize to LF (consistent with compose). A TTY with no body
/// fails clearly rather than hanging on an interactive read (ADR 040 D8 stdin).
fn read_body(body: Option<&str>, body_file: Option<&std::path::Path>) -> CliResult<String> {
    use std::io::Read;
    let raw = if let Some(body) = body {
        body.to_string()
    } else if let Some(path) = body_file {
        if path.as_os_str() == "-" {
            read_stdin_body()?
        } else {
            fs::read_to_string(path).map_err(|error| {
                CliError::failure(format!(
                    "failed to read body file {}: {error}",
                    path.display()
                ))
            })?
        }
    } else {
        // Default to stdin when it is piped; a TTY with no body is a usage error.
        if std::io::stdin().is_terminal() {
            return Err(CliError::usage(
                "no body: pass --body, --body-file <path>, or pipe the body on stdin",
            ));
        }
        let mut buffer = String::new();
        std::io::stdin()
            .read_to_string(&mut buffer)
            .map_err(|error| {
                CliError::failure(format!("failed to read body from stdin: {error}"))
            })?;
        buffer
    };
    Ok(raw.replace("\r\n", "\n").replace('\r', "\n"))
}

fn read_stdin_body() -> CliResult<String> {
    use std::io::Read;
    if std::io::stdin().is_terminal() {
        return Err(CliError::usage(
            "--body-file - expects the body on stdin, but stdin is a TTY",
        ));
    }
    let mut buffer = String::new();
    std::io::stdin()
        .read_to_string(&mut buffer)
        .map_err(|error| CliError::failure(format!("failed to read body from stdin: {error}")))?;
    Ok(buffer)
}

/// Shared `SendHerdrArgs` builder for `reply` and `send agent` (ADR 040 D1/D6).
/// Sets `from = "<me>:<my_pane>"`, `to = "<peer>:<peer_pane>"`, `pane =
/// <peer_pane>` so `send_herdr::prepare_audit` records the real transport
/// destination and the record is byte-identical to the longhand.
struct BuildSend<'a> {
    herdr_bin: String,
    me: &'a SelfContext,
    peer_agent: &'a str,
    peer_pane: &'a str,
    mid: Option<String>,
    message_type: String,
    re: Option<String>,
    r#ref: Option<String>,
    mode: Option<String>,
    session_id: String,
    body: String,
    command_origin: String,
    payload_redaction_policy: String,
    no_audit: bool,
    dry_run: bool,
    db: Option<std::path::PathBuf>,
    no_db: bool,
    root: std::path::PathBuf,
}

fn build_send_args(spec: BuildSend<'_>) -> CliResult<crate::send_herdr::SendHerdrArgs> {
    let mid = spec.mid.unwrap_or_else(crate::dashboard_write::mint_mid);
    let from = format!("{}:{}", spec.me.agent, spec.me.pane_id);
    let to = format!("{}:{}", spec.peer_agent, spec.peer_pane);
    let compose = crate::compose::ComposeArgs {
        profile: None,
        from: Some(from),
        to: Some(to),
        mid: Some(mid),
        message_type: Some(spec.message_type),
        shorthand: None,
        r#ref: spec.r#ref,
        re: spec.re,
        due: None,
        mode: spec.mode,
        transport: None,
        body: Some(spec.body),
        body_file: None,
        field: Vec::new(),
        var: Vec::new(),
    };
    Ok(crate::send_herdr::SendHerdrArgs {
        pane: spec.peer_pane.to_string(),
        dry_run: spec.dry_run,
        herdr_bin: spec.herdr_bin,
        session_id: Some(spec.session_id),
        no_audit: spec.no_audit,
        root: spec.root,
        command_origin: spec.command_origin,
        payload_redaction_policy: spec.payload_redaction_policy,
        sensitive_category: None,
        db: spec.db,
        no_db: spec.no_db,
        retain_custody: false,
        custody_key_file: None,
        compose,
    })
}

// ---------------------------------------------------------------------------
// `zynk send agent <name>` (ADR 040): a fresh, non-reply audited send to a named
// LIVE agent. Resolves name -> pane live (D2; `--to-pane`/`--workspace`
// disambiguate), mints a mid if omitted, composes `send_herdr::run`.
// ---------------------------------------------------------------------------

#[derive(Debug, Args)]
pub struct SendAgentArgs {
    #[arg(help = "Target agent name; resolved to exactly one LIVE pane (ADR 040 D2).")]
    pub agent: String,
    #[arg(
        long,
        help = "Pin the exact target pane id (verified to be occupied by <agent>); disambiguates duplicates."
    )]
    pub to_pane: Option<String>,
    #[arg(
        long,
        help = "Restrict resolution to this workspace (id, label, or number); disambiguates cross-workspace duplicates."
    )]
    pub workspace: Option<String>,
    #[arg(long = "type", help = "Message type (required; never inferred).")]
    pub message_type: Option<String>,
    #[arg(long, help = "Session id for the audited send (required).")]
    pub session_id: Option<String>,
    #[arg(long, help = "Artifact reference (optional).")]
    pub r#ref: Option<String>,
    #[arg(
        long,
        help = "Collaboration mode (optional; the message default applies otherwise)."
    )]
    pub mode: Option<String>,
    #[arg(
        long,
        help = "Message body inline; otherwise --body-file, otherwise stdin."
    )]
    pub body: Option<String>,
    #[arg(
        long,
        help = "Body file ('-' reads stdin); otherwise stdin when not a TTY."
    )]
    pub body_file: Option<std::path::PathBuf>,
    #[arg(long, help = "Message id; auto-minted (op-<hex>) when omitted.")]
    pub mid: Option<String>,
    #[arg(
        long,
        default_value = "outputs",
        help = "Audit artifact root for the send."
    )]
    pub root: std::path::PathBuf,
    #[arg(
        long,
        help = "Live DB path for the projection; defaults to cwd .zynk/zynk.db."
    )]
    pub db: Option<std::path::PathBuf>,
    #[arg(long, help = "Force file-only (skip the DB projection).")]
    pub no_db: bool,
    #[arg(
        long,
        help = "Opt out of the audited send (send only; no audit/corpus record)."
    )]
    pub no_audit: bool,
    #[arg(
        long,
        default_value = "agent",
        value_parser = ["agent", "operator", "helper-tool", "unknown"],
        help = "Who originated this send, for the audit record."
    )]
    pub command_origin: String,
    #[arg(
        long,
        default_value = "full",
        help = "Redaction policy for the audited payload."
    )]
    pub payload_redaction_policy: String,
    #[arg(
        long,
        help = "Preview the inferred routing + composed message without sending; writes no audit/outputs (--type/--session-id still required)."
    )]
    pub dry_run: bool,
    #[arg(long, default_value = "herdr", help = "herdr executable path.")]
    pub herdr_bin: String,
}

pub fn run_send_agent(args: SendAgentArgs) -> CliResult<()> {
    // Judgment fields explicit (ADR 040 D3): --type + --session-id + body required.
    let message_type = args.message_type.clone().ok_or_else(|| {
        CliError::usage("send agent requires --type (the type is never inferred)")
    })?;
    let session_id = args.session_id.clone().ok_or_else(|| {
        CliError::usage("send agent requires --session-id for the audited record")
    })?;

    // ADR 040 D2: resolve BOTH sides live, BEFORE any write.
    let me = resolve_self(&args.herdr_bin)?;
    let inventory = load_inventory(&args.herdr_bin)?;
    let (peer_agent, peer_pane) = resolve_send_target(
        &inventory,
        &args.agent,
        args.to_pane.as_deref(),
        args.workspace.as_deref(),
    )?;

    let body = read_body(args.body.as_deref(), args.body_file.as_deref())?;

    let send_args = build_send_args(BuildSend {
        herdr_bin: args.herdr_bin,
        me: &me,
        peer_agent: &peer_agent,
        peer_pane: &peer_pane,
        mid: args.mid.clone(),
        message_type,
        re: None,
        r#ref: args.r#ref.clone(),
        mode: args.mode.clone(),
        session_id,
        body,
        command_origin: args.command_origin,
        payload_redaction_policy: args.payload_redaction_policy,
        no_audit: args.no_audit,
        dry_run: args.dry_run,
        db: args.db,
        no_db: args.no_db,
        root: args.root,
    })?;
    crate::send_herdr::run(send_args)
}

/// Resolve a `send agent` target. `--to-pane` pins an exact pane (verified to be
/// occupied by `agent` — ADR 040 D2 agent-mismatch aborts); otherwise resolve by
/// name (optionally scoped to `--workspace`). A cross-workspace duplicate without
/// `--to-pane`/`--workspace` is ambiguous (contrast `reply`, which is
/// thread-workspace-scoped).
fn resolve_send_target(
    inventory: &Inventory,
    agent: &str,
    to_pane: Option<&str>,
    workspace: Option<&str>,
) -> CliResult<(String, String)> {
    if let Some(pane_id) = to_pane {
        let pane = all_panes(inventory)
            .find(|pane| pane.pane_id == pane_id)
            .ok_or_else(|| {
                CliError::usage(format!("--to-pane {pane_id} is not a live Herdr pane"))
            })?;
        match pane.agent.as_deref() {
            Some(occupant) if occupant == agent => Ok((agent.to_string(), pane_id.to_string())),
            Some(occupant) => Err(CliError::usage(format!(
                "--to-pane {pane_id} is occupied by {occupant}, not {agent} (ADR 040 D2)"
            ))),
            None => Err(CliError::usage(format!(
                "--to-pane {pane_id} has no agent; cannot target {agent}"
            ))),
        }
    } else {
        resolve_target_in(inventory, agent, workspace)
    }
}

// ---------------------------------------------------------------------------
// `zynk inbox` + `zynk thread <mid>` (ADR 040 D5): strictly read-only views over
// the corpus. Read an existing DB if present (never auto-create — D5), else
// parse `outputs/sessions/*/audit.md`. Honor redaction in excerpts.
// ---------------------------------------------------------------------------

#[derive(Debug, Args)]
pub struct InboxArgs {
    #[arg(
        long,
        help = "Show messages addressed to this agent; defaults to the live self (HERDR_PANE_ID)."
    )]
    pub me: Option<String>,
    #[arg(long, help = "Restrict to one session id.")]
    pub session: Option<String>,
    #[arg(
        long,
        help = "BEST-EFFORT HEURISTIC: my request-* messages with no live re= reply yet (never an authoritative answered state)."
    )]
    pub unanswered: bool,
    #[arg(
        long,
        default_value = "outputs",
        help = "Audit artifact root for the file-only view."
    )]
    pub root: std::path::PathBuf,
    #[arg(
        long,
        help = "DB path to read; defaults to cwd .zynk/zynk.db if it exists (read-only)."
    )]
    pub db: Option<std::path::PathBuf>,
    #[arg(long, help = "Force the file-only view (ignore any DB).")]
    pub no_db: bool,
    #[arg(long, default_value = "table", value_enum, help = "Output format.")]
    pub format: crate::herdr_orchestration::OutputFormat,
    #[arg(
        long,
        default_value = "herdr",
        help = "herdr executable path (only for self resolution)."
    )]
    pub herdr_bin: String,
}

#[derive(Debug, Args)]
pub struct ThreadArgs {
    #[arg(
        help = "Any message in the thread; shows the full connected re= component (its ancestors up to the root plus the descendants), oldest-first."
    )]
    pub mid: String,
    #[arg(
        long,
        help = "Disambiguate when the mid is reused across sessions (ADR 001): scope the thread to this session. Required when a cross-session mid collision is detected."
    )]
    pub session_id: Option<String>,
    #[arg(
        long,
        default_value = "outputs",
        help = "Audit artifact root for the file-only view."
    )]
    pub root: std::path::PathBuf,
    #[arg(
        long,
        help = "DB path to read; defaults to cwd .zynk/zynk.db if it exists (read-only)."
    )]
    pub db: Option<std::path::PathBuf>,
    #[arg(long, help = "Force the file-only view (ignore any DB).")]
    pub no_db: bool,
    #[arg(long, default_value = "table", value_enum, help = "Output format.")]
    pub format: crate::herdr_orchestration::OutputFormat,
}

/// One corpus message row for the read-only views. `excerpt` already honors
/// redaction (None for hash-only).
#[derive(Debug, Clone, serde::Serialize)]
pub(crate) struct MessageRow {
    pub mid: String,
    pub session_id: String,
    pub message_type: String,
    pub source_agent: Option<String>,
    pub target_agent: Option<String>,
    pub r#ref: Option<String>,
    pub re: Option<String>,
    pub timestamp: String,
    pub redaction_policy: String,
    pub excerpt: Option<String>,
}

pub fn run_inbox(args: InboxArgs) -> CliResult<()> {
    use crate::herdr_orchestration::OutputFormat;
    // "me": explicit --me wins; else resolve from live Herdr (read-only).
    let me = match args.me.clone() {
        Some(me) => me,
        None => resolve_self(&args.herdr_bin)?.agent,
    };

    let db = resolve_db_path(args.db.as_deref(), args.no_db);
    let mut rows = load_messages(db.as_deref(), &args.root, args.session.as_deref())?;
    rows.retain(|row| row.target_agent.as_deref() == Some(me.as_str()));
    // Newest first.
    rows.sort_by(|a, b| b.timestamp.cmp(&a.timestamp).then(b.mid.cmp(&a.mid)));

    // P4 (ADR 001): "answered" is keyed by (session_id, re_mid) — a reply only
    // answers a request WITHIN ITS OWN SESSION, since a mid is unique only within
    // a session. A same-mid reply in another session must NOT mark this one
    // answered.
    let answered: std::collections::HashSet<(String, String)> = if args.unanswered {
        let all = load_messages(db.as_deref(), &args.root, None)?;
        all.iter()
            .filter_map(|row| row.re.clone().map(|re| (row.session_id.clone(), re)))
            .collect()
    } else {
        std::collections::HashSet::new()
    };
    if args.unanswered {
        rows.retain(|row| {
            row.message_type.starts_with("request-")
                && !answered.contains(&(row.session_id.clone(), row.mid.clone()))
        });
    }

    match args.format {
        OutputFormat::Json => print_rows_json(&rows)?,
        OutputFormat::Table => {
            if args.unanswered {
                println!("# inbox --unanswered is a BEST-EFFORT HEURISTIC over the re= chain (not an authoritative answered state)");
            }
            print_rows_table(&rows, &format!("inbox for {me}"));
        }
    }
    Ok(())
}

pub fn run_thread(args: ThreadArgs) -> CliResult<()> {
    use crate::herdr_orchestration::OutputFormat;
    let db = resolve_db_path(args.db.as_deref(), args.no_db);
    let all = load_messages(db.as_deref(), &args.root, None)?;

    // P4 (ADR 001): a `mid` is unique only within a session, so resolve the start
    // SESSION first. The distinct sessions that hold the start mid:
    let start_sessions: std::collections::BTreeSet<String> = all
        .iter()
        .filter(|row| row.mid == args.mid)
        .map(|row| row.session_id.clone())
        .collect();
    let session = match (args.session_id.as_deref(), start_sessions.len()) {
        // Explicit scope: it must actually contain the mid.
        (Some(session), _) => {
            if !start_sessions.contains(session) {
                return Err(CliError::usage(format!(
                    "no message found for mid {:?} in session {session:?} (looked in the DB and {})",
                    args.mid,
                    args.root.display()
                )));
            }
            session.to_string()
        }
        (None, 0) => {
            return Err(CliError::usage(format!(
                "no message found for mid {:?} in the DB or {}",
                args.mid,
                args.root.display()
            )));
        }
        (None, 1) => start_sessions.iter().next().expect("len==1").clone(),
        // Ambiguous across sessions: fail loud BEFORE rendering (mirror reply P3).
        (None, _) => {
            let candidates = start_sessions
                .iter()
                .cloned()
                .collect::<Vec<_>>()
                .join(", ");
            return Err(CliError::usage(format!(
                "mid {:?} is ambiguous across {} sessions ({candidates}); pass --session-id <session> to disambiguate (ADR 001: a mid is unique only within a session)",
                args.mid,
                start_sessions.len()
            )));
        }
    };

    // Restrict to the resolved session, then compute the FULL connected re=
    // component (ancestors + descendants) over (session, mid) node identity — a
    // re= edge only connects messages WITHIN the same session (P4). Pointed at any
    // message in the thread, this recovers the whole thread.
    let scoped: Vec<MessageRow> = all
        .into_iter()
        .filter(|row| row.session_id == session)
        .collect();
    let members = connected_re_component(&scoped, &session, &args.mid);

    let mut rows: Vec<MessageRow> = scoped
        .iter()
        .filter(|row| members.contains(&(row.session_id.clone(), row.mid.clone())))
        .cloned()
        .collect();
    if rows.is_empty() {
        return Err(CliError::usage(format!(
            "no message found for mid {:?} in the DB or {}",
            args.mid,
            args.root.display()
        )));
    }
    // Oldest-first so the root leads and the chain reads top-down. Primary key is
    // the timestamp; ties (same-second sends are common) break by re= DEPTH so a
    // parent always precedes its reply even when both share a timestamp, then by
    // mid for full determinism.
    let depth = re_depth(&scoped);
    rows.sort_by(|a, b| {
        let ka = (a.session_id.clone(), a.mid.clone());
        let kb = (b.session_id.clone(), b.mid.clone());
        a.timestamp
            .cmp(&b.timestamp)
            .then(depth.get(&ka).cmp(&depth.get(&kb)))
            .then(a.mid.cmp(&b.mid))
    });

    match args.format {
        OutputFormat::Json => print_rows_json(&rows)?,
        OutputFormat::Table => print_rows_table(&rows, &format!("thread {}", args.mid)),
    }
    Ok(())
}

/// The set of `(session_id, mid)` nodes in the connected `re=` component
/// containing `(start_session, start_mid)`. A `re=` is an undirected edge between
/// a message and the mid it replies to WITHIN THE SAME SESSION (ADR 001: a mid is
/// unique only within a session), so the BFS reaches ancestors (a message's own
/// `re`) and descendants (messages whose `re` points back) but never crosses a
/// session boundary. `start` is always included even with no edges.
fn connected_re_component(
    all: &[MessageRow],
    start_session: &str,
    start_mid: &str,
) -> std::collections::HashSet<(String, String)> {
    use std::collections::{HashMap, HashSet, VecDeque};
    type Node = (String, String); // (session_id, mid)
                                  // child node -> parent node (its own re, in the same session), and the reverse.
    let mut parent_of: HashMap<Node, Node> = HashMap::new();
    let mut children_of: HashMap<Node, Vec<Node>> = HashMap::new();
    for row in all {
        if let Some(re) = row.re.as_deref() {
            let child = (row.session_id.clone(), row.mid.clone());
            let parent = (row.session_id.clone(), re.to_string());
            parent_of.insert(child.clone(), parent.clone());
            children_of.entry(parent).or_default().push(child);
        }
    }
    let start = (start_session.to_string(), start_mid.to_string());
    let mut seen: HashSet<Node> = HashSet::new();
    let mut queue: VecDeque<Node> = VecDeque::new();
    seen.insert(start.clone());
    queue.push_back(start);
    while let Some(node) = queue.pop_front() {
        if let Some(parent) = parent_of.get(&node) {
            if seen.insert(parent.clone()) {
                queue.push_back(parent.clone());
            }
        }
        if let Some(children) = children_of.get(&node) {
            for child in children {
                if seen.insert(child.clone()) {
                    queue.push_back(child.clone());
                }
            }
        }
    }
    seen
}

/// re= depth of each `(session_id, mid)`: the number of `re=` hops back to a
/// message whose parent is not present (a thread root has depth 0). Edges stay
/// WITHIN a session (P4). Used as the tie-break so a parent precedes its reply
/// when timestamps collide. A `re=` cycle (which the protocol does not produce)
/// is depth-capped by the row count so this always terminates.
fn re_depth(all: &[MessageRow]) -> std::collections::HashMap<(String, String), usize> {
    use std::collections::{HashMap, HashSet};
    type Node = (String, String);
    let parent_of: HashMap<Node, Node> = all
        .iter()
        .filter_map(|row| {
            row.re.as_deref().map(|re| {
                (
                    (row.session_id.clone(), row.mid.clone()),
                    (row.session_id.clone(), re.to_string()),
                )
            })
        })
        .collect();
    let present: HashSet<Node> = all
        .iter()
        .map(|row| (row.session_id.clone(), row.mid.clone()))
        .collect();
    let mut depths: HashMap<Node, usize> = HashMap::new();
    let cap = all.len();
    for row in all {
        let mut depth = 0usize;
        let mut cursor = (row.session_id.clone(), row.mid.clone());
        while let Some(parent) = parent_of.get(&cursor) {
            // Stop at a parent not itself a known message (the root's re points
            // outside the loaded set) — that message is the local root.
            if !present.contains(parent) || depth >= cap {
                break;
            }
            depth += 1;
            cursor = parent.clone();
        }
        depths.insert((row.session_id.clone(), row.mid.clone()), depth);
    }
    depths
}

fn print_rows_table(rows: &[MessageRow], title: &str) {
    println!("# {title} ({} message(s))", rows.len());
    println!(
        "{:<20} {:<16} {:<18} {:<14} {:<14} EXCERPT",
        "MID", "TYPE", "FROM->TO", "REF", "RE"
    );
    for row in rows {
        let from_to = format!(
            "{}->{}",
            row.source_agent.as_deref().unwrap_or("-"),
            row.target_agent.as_deref().unwrap_or("-")
        );
        let excerpt = match (&row.excerpt, row.redaction_policy.as_str()) {
            (_, "hash-only") => "[hash-only]".to_string(),
            (Some(text), _) => truncate_excerpt(text),
            (None, _) => "-".to_string(),
        };
        println!(
            "{:<20} {:<16} {:<18} {:<14} {:<14} {}",
            row.mid,
            row.message_type,
            from_to,
            row.r#ref.as_deref().unwrap_or("-"),
            row.re.as_deref().unwrap_or("-"),
            excerpt
        );
    }
}

fn truncate_excerpt(text: &str) -> String {
    let single = text.replace('\n', " ");
    if single.chars().count() > 60 {
        let head: String = single.chars().take(57).collect();
        format!("{head}...")
    } else {
        single
    }
}

fn print_rows_json(rows: &[MessageRow]) -> CliResult<()> {
    println!(
        "{}",
        serde_json::to_string_pretty(rows)
            .map_err(|error| CliError::failure(format!("failed to render JSON: {error}")))?
    );
    Ok(())
}

/// Load corpus messages, DB-fast-path but FILE-AUTHORITATIVE (ADR 040 D7 / P1).
/// NEVER auto-creates a DB (ADR 040 D5): the DB is read only when it already
/// exists. `session` filters to one session when `Some`.
///
/// When a DB exists (and not `--no-db`), the `outputs/` files are ALSO scanned
/// and merged by `(session_id, mid)`: a file row WINS over a DB row for the same
/// key (the file is the conflict authority for every displayed/threading field),
/// and a file-only row is never dropped just because a stale DB snapshot omits
/// it. DB rows only fill in keys the files do not carry. With no DB / `--no-db`,
/// the view is files-only as before.
pub(crate) fn load_messages(
    db: Option<&std::path::Path>,
    root: &std::path::Path,
    session: Option<&str>,
) -> CliResult<Vec<MessageRow>> {
    let file_rows = load_messages_from_files(root, session)?;
    let Some(path) = db.filter(|path| path.exists()) else {
        return Ok(file_rows);
    };
    let db_rows = load_messages_from_db(path, session)?;
    Ok(merge_file_authoritative(db_rows, file_rows))
}

/// Merge DB + file rows by `(session_id, mid)`. The FILE row is authoritative
/// (ADR 040 D7): start from every file row, then add DB rows only for keys the
/// files do not already contain. Preserves a stable order (DB-only rows appended
/// after the file rows; callers re-sort by timestamp).
fn merge_file_authoritative(
    db_rows: Vec<MessageRow>,
    file_rows: Vec<MessageRow>,
) -> Vec<MessageRow> {
    use std::collections::HashSet;
    let file_keys: HashSet<(String, String)> = file_rows
        .iter()
        .map(|row| (row.session_id.clone(), row.mid.clone()))
        .collect();
    let mut merged = file_rows;
    for row in db_rows {
        let key = (row.session_id.clone(), row.mid.clone());
        if !file_keys.contains(&key) {
            merged.push(row);
        }
    }
    merged
}

fn load_messages_from_db(
    db: &std::path::Path,
    session: Option<&str>,
) -> CliResult<Vec<MessageRow>> {
    let connection = crate::db::open_read_database(db)?;
    let mut statement = connection
        .prepare(
            "SELECT m.mid, m.session_id, m.message_type, m.source_agent_id, m.target_agent_id,
                    m.ref, a.re, m.timestamp, m.payload_redaction_policy,
                    CASE WHEN m.payload_redaction_policy = 'hash-only'
                         THEN NULL ELSE m.payload_excerpt END
             FROM messages AS m
             LEFT JOIN audit_records AS a ON a.audit_id = m.latest_audit_id
             ORDER BY m.timestamp, m.mid",
        )
        .map_err(|error| CliError::failure(format!("failed to query messages: {error}")))?;
    let rows = statement
        .query_map([], |row| {
            Ok(MessageRow {
                mid: row.get(0)?,
                session_id: row.get(1)?,
                message_type: row.get(2)?,
                source_agent: row.get(3)?,
                target_agent: row.get(4)?,
                r#ref: row.get(5)?,
                re: row.get(6)?,
                timestamp: row.get(7)?,
                redaction_policy: row.get(8)?,
                excerpt: row.get(9)?,
            })
        })
        .map_err(|error| CliError::failure(format!("failed to read messages: {error}")))?
        .collect::<Result<Vec<_>, _>>()
        .map_err(|error| CliError::failure(format!("failed to read messages: {error}")))?;
    Ok(filter_session(rows, session))
}

fn load_messages_from_files(
    root: &std::path::Path,
    session: Option<&str>,
) -> CliResult<Vec<MessageRow>> {
    let sessions = root.join("sessions");
    if !sessions.is_dir() {
        return Ok(Vec::new());
    }
    let mut rows = Vec::new();
    // Collapse to one row per (session_id, mid): a mid may have multiple appended
    // audit records (e.g. a later `observed` correction); the FIRST block is the
    // original send carrying the stable routing/threading fields (consistent with
    // load_parent_from_file). This also makes the (session_id, mid) merge key
    // single-valued on the file side.
    let mut seen: std::collections::HashSet<(String, String)> = std::collections::HashSet::new();
    for entry in fs::read_dir(&sessions).map_err(|error| {
        CliError::failure(format!("failed to read {}: {error}", sessions.display()))
    })? {
        let entry = entry
            .map_err(|error| CliError::failure(format!("failed to read session dir: {error}")))?;
        let audit_path = entry.path().join("audit.md");
        if !audit_path.is_file() {
            continue;
        }
        let content = fs::read_to_string(&audit_path).map_err(|error| {
            CliError::failure(format!("failed to read {}: {error}", audit_path.display()))
        })?;
        for block in parse_audit_blocks_full(&content) {
            let Some(mid) = block.get("mid").cloned() else {
                continue;
            };
            let session_id = block.get("session_id").cloned().unwrap_or_default();
            if !seen.insert((session_id.clone(), mid.clone())) {
                continue; // a later appended record for the same (session, mid)
            }
            let redaction_policy = block
                .get("payload_redaction_policy")
                .cloned()
                .unwrap_or_else(|| "hash-only".to_string());
            let excerpt = if redaction_policy == "hash-only" {
                None
            } else {
                block.get("payload_excerpt").cloned()
            };
            rows.push(MessageRow {
                mid,
                session_id,
                message_type: block.get("type").cloned().unwrap_or_default(),
                source_agent: block.get("source_agent").cloned(),
                target_agent: block.get("target_agent").cloned(),
                r#ref: block.get("ref").cloned(),
                re: block.get("re").cloned(),
                timestamp: block.get("timestamp").cloned().unwrap_or_default(),
                redaction_policy,
                excerpt,
            });
        }
    }
    Ok(filter_session(rows, session))
}

fn filter_session(rows: Vec<MessageRow>, session: Option<&str>) -> Vec<MessageRow> {
    match session {
        Some(session) => rows
            .into_iter()
            .filter(|row| row.session_id == session)
            .collect(),
        None => rows,
    }
}

/// Like `parse_audit_blocks` but captures the terminal multi-line
/// `payload_excerpt` field (for the excerpt column). Mirrors the writer's
/// terminal-field discipline (src/db.rs parse_fenced_key_value_blocks).
fn parse_audit_blocks_full(content: &str) -> Vec<std::collections::BTreeMap<String, String>> {
    let mut blocks = Vec::new();
    let mut current: Option<std::collections::BTreeMap<String, String>> = None;
    let mut payload_capture: Option<Vec<String>> = None;
    for raw in content.lines() {
        if payload_capture.is_some() {
            if raw == "```" {
                if let (Some(values), Some(lines)) = (current.as_mut(), payload_capture.take()) {
                    values.insert("payload_excerpt".to_string(), lines.join("\n"));
                }
                if let Some(values) = current.take() {
                    blocks.push(values);
                }
                continue;
            }
            if let Some(lines) = payload_capture.as_mut() {
                lines.push(raw.to_string());
            }
            continue;
        }
        let line = raw.trim();
        if line == "```text" {
            current = Some(std::collections::BTreeMap::new());
            continue;
        }
        if line == "```" {
            if let Some(values) = current.take() {
                blocks.push(values);
            }
            continue;
        }
        if current.is_some() {
            if let Some((key, value)) = line.split_once('=') {
                if key == "payload_excerpt" {
                    payload_capture = Some(vec![value.to_string()]);
                } else if let Some(values) = current.as_mut() {
                    values
                        .entry(key.to_string())
                        .or_insert_with(|| value.to_string());
                }
            }
        }
    }
    blocks
}

// ---------------------------------------------------------------------------
// `zynk doctor` (ADR 040 D5/D8): a strictly read-only diagnostic. Every check
// degrades to a printed finding — herdr-unreachable is a finding, not a crash —
// and NOTHING is written (no `.zynk/`, no `outputs/`, no DB).
// ---------------------------------------------------------------------------

#[derive(Debug, Args)]
pub struct DoctorArgs {
    #[arg(
        long,
        default_value = "herdr",
        help = "herdr executable path to probe."
    )]
    pub herdr_bin: String,
    #[arg(
        long,
        help = "DB path to inspect read-only (default cwd .zynk/zynk.db if it exists)."
    )]
    pub db: Option<std::path::PathBuf>,
    #[arg(
        long,
        default_value = "outputs",
        help = "Audit artifact root to inspect."
    )]
    pub root: std::path::PathBuf,
    #[arg(long, default_value = "table", value_enum, help = "Output format.")]
    pub format: crate::herdr_orchestration::OutputFormat,
}

#[derive(Debug, Clone, serde::Serialize)]
struct Finding {
    level: &'static str,
    check: &'static str,
    detail: String,
}

pub fn run_doctor(args: DoctorArgs) -> CliResult<()> {
    use crate::herdr_orchestration::OutputFormat;
    let mut findings: Vec<Finding> = Vec::new();

    // 1. Installed version.
    findings.push(Finding {
        level: "info",
        check: "version",
        detail: format!("zynk {}", env!("CARGO_PKG_VERSION")),
    });

    // 2. Herdr reachable + 3. self pane resolvable + 4. ambiguous panes — each
    // degrades to a finding (never a crash).
    match load_inventory(&args.herdr_bin) {
        Ok(inventory) => {
            findings.push(Finding {
                level: "ok",
                check: "herdr",
                detail: format!(
                    "reachable ({} workspace(s) visible)",
                    inventory.workspaces.len()
                ),
            });
            match resolve_self(&args.herdr_bin) {
                Ok(me) => findings.push(Finding {
                    level: "ok",
                    check: "self-pane",
                    detail: format!(
                        "{} at {} (workspace {})",
                        me.agent, me.pane_id, me.workspace_id
                    ),
                }),
                Err(error) => findings.push(Finding {
                    level: "warn",
                    check: "self-pane",
                    detail: format!("cannot resolve self: {}", error.message()),
                }),
            }
            for (agent, count) in ambiguous_agents(&inventory) {
                findings.push(Finding {
                    level: "warn",
                    check: "ambiguous-agent",
                    detail: format!(
                        "agent {agent} occupies {count} live panes — name alone is ambiguous; use --workspace/--to-pane"
                    ),
                });
            }
        }
        Err(error) => findings.push(Finding {
            level: "warn",
            check: "herdr",
            detail: format!(
                "not reachable: {} (send/whoami need a live herdr)",
                error.message()
            ),
        }),
    }

    // 5. DB presence / projection gap (only inspect an EXISTING DB — never create).
    let db = resolve_db_path(args.db.as_deref(), false);
    match db {
        Some(path) if path.exists() => match doctor_projection_gap(&path) {
            Ok(0) => findings.push(Finding {
                level: "ok",
                check: "db",
                detail: format!("{} present; no obvious projection gap", path.display()),
            }),
            Ok(gap) => findings.push(Finding {
                level: "warn",
                check: "db",
                detail: format!(
                    "{}: {gap} message(s) with no latest_audit_id (run `zynk db import outputs` to reconcile)",
                    path.display()
                ),
            }),
            Err(error) => findings.push(Finding {
                level: "warn",
                check: "db",
                detail: format!("could not inspect {}: {}", path.display(), error.message()),
            }),
        },
        _ => findings.push(Finding {
            level: "info",
            check: "db",
            detail: "no .zynk/zynk.db in cwd (file-only mode; status/audit/send auto-create it)".to_string(),
        }),
    }

    // 6. Skill-mirror presence (a soft hint; absence is informational).
    findings.push(skill_mirror_finding());

    // 7. Common send blockers (a static hint surface).
    findings.push(Finding {
        level: "info",
        check: "send-hints",
        detail: "addresses are agent:pane-id; reply/send-agent resolve panes live, so a stale pane aborts loudly rather than misdelivering".to_string(),
    });

    match args.format {
        OutputFormat::Json => {
            println!(
                "{}",
                serde_json::to_string_pretty(&findings).map_err(|error| CliError::failure(
                    format!("failed to render doctor JSON: {error}")
                ))?
            );
        }
        OutputFormat::Table => {
            println!("{:<6} {:<18} DETAIL", "LEVEL", "CHECK");
            for finding in &findings {
                println!(
                    "{:<6} {:<18} {}",
                    finding.level, finding.check, finding.detail
                );
            }
        }
    }
    Ok(())
}

fn ambiguous_agents(inventory: &Inventory) -> Vec<(String, usize)> {
    use std::collections::BTreeMap;
    let mut counts: BTreeMap<String, usize> = BTreeMap::new();
    for pane in all_panes(inventory) {
        if let Some(agent) = pane.agent.as_deref() {
            *counts.entry(agent.to_string()).or_insert(0) += 1;
        }
    }
    counts.into_iter().filter(|(_, count)| *count > 1).collect()
}

/// Count messages with no proof linkage (latest_audit_id IS NULL) — a coarse
/// projection-gap signal. Read-only.
fn doctor_projection_gap(db: &std::path::Path) -> CliResult<i64> {
    let connection = crate::db::open_read_database(db)?;
    connection
        .query_row(
            "SELECT COUNT(*) FROM messages WHERE latest_audit_id IS NULL",
            [],
            |row| row.get(0),
        )
        .map_err(|error| CliError::failure(format!("failed to inspect messages: {error}")))
}

/// Best-effort check for a mirrored zynk skill (informational only). Looks for a
/// `skills/zynk` dir under cwd or `$HOME/.claude`.
fn skill_mirror_finding() -> Finding {
    let mut candidates: Vec<std::path::PathBuf> =
        vec![std::path::PathBuf::from("skills/zynk/SKILL.md")];
    if let Ok(home) = std::env::var("HOME") {
        candidates.push(std::path::Path::new(&home).join(".claude/skills/zynk/SKILL.md"));
    }
    if let Some(found) = candidates.iter().find(|path| path.exists()) {
        Finding {
            level: "ok",
            check: "skill-mirror",
            detail: format!("zynk skill present at {}", found.display()),
        }
    } else {
        Finding {
            level: "info",
            check: "skill-mirror",
            detail: "no zynk skill found under ./skills or $HOME/.claude/skills (optional)"
                .to_string(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::herdr_orchestration::{Inventory, PaneView, TabView, WorkspaceView};

    fn pane(id: &str, workspace: &str, agent: &str) -> PaneView {
        PaneView {
            pane_id: id.to_string(),
            workspace_id: workspace.to_string(),
            tab_id: format!("{workspace}:1"),
            agent: Some(agent.to_string()),
            agent_status: "idle".to_string(),
            label: None,
            cwd: None,
            focused: false,
        }
    }

    /// Build a single-workspace `WorkspaceView` (label/number derived from a
    /// small fixed map) holding `panes`.
    fn ws(workspace_id: &str, label: &str, number: i64, panes: Vec<PaneView>) -> WorkspaceView {
        WorkspaceView {
            workspace_id: workspace_id.to_string(),
            label: Some(label.to_string()),
            number: Some(number),
            focused: false,
            tabs: vec![TabView {
                tab_id: format!("{workspace_id}:1"),
                workspace_id: workspace_id.to_string(),
                label: None,
                number: Some(1),
                focused: false,
                panes,
            }],
        }
    }

    fn inventory(workspaces: Vec<WorkspaceView>) -> Inventory {
        Inventory { workspaces }
    }

    #[test]
    fn resolve_target_exactly_one_pane_ok() {
        let inv = inventory(vec![ws(
            "w1",
            "smscode",
            1,
            vec![pane("w1-1", "w1", "codex"), pane("w1-2", "w1", "claude")],
        )]);
        let (agent, pane_id) = resolve_target_in(&inv, "codex", None).unwrap();
        assert_eq!(agent, "codex");
        assert_eq!(pane_id, "w1-1");
    }

    #[test]
    fn resolve_target_zero_panes_errors_no_live_pane() {
        let inv = inventory(vec![ws(
            "w1",
            "smscode",
            1,
            vec![pane("w1-1", "w1", "claude")],
        )]);
        let err = resolve_target_in(&inv, "codex", None).unwrap_err();
        assert!(
            err.message().contains("no live pane"),
            "expected no-live-pane error, got: {}",
            err.message()
        );
    }

    #[test]
    fn resolve_target_two_cross_workspace_without_scope_lists_candidates() {
        let inv = inventory(vec![
            ws("w1", "smscode", 1, vec![pane("w1-1", "w1", "codex")]),
            ws("w2", "infra", 2, vec![pane("w2-1", "w2", "codex")]),
        ]);
        let err = resolve_target_in(&inv, "codex", None).unwrap_err();
        let msg = err.message();
        assert!(
            msg.contains("ambiguous"),
            "expected ambiguity error, got: {msg}"
        );
        assert!(
            msg.contains("w1:w1-1"),
            "should list candidate w1:w1-1, got: {msg}"
        );
        assert!(
            msg.contains("w2:w2-1"),
            "should list candidate w2:w2-1, got: {msg}"
        );
    }

    #[test]
    fn resolve_target_two_panes_with_workspace_scope_narrows_to_one() {
        let inv = inventory(vec![
            ws("w1", "smscode", 1, vec![pane("w1-1", "w1", "codex")]),
            ws("w2", "infra", 2, vec![pane("w2-1", "w2", "codex")]),
        ]);
        // Scope by id, by label, and by number — all narrow to the single pane.
        assert_eq!(
            resolve_target_in(&inv, "codex", Some("w2")).unwrap().1,
            "w2-1"
        );
        assert_eq!(
            resolve_target_in(&inv, "codex", Some("infra")).unwrap().1,
            "w2-1"
        );
        assert_eq!(
            resolve_target_in(&inv, "codex", Some("1")).unwrap().1,
            "w1-1"
        );
    }
}