dbmd-cli 0.13.2

The `dbmd` command-line tool for db.md, the open standard for databases in plain files. A thin wrapper over dbmd-core: validate, search, query, graph, write, index, and log over a db.md store. Zero AI dependencies.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
//! The complete `dbmd` command tree (clap derive).
//!
//! This file **locks the command surface**: every subcommand, its flags, and
//! its nested subcommands are declared here so the subcommand-body agents can
//! fill `cmd/<name>.rs` in parallel without ever editing this file or
//! `main.rs`. The dispatch in `main.rs` matches exhaustively on
//! [`Command`]; adding/removing a variant is the one change that touches both.
//!
//! Conventions enforced here (agent-primary ergonomics, SPEC.md § Tooling):
//!   - A global `--json` flag on the top-level command, inherited by all.
//!   - A global `--color <auto|always|never>` (default `auto` ⇒ off; pipe-safe).
//!   - Rich per-subcommand help via `///` doc comments (clap renders them).
//!   - No interactive prompts anywhere — flags only.
//!
//! Argument *shapes* are locked to match SPEC.md / TOOLS.md and the plan
//! (Block 2 + Block 5). The parsed-arg structs are the contract each
//! `cmd/<name>.rs` body reads from.

use clap::{ArgGroup, Args, Parser, Subcommand};

use crate::context::ColorChoice;

/// `dbmd` — the reference command-line tool for **db.md**, the open database in
/// plain files.
///
/// db.md is one directory: raw evidence in `sources/`, atomic typed data in
/// `records/` (curator-synthesized narrative lives in `records/` too, as
/// conclusion records tagged `meta-type: conclusion`), and a single `DB.md`
/// at the root. `dbmd` reads, writes, validates, searches, and indexes that
/// store. It embeds ripgrep and has zero AI/LLM dependencies — the agent
/// driving `dbmd` is the semantic layer; `dbmd` is deterministic plumbing.
///
/// Every subcommand supports `--json` for machine-parseable output and
/// `--help`; none prompt interactively. See `dbmd spec` for the full standard.
#[derive(Debug, Parser)]
#[command(
    name = "dbmd",
    version,
    about = "The reference CLI for db.md — the open standard for databases in plain files.",
    long_about = None,
    propagate_version = true,
    // Show the most useful help when invoked bare, rather than a terse error.
    arg_required_else_help = true,
    // We manage color ourselves via --color so output is pipe-safe by default.
    disable_colored_help = true,
)]
pub struct Cli {
    /// Emit machine-parseable JSON instead of human-readable text. Honored by
    /// every subcommand; errors render as `{"error": {...}}` on stderr.
    #[arg(long, global = true)]
    pub json: bool,

    /// When to colorize human output: `auto` (default — off; pipe-safe),
    /// `always`, or `never`. JSON output is never colorized.
    #[arg(long, global = true, value_enum, default_value_t = ColorChoice::Auto, value_name = "WHEN")]
    pub color: ColorChoice,

    /// The subcommand to run.
    #[command(subcommand)]
    pub command: Command,
}

/// Every top-level `dbmd` subcommand. Grouped in declaration order by session
/// phase (open → warm up → read → write → validate → maintain → close), the
/// same grouping SPEC.md § Tooling and TOOLS.md use.
#[derive(Debug, Subcommand)]
pub enum Command {
    // ── Validate ────────────────────────────────────────────────────────────
    /// Validate a store: frontmatter conformance, link integrity, layer-typed
    /// rules, `DB.md` sections, and entity collisions.
    ///
    /// Default = the **working set** (files changed since the last `validate`
    /// log entry, or since `--since`). `--all` runs a full-store SWEEP that
    /// additionally checks `log.md` well-formedness, every index level's sync,
    /// and entity-dedup. Exits non-zero when errors are found.
    Validate(ValidateArgs),

    // ── Format ──────────────────────────────────────────────────────────────
    /// Re-emit a file's frontmatter + body canonically (key order, YAML style,
    /// whitespace). Writes back in place.
    Format(FormatArgs),

    // ── Read: structured query ───────────────────────────────────────────────
    /// Query files by frontmatter — `--type`, `--where key=value` (repeatable),
    /// `--in <layer>`, and `--updated/created-after/-before` time windows.
    /// Resolves against the `index.jsonl` sidecar — never a whole-store parse.
    /// Prints matching store-relative paths; `--json` emits the complete records
    /// (path + summary + tags + links + timestamps + type-specific fields).
    /// (For incoming wiki-links use `graph backlinks`.)
    Query(QueryArgs),

    /// Print one file as its full structured record: parsed frontmatter,
    /// derived fields (layer, type, effective meta-type, title, summary,
    /// timestamps), verbatim body, normalized wiki-link targets with byte
    /// spans, and the file-bytes SHA-256 — the single-file form of
    /// `dbmd emit`, byte-identical under `--json` to that dump's entry for
    /// the file. The store root is found from the file itself (nearest
    /// ancestor `DB.md`). (For the catalog row instead use `query`; for
    /// incoming links, `graph backlinks`.)
    Show(ShowArgs),

    /// List the `##` sections of a single file.
    Sections(SectionsArgs),

    /// Print the store's declared type contracts (`DB.md ## Schemas`), parsed:
    /// each field with its modifiers (`required`, shape, `link to`, `default`,
    /// `enum`), plus the `unique:` keys, `summary_template`, and `shard`
    /// directives. The introspection twin of schema *enforcement*
    /// (`dbmd validate`) — an app or agent renders forms and client-side
    /// checks from this instead of re-parsing `DB.md`. A bare call prints
    /// every declared type; `dbmd schema <type>` narrows to one. A type with
    /// no `### <type>` block is unconstrained and prints nothing.
    Schema(SchemaArgs),

    // ── Read: extraction ─────────────────────────────────────────────────────
    /// Extract plain text from a document (PDF / docx / xlsx / epub / html) to
    /// stdout, auto-detecting the format by extension.
    Extract(ExtractArgs),

    // ── Read: free-text + structured search ──────────────────────────────────
    /// Search the store with embedded ripgrep, narrowed by db.md-aware filters
    /// (`--type`, `--in`, `--where`, link filters, time windows). Structured
    /// filters resolve via the sidecar; the free-text query scans only the
    /// resulting candidate set. Output is `file:line: text`, `rg`-compatible.
    Search(SearchArgs),

    // ── Read: the relationship graph ─────────────────────────────────────────
    /// Inspect the wiki-link graph (backlinks, forward links, neighborhood,
    /// orphans). All on-demand; no maintained graph.
    Graph(GraphArgs),

    // ── Read / Write: frontmatter ────────────────────────────────────────────
    /// Read, write, or initialize file frontmatter. (For frontmatter queries /
    /// pre-write dedup lookups use `query --where key=value`.)
    Fm(FmArgs),

    // ── Read / Write: the body ───────────────────────────────────────────────
    /// Edit a file's body — everything after the frontmatter block. `set`
    /// replaces it verbatim; `append` adds raw content at the end. Both
    /// re-stamp `updated` and update the type-folder indexes write-through;
    /// `summary` is never recomputed (retitle explicitly with `fm set`). The
    /// store root is found from the file itself (nearest ancestor `DB.md`).
    /// (For section-addressed edits use `section`; to create a file, `write`.)
    Body(BodyArgs),

    /// Read or edit one `##`–`######` section of a file's body, addressed by
    /// its exact heading text: `get` prints it verbatim, `set` replaces its
    /// content (the whole subtree, deeper sub-sections included), `append`
    /// adds at its end. Edits re-stamp `updated` and update the indexes
    /// write-through; `--create` appends the section when the heading is
    /// absent. (`sections` lists the addressable headings.)
    Section(SectionArgs),

    // ── Read: structural views ───────────────────────────────────────────────
    /// Pretty-print the store as a tree, optionally scoped by layer or type.
    Tree(TreeArgs),

    /// Print a store overview: file counts (overall / per-layer / per-type),
    /// total size, orphan + broken-link counts, top types. A SWEEP; never
    /// precomputed.
    Stats(StatsArgs),

    // ── Read: the whole-store structured dump ────────────────────────────────
    /// Emit the whole store as one structured JSON document (`--json`): every
    /// content file (`sources/` + `records/`, derived catalogs skipped) plus
    /// `DB.md`, each with its parsed frontmatter (values verbatim), derived
    /// fields (layer, type, effective meta-type, title, summary, timestamps),
    /// verbatim body, normalized wiki-link targets, and the SHA-256 of the
    /// file bytes. The host-integration surface: a hub or indexer ingests a
    /// store as a pure consumer of `dbmd` output instead of reimplementing
    /// the parse. Read-only; a SWEEP. Text mode prints the store-relative
    /// paths that would be emitted, one per line.
    Emit(EmitArgs),

    /// Print the section / sub-section outline of a single file.
    Outline(OutlineArgs),

    // ── Read: the local change feed ──────────────────────────────────────────
    /// Follow the store's files for changes: poll the emit membership (every
    /// content file plus `DB.md`) and print one event line per created /
    /// modified / removed file (one JSON object per line under `--json`) —
    /// the local-filesystem sibling of `subscribe`, which follows a hub feed.
    /// Poll-based and dependency-free: each tick re-stats the membership, so
    /// narrow very large stores with `--path`. Derived catalogs (`index.*`,
    /// `log.md`) are not content and are never reported. Purely observational
    /// (no locks — a watcher never blocks a writer); runs until interrupted.
    Watch(WatchArgs),

    // ── Harness: subscription sign-in ────────────────────────────────────────
    /// Sign in to a provider that bills a SUBSCRIPTION rather than an API key.
    /// `dbmd login codex` runs OpenAI's public PKCE flow so a ChatGPT
    /// Plus/Pro subscription drives `dbmd ask` with no vendor CLI installed:
    /// your browser opens, this process serves the loopback callback, and the
    /// tokens land in the toolkit state directory (0600) — never inside a
    /// store, and refreshed automatically when they expire.
    ///
    /// `dbmd login anthropic` is the second path and delegates: it runs
    /// Anthropic's own `ant auth login`, after which the harness asks `ant`
    /// for a fresh short-lived token per request — the vendor's published
    /// handoff for third-party HTTP clients, so nothing here poses as another
    /// vendor's first-party client. An explicit `ANTHROPIC_API_KEY` still
    /// wins.
    ///
    /// `--code` skips the browser for headless machines (paste the code back
    /// yourself), and `--status` lists what is signed in. A Copilot
    /// subscription, or a Claude subscription you would rather drive through
    /// its own agent, needs no login here: delegate to that CLI
    /// (`--provider claude-code`).
    Login(LoginArgs),

    /// Forget a provider's stored subscription credentials.
    Logout(LogoutArgs),

    // ── Harness: the embedded operator ───────────────────────────────────────
    /// Ask the store a question in natural language. Runs the embedded
    /// micro-harness: a stateless tool-calling loop against YOUR model (a
    /// preset + key, a local server — Ollama/LM Studio/llama.cpp are
    /// autodetected — or a logged-in vendor CLI via `--provider claude-code`
    /// / `codex`), whose tools are the store's READ verbs only (query,
    /// search, show, schema, tree, log tail). Guaranteed no mutation: a
    /// prompt injection can at worst produce a wrong answer. Configure with
    /// `--provider/--model/--base-url/--protocol`, `DBMD_LLM_*` env vars, or
    /// non-secret `llm_*` keys in `.dbmd/config`; the key is env-only
    /// (`DBMD_LLM_KEY`, or the preset's conventional variable). No default
    /// vendor. `--json` streams the event feed as NDJSON.
    Ask(AskArgs),

    /// Tell the store to do something in natural language. The same embedded
    /// harness as `ask` with the WRITE verbs added (write, fm set, body set,
    /// rm — link-aware, never forced — and log). Every mutation rides the
    /// full store contract: schema enforcement, frozen pages, the
    /// cross-process transaction lock (taken per tool call), write-through
    /// indexes, and the store log — the audit trail of what the model did.
    Do(AskArgs),

    /// Operate the store AND the app workspace around it — the full-stack
    /// tier. Adds file tools (list/read/write/edit) confined beneath the
    /// DECLARED workspace root (`--workspace`, `DBMD_WORKSPACE`, or
    /// `workspace = <path>` in `.dbmd/config`); the store subtree is refused
    /// for file tools (store files go through store verbs), and there is no
    /// shell — a running dev server (or your own agent) does any executing.
    /// CLI-only by design: `build` is never exposed over `dbmd api`.
    Build(AskArgs),

    // ── Serve: the local app API ─────────────────────────────────────────────
    /// Serve the store's full local verb surface over loopback HTTP — the
    /// app-server projection of the CLI. Every route executes the
    /// corresponding `dbmd` verb (same binary, same store transaction locks,
    /// `--json` output passed through verbatim), so the API can never drift
    /// from the CLI: reads (`/v1/show`, `/v1/query`, `/v1/search`,
    /// `/v1/schema`, graph/tree/stats/emit/validate/log/assets), writes
    /// (`/v1/write`, `/v1/fm`, `/v1/body`, `/v1/section`, `/v1/link`,
    /// `/v1/rename`, `/v1/rm`, …), and `/v1/events` — the `watch` feed as
    /// Server-Sent Events. Exit codes map to HTTP statuses (0→200, 1/2→400,
    /// 3→404, 4→403, 5→409, 6→422); CORS is open so a local browser app can
    /// call it directly. Loopback ONLY — this is an unauthenticated
    /// read-write surface for the machine's own apps; there is deliberately
    /// no public-bind escape hatch. Cross-party operations (sync, grants,
    /// keys) stay in the CLI and the hub — this serves the folder, not the
    /// network. `GET /v1` lists the routes. Runs until interrupted.
    Api(ApiArgs),

    // ── Read / Maintain: the index catalog ───────────────────────────────────
    /// Maintain or read the write-through index catalog (`index.md` +
    /// `index.jsonl`): rebuild or show. (For structured reads over the sidecar
    /// use `query`.)
    Index(IndexArgs),

    // ── Warm up / Close: the chronological log ───────────────────────────────
    /// Append to, or read from, the append-only store log. The append form is
    /// `dbmd log <kind> <object> [-m <note>]`; `tail` and `since` read it back.
    Log(LogArgs),

    // ── Write ────────────────────────────────────────────────────────────────
    /// Create a new file with canonical frontmatter. Auto-composes `summary`
    /// when `--summary` is absent; source-layer paths auto-shard by date and
    /// the resolved store-relative path is printed. Refuses on path collision.
    Write(WriteArgs),

    /// Append a wiki-link from one file to another (the common-case helper).
    Link(LinkArgs),

    /// Move a file and rewrite every incoming wiki-link across the store.
    /// Updates both affected type-folder indexes write-through.
    Rename(RenameArgs),

    /// Delete one content file, link-aware: refuses while other content files
    /// still wiki-link to it (listing them), `--force` deletes anyway. Updates
    /// the type-folder indexes write-through — the delete twin of `rename`,
    /// replacing the raw `rm` + `dbmd index rebuild` dance. Reserved meta
    /// files (`DB.md`, `log.md`, `index.md`, `index.jsonl`) and frozen pages
    /// are never deletable.
    Rm(RmArgs),

    // ── Assets: the heavy-binary manifest ────────────────────────────────────
    /// Catalog, verify, and report raw assets (PDFs, recordings, large exports
    /// — any in-store file a wrapper declares, markdown content files
    /// included). Maintains the root `assets.jsonl` manifest; never transports
    /// bytes, never runs git.
    Assets(AssetsArgs),

    // ── Interconnect: the link.md client ─────────────────────────────────────
    /// Resolve an `@brain[/id]` address against a hub: a bare `@brain` returns
    /// the brain card (metadata + index stats); `@brain/<record-id>` (or
    /// `@brain/<store-path>.md`) returns the full record, frontmatter + body.
    Resolve(ResolveArgs),

    /// Reconcile a granted hosted brain with a local plain-file checkout.
    /// Pull is the default; `--push` publishes only locally changed files.
    /// Permissioned v2 brains use verified incremental three-way sync with
    /// exact conflicts and baseline-safe deletes. Legacy v1 hubs retain their
    /// whole-snapshot behavior.
    Sync(SyncArgs),

    /// Issue, list, or revoke capability grants on a brain you own. v0 grants
    /// name a hub principal by email; scope is a store-path prefix; a scoped
    /// grant is read-only.
    Grant(GrantArgs),

    /// Submit evidence to a published site's inbox — write without trust. The
    /// submission lands in the owner's `sources/inbox/` (never as truth) for
    /// their curator to accept or reject. Unauthenticated by design.
    Propose(ProposeArgs),

    /// Review the encrypted change queue for a self-custodied brain. Listing
    /// and showing require a full readable view plus `review_proposals`;
    /// accepting also requires the matching local brain key.
    Proposal(ProposalArgs),

    /// Follow a brain's feed head: poll the hub and emit an event line each
    /// time the feed advances (one JSON object per line under `--json`).
    /// `--once` reads the current head and exits.
    Subscribe(SubscribeArgs),

    /// Replicate a brain with FULL verification: every signed feed entry's
    /// signature, hash, and chain linkage checked before its exact bytes are
    /// stored under `.dbmd/mirror/`; the identity is pinned in `.dbmd/config`
    /// (trust-on-first-use); the store files are pulled beside it. The result
    /// is a provable full copy that `dbmd serve` can re-serve — signatures
    /// survive re-hosting.
    Mirror(MirrorArgs),

    /// Serve a mirrored brain read-only over the hub HTTP binding (card, feed,
    /// export) on loopback — the reference node. A second `dbmd` can
    /// `subscribe`/`sync` against it and re-verify the ORIGINAL signatures,
    /// hub-independent: federation v0.
    Serve(ServeArgs),

    /// Agent signing keys (link.md §8). `dbmd key generate` mints an Ed25519
    /// keypair locally — the secret lands in a 0600 file and NEVER leaves the
    /// machine; register the printed `publicKeySpki` with your hub, then set
    /// `DBMD_AGENT_KEY_FILE` to sign every authenticated request instead of
    /// sending a bearer (nothing reusable on the wire).
    Key(KeyArgs),

    /// Internal installer primitive: copy a verified dbmd binary into a held,
    /// no-follow destination directory and atomically replace its regular leaf.
    #[command(name = "__install-verified", hide = true)]
    InstallVerified(InstallVerifiedArgs),

    // ── Agent bootstrap ──────────────────────────────────────────────────────
    /// Print the bundled canonical SPEC.md (compiled in at build time). The
    /// installation point: `dbmd spec` loads the standard into an agent's
    /// system prompt.
    Spec(SpecArgs),
}

#[derive(Debug, Args)]
pub struct InstallVerifiedArgs {
    /// Verified binary extracted from the authenticated release archive.
    #[arg(value_name = "SOURCE")]
    pub source: String,

    /// Destination directory to create/open without following symlinks.
    #[arg(value_name = "INSTALL_DIR")]
    pub install_dir: String,
}

// ─────────────────────────────────────────────────────────────────────────────
// validate
// ─────────────────────────────────────────────────────────────────────────────

/// `dbmd validate` — working-set by default, full SWEEP under `--all`.
#[derive(Debug, Args)]
pub struct ValidateArgs {
    /// Store root to validate. Defaults to the current directory (which must be
    /// a db.md store, i.e. contain `DB.md`).
    #[arg(value_name = "DIR", default_value = ".")]
    pub dir: String,

    /// Run a full-store SWEEP (every file, every index level, `log.md`
    /// well-formedness, entity-dedup) instead of the default working set.
    #[arg(long)]
    pub all: bool,

    /// Validate an intentionally partial store projection. FILE is a bounded
    /// `.sevralocal`-compatible list of case-sensitive store-path globs. Only
    /// broken wiki-links matched by a rule are downgraded to explicit
    /// projection-unresolved info; every other error remains blocking. Requires
    /// `--all`.
    #[arg(
        long,
        value_name = "FILE",
        requires = "all",
        conflicts_with = "projection_manifest"
    )]
    pub projection_excludes: Option<String>,

    /// Validate from a canonical path-confidential projection commitment
    /// manifest. FILE is store-relative; `-` reads bounded JSON from stdin.
    /// Requires `--all` and is mutually exclusive with
    /// `--projection-excludes`.
    #[arg(
        long,
        value_name = "FILE",
        requires = "all",
        conflicts_with = "projection_excludes"
    )]
    pub projection_manifest: Option<String>,

    /// Override the working-set cutoff: validate files changed at or after this
    /// RFC3339 timestamp. Ignored when `--all` is set. Date-only is accepted
    /// and treated as `T00:00:00Z`.
    #[arg(long, value_name = "RFC3339")]
    pub since: Option<String>,
}

// ─────────────────────────────────────────────────────────────────────────────
// format
// ─────────────────────────────────────────────────────────────────────────────

/// `dbmd format <file>` — canonical re-emit, writes back in place.
#[derive(Debug, Args)]
pub struct FormatArgs {
    /// The file to re-format canonically.
    #[arg(value_name = "FILE")]
    pub file: String,
}

// ─────────────────────────────────────────────────────────────────────────────
// query
// ─────────────────────────────────────────────────────────────────────────────

/// `dbmd query` — frontmatter filter over the sidecar.
#[derive(Debug, Args)]
pub struct QueryArgs {
    /// Filter to files whose frontmatter `type` equals this value.
    #[arg(long, value_name = "TYPE")]
    pub r#type: Option<String>,

    /// Scope to a single layer: `sources` or `records`.
    #[arg(long, value_name = "LAYER")]
    pub r#in: Option<String>,

    /// Additional frontmatter filter as `key=value`. Repeatable.
    #[arg(long = "where", value_name = "K=V")]
    pub r#where: Vec<String>,

    /// Only files whose `updated` is at or after this RFC3339 timestamp.
    #[arg(long, value_name = "RFC3339")]
    pub updated_after: Option<String>,

    /// Only files whose `updated` is at or before this RFC3339 timestamp.
    #[arg(long, value_name = "RFC3339")]
    pub updated_before: Option<String>,

    /// Only files whose `created` is at or after this RFC3339 timestamp.
    #[arg(long, value_name = "RFC3339")]
    pub created_after: Option<String>,

    /// Only files whose `created` is at or before this RFC3339 timestamp.
    #[arg(long, value_name = "RFC3339")]
    pub created_before: Option<String>,

    /// Cap the number of results.
    #[arg(long, value_name = "N")]
    pub limit: Option<usize>,

    /// Store root. Defaults to the current directory.
    #[arg(long, value_name = "DIR", default_value = ".")]
    pub dir: String,
}

// ─────────────────────────────────────────────────────────────────────────────
// show
// ─────────────────────────────────────────────────────────────────────────────

/// `dbmd show <file>` — one file as its full structured record.
#[derive(Debug, Args)]
pub struct ShowArgs {
    /// The file to show. Its store is the nearest ancestor carrying `DB.md`.
    #[arg(value_name = "FILE")]
    pub file: String,
}

// ─────────────────────────────────────────────────────────────────────────────
// sections
// ─────────────────────────────────────────────────────────────────────────────

/// `dbmd sections <file>` — list `##` sections in a file.
#[derive(Debug, Args)]
pub struct SectionsArgs {
    /// The file whose sections to list.
    #[arg(value_name = "FILE")]
    pub file: String,
}

// ─────────────────────────────────────────────────────────────────────────────
// schema
// ─────────────────────────────────────────────────────────────────────────────

/// `dbmd schema [<type>]` — the declared type contracts, parsed.
#[derive(Debug, Args)]
pub struct SchemaArgs {
    /// Print only this type's schema. A type with no `### <type>` block in
    /// `DB.md ## Schemas` is unconstrained and prints nothing.
    #[arg(value_name = "TYPE")]
    pub r#type: Option<String>,

    /// Store root. Defaults to the current directory.
    #[arg(long, value_name = "DIR", default_value = ".")]
    pub dir: String,
}

// ─────────────────────────────────────────────────────────────────────────────
// extract
// ─────────────────────────────────────────────────────────────────────────────

/// `dbmd extract <file>` — document text extraction.
#[derive(Debug, Args)]
pub struct ExtractArgs {
    /// The document to extract text from (PDF / docx / xlsx / epub / html;
    /// format auto-detected by extension).
    #[arg(value_name = "FILE")]
    pub file: String,

    /// Write the extracted text to this path instead of stdout.
    #[arg(long, value_name = "PATH")]
    pub out: Option<String>,
}

// ─────────────────────────────────────────────────────────────────────────────
// search
// ─────────────────────────────────────────────────────────────────────────────

/// `dbmd search <query>` — ripgrep over a sidecar-resolved candidate set.
#[derive(Debug, Args)]
pub struct SearchArgs {
    /// The free-text query (a regex; alternation like `(revenue|sales|ARR)` is
    /// the agent's query-expansion path — no embeddings).
    #[arg(value_name = "QUERY")]
    pub query: String,

    /// Filter to files whose frontmatter `type` equals this value.
    #[arg(long, value_name = "TYPE")]
    pub r#type: Option<String>,

    /// Scope to a single layer: `sources` or `records`.
    #[arg(long, value_name = "LAYER")]
    pub r#in: Option<String>,

    /// Additional frontmatter filter as `key=value`. Repeatable.
    #[arg(long = "where", value_name = "K=V")]
    pub r#where: Vec<String>,

    /// Restrict to files that the given file links TO (forward links).
    #[arg(long, value_name = "PATH")]
    pub linked_from: Option<String>,

    /// Restrict to files that link TO the given file (backlinks).
    #[arg(long, value_name = "PATH")]
    pub linked_to: Option<String>,

    /// Only files whose `updated` is at or after this RFC3339 timestamp.
    #[arg(long, value_name = "RFC3339")]
    pub updated_after: Option<String>,

    /// Only files whose `updated` is at or before this RFC3339 timestamp.
    #[arg(long, value_name = "RFC3339")]
    pub updated_before: Option<String>,

    /// Only files whose `created` is at or after this RFC3339 timestamp.
    #[arg(long, value_name = "RFC3339")]
    pub created_after: Option<String>,

    /// Only files whose `created` is at or before this RFC3339 timestamp.
    #[arg(long, value_name = "RFC3339")]
    pub created_before: Option<String>,

    /// Cap the number of matches.
    #[arg(long, value_name = "N")]
    pub limit: Option<usize>,

    /// Store root. Defaults to the current directory.
    #[arg(long, value_name = "DIR", default_value = ".")]
    pub dir: String,
}

// ─────────────────────────────────────────────────────────────────────────────
// graph (backlinks / forwardlinks / neighborhood / orphans)
// ─────────────────────────────────────────────────────────────────────────────

/// `dbmd graph <sub>` — the relationship-retrieval axis.
#[derive(Debug, Args)]
pub struct GraphArgs {
    /// Which graph view to compute.
    #[command(subcommand)]
    pub command: GraphCommand,
}

/// The `dbmd graph` subcommands.
#[derive(Debug, Subcommand)]
pub enum GraphCommand {
    /// Incoming wiki-links to a file (blast radius / dependents).
    Backlinks(GraphTargetArgs),

    /// Outgoing wiki-links from a file (follow the chain).
    Forwardlinks(GraphTargetArgs),

    /// Bounded BFS from a seed: each reached node, its `summary`, and how it
    /// connects — context hydration in one call.
    Neighborhood(NeighborhoodArgs),

    /// Content files with no incoming or outgoing links (the curation
    /// worklist).
    Orphans(OrphansArgs),
}

/// Shared args for `graph backlinks` / `graph forwardlinks`.
#[derive(Debug, Args)]
pub struct GraphTargetArgs {
    /// The store-relative file path to inspect.
    #[arg(value_name = "PATH")]
    pub path: String,

    /// Restrict to linking/linked files of this frontmatter `type`. For
    /// `backlinks` this scopes which type-folder `index.jsonl` sidecars are read
    /// (an I/O scope, not just a filter); for `forwardlinks` it filters the
    /// returned targets by their type.
    #[arg(long, value_name = "TYPE")]
    pub r#type: Option<String>,

    /// Restrict to a single layer: `sources` or `records`. For
    /// `backlinks` this scopes the sidecar walk to that layer; for
    /// `forwardlinks` it filters the returned targets by layer.
    #[arg(long, value_name = "LAYER")]
    pub r#in: Option<String>,

    /// Cap the number of results.
    #[arg(long, value_name = "N")]
    pub limit: Option<usize>,

    /// Store root. Defaults to the current directory.
    #[arg(long, value_name = "DIR", default_value = ".")]
    pub dir: String,
}

/// `dbmd graph neighborhood <seed>`.
#[derive(Debug, Args)]
pub struct NeighborhoodArgs {
    /// The store-relative seed path to expand from.
    #[arg(value_name = "SEED")]
    pub seed: String,

    /// How many hops out from the seed to traverse.
    #[arg(long, value_name = "N", default_value_t = 1)]
    pub hops: usize,

    /// Restrict reached nodes to this frontmatter `type`.
    #[arg(long, value_name = "TYPE")]
    pub r#type: Option<String>,

    /// Restrict reached nodes to this layer.
    #[arg(long, value_name = "LAYER")]
    pub r#in: Option<String>,

    /// Cap the number of reached nodes. Also bounds the BFS traversal work (the
    /// per-node full-store backlinks scans), not just the printed result, and
    /// defaults to 200 when unset so the command is never unbounded on a
    /// densely-linked hub.
    #[arg(long, value_name = "N")]
    pub limit: Option<usize>,

    /// Store root. Defaults to the current directory.
    #[arg(long, value_name = "DIR", default_value = ".")]
    pub dir: String,
}

/// `dbmd graph orphans`.
#[derive(Debug, Args)]
pub struct OrphansArgs {
    /// Restrict to a single layer: `sources` or `records`.
    #[arg(long, value_name = "LAYER")]
    pub r#in: Option<String>,

    /// Cap the number of results.
    #[arg(long, value_name = "N")]
    pub limit: Option<usize>,

    /// Store root. Defaults to the current directory.
    #[arg(long, value_name = "DIR", default_value = ".")]
    pub dir: String,
}

// ─────────────────────────────────────────────────────────────────────────────
// fm (get / set / query / init)
// ─────────────────────────────────────────────────────────────────────────────

/// `dbmd fm <sub>` — frontmatter read/write/query/init.
#[derive(Debug, Args)]
pub struct FmArgs {
    /// Which frontmatter operation to run.
    #[command(subcommand)]
    pub command: FmCommand,
}

/// The `dbmd fm` subcommands.
#[derive(Debug, Subcommand)]
pub enum FmCommand {
    /// Read a single frontmatter value: `dbmd fm get <file> <key>`.
    Get(FmGetArgs),

    /// Set (insert/update) a frontmatter value: `dbmd fm set <file> <key>=<value>`.
    /// Atomic; re-sorts the type-folder index entry if recency changed.
    Set(FmSetArgs),

    /// Initialize canonical frontmatter on a file: auto-detect type by path,
    /// seed timestamps, compose a default `summary`, and fold the file into its
    /// `index`. `dbmd fm init <file> [--summary <str>]`.
    Init(FmInitArgs),
}

/// `dbmd fm get <file> <key>`.
#[derive(Debug, Args)]
pub struct FmGetArgs {
    /// The file to read frontmatter from (e.g. `DB.md` for store identity).
    #[arg(value_name = "FILE")]
    pub file: String,

    /// The frontmatter key to read.
    #[arg(value_name = "KEY")]
    pub key: String,
}

/// `dbmd fm set <file> <key>=<value>`.
#[derive(Debug, Args)]
pub struct FmSetArgs {
    /// The file to update.
    #[arg(value_name = "FILE")]
    pub file: String,

    /// The assignment, `key=value`. The value may be a wiki-link, scalar, or
    /// quoted string.
    #[arg(value_name = "K=V")]
    pub assignment: String,
}

/// `dbmd fm init <file>`.
#[derive(Debug, Args)]
pub struct FmInitArgs {
    /// The file to initialize frontmatter on (type auto-detected by path).
    #[arg(value_name = "FILE")]
    pub file: String,

    /// Override the composed default `summary` with this string.
    #[arg(long, value_name = "STR")]
    pub summary: Option<String>,
}

// ─────────────────────────────────────────────────────────────────────────────
// tree
// ─────────────────────────────────────────────────────────────────────────────

/// `dbmd tree` — pretty-print the store.
#[derive(Debug, Args)]
pub struct TreeArgs {
    /// Restrict to a single layer: `sources` or `records`.
    #[arg(long, value_name = "LAYER")]
    pub layer: Option<String>,

    /// Restrict to a single frontmatter `type`.
    #[arg(long, value_name = "TYPE")]
    pub r#type: Option<String>,

    /// Store root. Defaults to the current directory.
    #[arg(long, value_name = "DIR", default_value = ".")]
    pub dir: String,
}

// ─────────────────────────────────────────────────────────────────────────────
// stats
// ─────────────────────────────────────────────────────────────────────────────

/// `dbmd stats` — on-demand store overview (a SWEEP).
#[derive(Debug, Args)]
pub struct StatsArgs {
    /// Store root. Defaults to the current directory.
    #[arg(value_name = "DIR", default_value = ".")]
    pub dir: String,
}

// ─────────────────────────────────────────────────────────────────────────────
// emit
// ─────────────────────────────────────────────────────────────────────────────

/// `dbmd emit` — the whole-store structured dump (a SWEEP; read-only).
#[derive(Debug, Args)]
pub struct EmitArgs {
    /// Store root. Defaults to the current directory.
    #[arg(value_name = "DIR", default_value = ".")]
    pub dir: String,

    /// Stream the dump as NDJSON: one compact JSON object per line — exactly
    /// the `--json` form's `files[]` element shape, in the same deterministic
    /// order, with no envelope or summary. The streaming form of the same
    /// contract: a consumer that concatenates the lines gets `files[]`
    /// verbatim, and neither side ever holds the whole dump (each file is
    /// projected, printed, and dropped). Implies machine output; the global
    /// `--json` flag is redundant with it.
    #[arg(long)]
    pub ndjson: bool,
}

// ─────────────────────────────────────────────────────────────────────────────
// outline
// ─────────────────────────────────────────────────────────────────────────────

/// `dbmd outline <file>` — section + sub-section outline of one file.
#[derive(Debug, Args)]
pub struct OutlineArgs {
    /// The file to outline.
    #[arg(value_name = "FILE")]
    pub file: String,

    /// The store directory (defaults to the current directory). Consistent with
    /// the other read commands so `outline` can target a store from elsewhere.
    #[arg(long, value_name = "DIR", default_value = ".")]
    pub dir: String,
}

// ─────────────────────────────────────────────────────────────────────────────
// index (rebuild / show / query)
// ─────────────────────────────────────────────────────────────────────────────

/// `dbmd index <sub>` — the write-through catalog.
#[derive(Debug, Args)]
pub struct IndexArgs {
    /// Which index operation to run.
    #[command(subcommand)]
    pub command: IndexCommand,
}

/// The `dbmd index` subcommands.
#[derive(Debug, Subcommand)]
pub enum IndexCommand {
    /// From-scratch repair of the catalog (not a loop step — writes maintain it
    /// write-through). Rebuilds the full hierarchy by default; scope with
    /// `--layer` / `--folder`; preview with `--dry-run`.
    Rebuild(IndexRebuildArgs),

    /// Print an `index.md` to stdout. Default = root; pass a layer or
    /// type-folder path for a scoped index.
    Show(IndexShowArgs),
}

/// `dbmd index rebuild`.
#[derive(Debug, Args)]
pub struct IndexRebuildArgs {
    /// Scope the rebuild to a single layer: `sources` or `records`.
    #[arg(long, value_name = "LAYER")]
    pub layer: Option<String>,

    /// Scope the rebuild to a single folder (store-relative).
    #[arg(long, value_name = "PATH")]
    pub folder: Option<String>,

    /// Print what would be written (with `--- <path> ---` separators) without
    /// writing anything.
    #[arg(long)]
    pub dry_run: bool,

    /// Store root. Defaults to the current directory.
    #[arg(long, value_name = "DIR", default_value = ".")]
    pub dir: String,
}

/// `dbmd index show [<path>]`.
#[derive(Debug, Args)]
pub struct IndexShowArgs {
    /// The layer or type-folder whose `index.md` to print (e.g.
    /// `records/profiles`). Omit for the root `index.md`.
    #[arg(value_name = "PATH")]
    pub path: Option<String>,

    /// Store root. Defaults to the current directory.
    #[arg(long, value_name = "DIR", default_value = ".")]
    pub dir: String,
}

// ─────────────────────────────────────────────────────────────────────────────
// log (append form + tail + since)
// ─────────────────────────────────────────────────────────────────────────────

/// `dbmd log` — the store timeline.
///
/// Two shapes share this command. The **append** form takes a `<kind>` and an
/// `<object>` positionally with an optional `-m <note>`:
/// `dbmd log create records/meetings/standup.md -m "weekly sync"`. The **read**
/// forms are the explicit `tail` and `since` subcommands. clap routes any
/// first token that is not `tail`/`since`/`help` into the append form via an
/// external subcommand; the body parses `<kind> <object> [-m <note>]` out of
/// the captured tokens.
#[derive(Debug, Args)]
pub struct LogArgs {
    /// `tail`, `since`, or the append form (`<kind> <object> [-m <note>]`).
    #[command(subcommand)]
    pub command: LogCommand,
}

/// The `dbmd log` subcommands.
#[derive(Debug, Subcommand)]
pub enum LogCommand {
    /// Read the last N entries (default 20), oldest→newest (chronological): the
    /// last printed line is the most recent.
    Tail(LogTailArgs),

    /// Read entries newer than an RFC3339 timestamp (date-only is treated as
    /// `T00:00:00Z`).
    Since(LogSinceArgs),

    /// The append form: `dbmd log <kind> <object> [-m <note>]`. Captured
    /// verbatim; the body splits out the kind, object, and optional `-m` note.
    /// (`<object>` is the file path the action was on, or `-` for store-wide.)
    #[command(external_subcommand)]
    Append(Vec<String>),
}

/// `dbmd log tail [N]`.
#[derive(Debug, Args)]
pub struct LogTailArgs {
    /// How many entries to read. The returned window is the last N entries,
    /// printed oldest→newest (chronological); the last line is the most recent.
    #[arg(value_name = "N", default_value_t = 20)]
    pub n: usize,

    /// Store root. Defaults to the current directory.
    #[arg(long, value_name = "DIR", default_value = ".")]
    pub dir: String,
}

/// `dbmd log since <timestamp>`.
#[derive(Debug, Args)]
pub struct LogSinceArgs {
    /// The RFC3339 timestamp; entries strictly newer are returned. Date-only
    /// (`2026-05-27`) is accepted and treated as `T00:00:00Z`.
    #[arg(value_name = "RFC3339")]
    pub timestamp: String,

    /// Store root. Defaults to the current directory.
    #[arg(long, value_name = "DIR", default_value = ".")]
    pub dir: String,
}

// ─────────────────────────────────────────────────────────────────────────────
// write
// ─────────────────────────────────────────────────────────────────────────────

/// `dbmd write <path> --type <t>` — create a new file with frontmatter.
#[derive(Debug, Args)]
pub struct WriteArgs {
    /// The store-relative path to create. Source-layer paths auto-shard by date
    /// (`sources/<type>/<YYYY>/<MM>/`); the resolved path is printed.
    #[arg(value_name = "PATH")]
    pub path: String,

    /// The frontmatter `type` for the new file (required).
    #[arg(long, value_name = "TYPE")]
    pub r#type: String,

    /// The canonical `summary`. If absent, a deterministic default is composed;
    /// a content file with no usable summary is refused.
    #[arg(long, value_name = "STR")]
    pub summary: Option<String>,

    /// Additional frontmatter as `key=value`. Repeatable.
    #[arg(long, value_name = "K=V")]
    pub fm: Vec<String>,

    /// Read the markdown body from this file (otherwise the body is empty).
    #[arg(long, value_name = "PATH")]
    pub body_file: Option<String>,

    /// Store root. Defaults to the current directory.
    #[arg(long, value_name = "DIR", default_value = ".")]
    pub dir: String,
}

// ─────────────────────────────────────────────────────────────────────────────
// link
// ─────────────────────────────────────────────────────────────────────────────

/// `dbmd link <from> <to>` — append a wiki-link.
#[derive(Debug, Args)]
pub struct LinkArgs {
    /// The file to add the wiki-link to.
    #[arg(value_name = "FROM")]
    pub from: String,

    /// The store-relative target the wiki-link points at.
    #[arg(value_name = "TO")]
    pub to: String,

    /// Store root. Defaults to the current directory.
    #[arg(long, value_name = "DIR", default_value = ".")]
    pub dir: String,
}

// ─────────────────────────────────────────────────────────────────────────────
// rename
// ─────────────────────────────────────────────────────────────────────────────

/// `dbmd rename <old> <new>` — move a file + rewrite incoming wiki-links.
#[derive(Debug, Args)]
pub struct RenameArgs {
    /// The current store-relative path.
    #[arg(value_name = "OLD")]
    pub old: String,

    /// The new store-relative path.
    #[arg(value_name = "NEW")]
    pub new: String,

    /// Store root. Defaults to the current directory.
    #[arg(long, value_name = "DIR", default_value = ".")]
    pub dir: String,
}

// ─────────────────────────────────────────────────────────────────────────────
// api
// ─────────────────────────────────────────────────────────────────────────────

/// `dbmd api` — the local app API over loopback HTTP.
#[derive(Debug, Args)]
pub struct ApiArgs {
    /// Listen address. Must be loopback ("3263" is `dbmd` on a phone
    /// keypad); port `0` binds an OS-assigned free port, printed on the
    /// first output line.
    #[arg(long, value_name = "ADDR", default_value = "127.0.0.1:3263")]
    pub addr: String,

    /// Enable `POST /v1/ask` — the embedded harness's read-only registry,
    /// streamed as SSE. Off by default: an ask route lets anything on
    /// loopback spend the configured model's tokens.
    #[arg(long = "ask")]
    pub enable_ask: bool,

    /// Enable `POST /v1/do` — the harness's write registry over SSE
    /// (implies --ask). Off by default for the same reason, doubly so:
    /// callers can mutate the store through the model.
    #[arg(long = "do")]
    pub enable_do: bool,

    /// Store root. Defaults to the current directory.
    #[arg(long, value_name = "DIR", default_value = ".")]
    pub dir: String,
}

// ─────────────────────────────────────────────────────────────────────────────
// login / logout (subscription sign-in)
// ─────────────────────────────────────────────────────────────────────────────

/// `dbmd login [codex]`.
#[derive(Debug, Args)]
pub struct LoginArgs {
    /// Which provider to sign in to: `codex` (a ChatGPT Plus/Pro
    /// subscription, native PKCE flow) or `anthropic` (delegates to
    /// Anthropic's own `ant auth login`). Defaults to `codex`.
    #[arg(value_name = "PROVIDER")]
    pub provider: Option<String>,

    /// Do not open a browser or bind the callback port: print the URL and
    /// read the authorization code (or full redirect URL) from stdin.
    #[arg(long)]
    pub code: bool,

    /// List the providers with stored credentials instead of signing in.
    #[arg(long)]
    pub status: bool,
}

/// `dbmd logout [codex]`.
#[derive(Debug, Args)]
pub struct LogoutArgs {
    /// Which provider's credentials to forget (defaults to `codex`).
    #[arg(value_name = "PROVIDER")]
    pub provider: Option<String>,
}

// ─────────────────────────────────────────────────────────────────────────────
// ask / do / build (the embedded harness)
// ─────────────────────────────────────────────────────────────────────────────

/// Shared arguments of `dbmd ask` / `do` / `build`.
#[derive(Debug, Args)]
pub struct AskArgs {
    /// The natural-language request.
    #[arg(value_name = "PROMPT")]
    pub prompt: String,

    /// Provider preset: an API-key provider (anthropic, openai, openrouter,
    /// groq, together, deepseek, mistral), a local server (ollama, lmstudio,
    /// llamacpp), your ChatGPT subscription (`codex`, after `dbmd login
    /// codex`), or a delegation backend that drives an installed, logged-in
    /// vendor CLI (claude-code, codex-cli). No default: with nothing
    /// configured, local servers are autodetected.
    #[arg(long, value_name = "NAME")]
    pub provider: Option<String>,

    /// Model id sent on the wire (e.g. `claude-sonnet-5`, `qwen3:8b`).
    #[arg(long, value_name = "MODEL")]
    pub model: Option<String>,

    /// Endpoint base URL (overrides the preset). For `--protocol openai`
    /// include the `/v1` prefix; for `--protocol anthropic` exclude it.
    #[arg(long, value_name = "URL")]
    pub base_url: Option<String>,

    /// Wire protocol when `--base-url` is used without a preset:
    /// `openai` or `anthropic`.
    #[arg(long, value_name = "PROTO")]
    pub protocol: Option<String>,

    /// How hard the model should think: `off`, `minimal`, `low`, `medium`,
    /// `high`, `xhigh`, or `max`. Translated per provider (ChatGPT
    /// `reasoning.effort`, Anthropic `output_config.effort`, Ollama and other
    /// OpenAI-compatible servers `reasoning_effort`), and dropped
    /// automatically if the endpoint refuses it. Unset leaves each provider
    /// on its own default. Also `DBMD_LLM_EFFORT`, or `llm_effort` in
    /// `.dbmd/config`.
    #[arg(long, value_name = "LEVEL")]
    pub effort: Option<String>,

    /// Maximum model round-trips before the final forced answer.
    #[arg(long, value_name = "N", default_value_t = 15)]
    pub max_turns: usize,

    /// `max_tokens` per model call (default 4096).
    #[arg(long, value_name = "N")]
    pub max_tokens: Option<u32>,

    /// The app workspace root for `dbmd build` (also `DBMD_WORKSPACE`, or
    /// `workspace = <path>` in `.dbmd/config`, relative to the store root).
    #[arg(long, value_name = "DIR")]
    pub workspace: Option<String>,

    /// Store root. Defaults to the current directory.
    #[arg(long, value_name = "DIR", default_value = ".")]
    pub dir: String,
}

// ─────────────────────────────────────────────────────────────────────────────
// watch
// ─────────────────────────────────────────────────────────────────────────────

/// `dbmd watch` — follow the store's files for changes.
#[derive(Debug, Args)]
pub struct WatchArgs {
    /// Only report changes under this store-relative path prefix (e.g.
    /// `records/todos`). Bounds the per-poll scan on very large stores.
    #[arg(long, value_name = "PATH")]
    pub path: Option<String>,

    /// Poll interval in seconds. Minimum 1.
    #[arg(long, value_name = "SECS", default_value_t = 1)]
    pub interval: u64,

    /// Store root. Defaults to the current directory.
    #[arg(long, value_name = "DIR", default_value = ".")]
    pub dir: String,
}

// ─────────────────────────────────────────────────────────────────────────────
// body
// ─────────────────────────────────────────────────────────────────────────────

/// `dbmd body <set|append> <file>` — whole-body edit.
#[derive(Debug, Args)]
pub struct BodyArgs {
    /// The body operation to run.
    #[command(subcommand)]
    pub command: BodyCommand,
}

/// The `body` sub-verbs.
#[derive(Debug, Subcommand)]
pub enum BodyCommand {
    /// Replace the whole body with the given content, stored verbatim.
    Set(BodyEditArgs),

    /// Append raw content at the end of the body (the joint gains a newline
    /// when the existing body lacks one; the content itself rides verbatim).
    Append(BodyEditArgs),
}

/// Shared arguments of the `body` edit sub-verbs.
#[derive(Debug, Args)]
#[command(group = ArgGroup::new("content").required(true).args(["text", "body_file"]))]
pub struct BodyEditArgs {
    /// The file whose body to edit. Its store is the nearest ancestor
    /// carrying `DB.md`.
    #[arg(value_name = "FILE")]
    pub file: String,

    /// The content, inline. Hyphen-leading values (list items) are accepted.
    #[arg(long, value_name = "TEXT", allow_hyphen_values = true)]
    pub text: Option<String>,

    /// Read the content from this file; `-` reads standard input.
    #[arg(long, value_name = "PATH")]
    pub body_file: Option<String>,
}

// ─────────────────────────────────────────────────────────────────────────────
// section
// ─────────────────────────────────────────────────────────────────────────────

/// `dbmd section <get|set|append> <file> <heading>` — section-addressed ops.
#[derive(Debug, Args)]
pub struct SectionArgs {
    /// The section operation to run.
    #[command(subcommand)]
    pub command: SectionCommand,
}

/// The `section` sub-verbs.
#[derive(Debug, Subcommand)]
pub enum SectionCommand {
    /// Print the addressed section verbatim — heading line plus content,
    /// deeper sub-sections included. Store-free: works on any markdown file.
    Get(SectionGetArgs),

    /// Replace the addressed section's content (its whole subtree), keeping
    /// the heading line itself.
    Set(SectionEditArgs),

    /// Append content at the end of the addressed section, before the next
    /// sibling-or-shallower heading.
    Append(SectionEditArgs),
}

/// Arguments of `section get`.
#[derive(Debug, Args)]
pub struct SectionGetArgs {
    /// The file to read.
    #[arg(value_name = "FILE")]
    pub file: String,

    /// The exact heading text, without the leading `#`s.
    #[arg(value_name = "HEADING")]
    pub heading: String,
}

/// Shared arguments of the `section` edit sub-verbs.
#[derive(Debug, Args)]
#[command(group = ArgGroup::new("content").required(true).args(["text", "body_file"]))]
pub struct SectionEditArgs {
    /// The file whose section to edit. Its store is the nearest ancestor
    /// carrying `DB.md`.
    #[arg(value_name = "FILE")]
    pub file: String,

    /// The exact heading text, without the leading `#`s. Duplicate headings
    /// are refused as ambiguous.
    #[arg(value_name = "HEADING")]
    pub heading: String,

    /// The content, inline. Hyphen-leading values (list items) are accepted.
    #[arg(long, value_name = "TEXT", allow_hyphen_values = true)]
    pub text: Option<String>,

    /// Read the content from this file; `-` reads standard input.
    #[arg(long, value_name = "PATH")]
    pub body_file: Option<String>,

    /// When the heading is absent, create the section at the end of the body
    /// (one separating blank line) instead of failing.
    #[arg(long)]
    pub create: bool,

    /// Heading level for a section created by `--create` (2–6).
    #[arg(long, value_name = "N", default_value_t = 2,
          value_parser = clap::value_parser!(u8).range(2..=6))]
    pub level: u8,
}

// ─────────────────────────────────────────────────────────────────────────────
// rm
// ─────────────────────────────────────────────────────────────────────────────

/// `dbmd rm <path>` — link-aware delete of one content file.
#[derive(Debug, Args)]
pub struct RmArgs {
    /// The content file to delete.
    #[arg(value_name = "PATH")]
    pub path: String,

    /// Delete even while other content files still wiki-link to the target.
    /// Each such link is left dangling; `dbmd validate --all` then reports
    /// `WIKI_LINK_BROKEN` on its file.
    #[arg(long)]
    pub force: bool,

    /// Store root. Defaults to the current directory.
    #[arg(long, value_name = "DIR", default_value = ".")]
    pub dir: String,
}

// ─────────────────────────────────────────────────────────────────────────────
// spec
// ─────────────────────────────────────────────────────────────────────────────

/// `dbmd spec` — print the bundled canonical SPEC.md.
#[derive(Debug, Args)]
pub struct SpecArgs {
    /// Print a specific SPEC instead of the compiled-in one (overrides the
    /// `DBMD_SPEC` env var).
    #[arg(long, value_name = "PATH")]
    pub spec: Option<String>,
}

// ─────────────────────────────────────────────────────────────────────────────
// assets (scan / refresh / refresh-wrapper / verify / status / paths)
// ─────────────────────────────────────────────────────────────────────────────

/// `dbmd assets <sub>` — the heavy-binary asset manifest.
#[derive(Debug, Args)]
pub struct AssetsArgs {
    /// Which asset operation to run.
    #[command(subcommand)]
    pub command: AssetsCommand,
}

/// The `dbmd assets` subcommands.
#[derive(Debug, Subcommand)]
pub enum AssetsCommand {
    /// Scan content files' `asset`/`assets` frontmatter, hash present files, and
    /// (re)write the canonical `assets.jsonl`. The manifest is a pure projection
    /// of the declarations; a path no longer declared drops out.
    Scan(AssetsScanArgs),

    /// Re-hash one asset declared by one wrapper and update only that canonical
    /// manifest row. This is the bounded write-through path; `scan` remains the
    /// from-scratch sweep.
    Refresh(AssetsRefreshArgs),

    /// Reconcile one wrapper's complete current asset set and write the
    /// manifest once, including clearing a now-empty generated set.
    #[command(name = "refresh-wrapper")]
    RefreshWrapper(AssetsRefreshWrapperArgs),

    /// Verify every required asset is present locally and matches the manifest.
    /// `--quick` checks presence+size only; the default deep mode re-hashes.
    /// Exits non-zero when anything is missing or corrupt. A SWEEP, not a loop op.
    Verify(AssetsVerifyArgs),

    /// Report present / missing assets and how many bytes remain to restore.
    /// Never fails on a missing asset.
    Status(AssetsStatusArgs),

    /// Print the cataloged asset paths, one per line — the VCS-neutral list a
    /// harness feeds into a `.gitignore` managed block or a sync exclude.
    /// Markdown assets are omitted (they are content files and must never be
    /// hidden from the VCS); their bytes stay tracked via the manifest.
    Paths(AssetsPathsArgs),
}

/// `dbmd assets scan`.
#[derive(Debug, Args)]
pub struct AssetsScanArgs {
    /// Store root. Defaults to the current directory.
    #[arg(long, value_name = "DIR", default_value = ".")]
    pub dir: String,

    /// Compute and report what would change, without writing the manifest.
    #[arg(long)]
    pub dry_run: bool,

    /// Also report non-markdown files under `sources/` that no wrapper declares.
    #[arg(long)]
    pub untracked: bool,
}

/// `dbmd assets refresh <path> --wrapper <wrapper>`.
#[derive(Debug, Args)]
pub struct AssetsRefreshArgs {
    /// Store-relative asset path to re-hash.
    #[arg(value_name = "PATH")]
    pub path: String,

    /// A markdown content file that currently declares this asset.
    #[arg(long, value_name = "PATH")]
    pub wrapper: String,

    /// Store root. Defaults to the current directory.
    #[arg(long, value_name = "DIR", default_value = ".")]
    pub dir: String,
}

/// `dbmd assets refresh-wrapper <wrapper>`.
#[derive(Debug, Args)]
pub struct AssetsRefreshWrapperArgs {
    /// Markdown content file whose complete asset set should be reconciled.
    #[arg(value_name = "WRAPPER")]
    pub wrapper: String,

    /// Store root. Defaults to the current directory.
    #[arg(long, value_name = "DIR", default_value = ".")]
    pub dir: String,
}

/// `dbmd assets verify`.
#[derive(Debug, Args)]
pub struct AssetsVerifyArgs {
    /// Store root. Defaults to the current directory.
    #[arg(long, value_name = "DIR", default_value = ".")]
    pub dir: String,

    /// Include optional (non-required) assets in the check.
    #[arg(long)]
    pub include_optional: bool,

    /// Check presence + size only, skipping the full SHA-256 re-hash (fast path).
    #[arg(long)]
    pub quick: bool,

    /// Verify an intentionally partial store projection. FILE is the same
    /// bounded `.sevralocal`-compatible list of case-sensitive store-path globs
    /// accepted by `validate --projection-excludes`. Only a matched asset may
    /// be absent; present corruption and every unmatched missing asset still
    /// fail.
    #[arg(long, value_name = "FILE", conflicts_with = "projection_manifest")]
    pub projection_excludes: Option<String>,

    /// Verify from a canonical path-confidential projection commitment
    /// manifest. FILE is store-relative; `-` reads bounded JSON from stdin.
    #[arg(long, value_name = "FILE", conflicts_with = "projection_excludes")]
    pub projection_manifest: Option<String>,
}

/// `dbmd assets status`.
#[derive(Debug, Args)]
pub struct AssetsStatusArgs {
    /// Store root. Defaults to the current directory.
    #[arg(long, value_name = "DIR", default_value = ".")]
    pub dir: String,
}

/// `dbmd assets paths`.
#[derive(Debug, Args)]
pub struct AssetsPathsArgs {
    /// Store root. Defaults to the current directory.
    #[arg(long, value_name = "DIR", default_value = ".")]
    pub dir: String,
}

// ─────────────────────────────────────────────────────────────────────────────
// The link.md client verbs (resolve / sync / grant / propose / subscribe)
//
// Shared configuration on every verb: `--hub <URL>` beats the `DBMD_HUB_URL`
// env var beats the `hub = <URL>` line in the store-local `.dbmd/config`;
// there is NO default hub (the toolkit is neutral — a hub is whatever you
// point it at). The credential is the `DBMD_HUB_KEY` env var, never a file in
// the store. Store-selected hubs require an exact
// `DBMD_HUB_CREDENTIAL_ORIGIN` binding before they receive ambient
// credentials. Non-HTTPS hubs are refused (loopback exempt).
// ─────────────────────────────────────────────────────────────────────────────

/// `dbmd resolve <ADDRESS>` — `@brain` card or `@brain/<id>` record.
#[derive(Debug, Args)]
pub struct ResolveArgs {
    /// The address: `@brain` (brain id or your slug), `@brain/<record-id>`
    /// (lowercase ULID), or `@brain/<store-path>.md`. The `@` is optional.
    #[arg(value_name = "ADDRESS")]
    pub address: String,

    /// Hub base URL for this invocation (beats `DBMD_HUB_URL` and `.dbmd/config`).
    #[arg(long, value_name = "URL")]
    pub hub: Option<String>,

    /// Directory whose `.dbmd/config` supplies the hub URL when the flag and
    /// env var are absent. Defaults to the current directory.
    #[arg(long, value_name = "DIR", default_value = ".")]
    pub dir: String,
}

/// `dbmd sync <BRAIN>` — clone a new checkout or converge an established one.
#[derive(Debug, Args)]
pub struct SyncArgs {
    /// The brain to sync with: its id (lowercase ULID) or your slug for it.
    /// A leading `@` is accepted.
    #[arg(value_name = "BRAIN")]
    pub brain: Option<String>,

    /// Resolve or prune private sync-control state.
    #[command(subcommand)]
    pub action: Option<SyncAction>,

    /// Push local changes from `--dir` without installing remote changes first.
    /// `--push-only` is the descriptive alias; `--push` remains compatible.
    #[arg(long, alias = "push-only")]
    pub push: bool,

    /// Install remote changes without sending local changes afterwards.
    #[arg(long, conflicts_with = "push")]
    pub pull_only: bool,

    /// Approve the exact local paths newly made eligible by a `.sevralocal`
    /// change. Without this flag they remain quarantined from upload.
    #[arg(long, conflicts_with = "pull_only")]
    pub resume_local_policy: bool,

    /// Confirm the exact permissioned bulk preview returned by the preceding
    /// sync attempt. The value is `<bulk_preview_id>:<bulk_preview_digest>`;
    /// changing the head, files, permissions, or principal invalidates it.
    #[arg(long, value_name = "ID:DIGEST", conflicts_with = "pull_only")]
    pub confirm_bulk: Option<String>,

    /// Remove this exact currently hosted path while preserving its local
    /// kept-home file. Repeat for multiple reviewed paths. Requires the path
    /// to be covered by `.sevralocal` and an explicit audit reason.
    #[arg(
        long,
        value_name = "PATH",
        action = clap::ArgAction::Append,
        requires = "withdraw_reason",
        conflicts_with = "pull_only"
    )]
    pub withdraw_from_hosting: Vec<String>,

    /// Bounded audit reason shared by this command's explicit withdrawals.
    #[arg(
        long,
        value_name = "REASON",
        requires = "withdraw_from_hosting",
        conflicts_with = "pull_only"
    )]
    pub withdraw_reason: Option<String>,

    /// Pull destination directory. Defaults to `./<slug>` (created if
    /// missing). Permissioned v2 applies remote changes atomically and removes
    /// only clean files whose hosted deletion matches the private baseline.
    #[arg(
        long,
        value_name = "DIR",
        conflicts_with_all = [
            "push",
            "resume_local_policy",
            "confirm_bulk",
            "withdraw_from_hosting",
            "withdraw_reason"
        ]
    )]
    pub out: Option<String>,

    /// Hub base URL for this invocation (beats `DBMD_HUB_URL` and `.dbmd/config`).
    #[arg(long, value_name = "URL")]
    pub hub: Option<String>,

    /// Store root: the push/convergence source, the pull-only destination for
    /// an established checkout, and where `.dbmd/config` is read from. Defaults
    /// to the current directory.
    #[arg(long, value_name = "DIR", default_value = ".")]
    pub dir: String,
}

#[derive(Debug, Subcommand)]
pub enum SyncAction {
    /// Replace one mutable alias binding after reviewing the exact old and new
    /// canonical brain ids. Canonical trust history is preserved.
    Rebind(SyncRebindArgs),

    /// Move the private incremental baseline after the checkout itself was
    /// atomically moved. The old checkout path must no longer exist and the
    /// new checkout must still match the verified baseline exactly.
    Relocate(SyncRelocateArgs),

    /// Resolve one exact private conflict bundle. This never acts as force.
    Resolve(SyncResolveArgs),

    /// Inspect or prune private conflict bundles.
    Conflicts(SyncConflictsArgs),
}

#[derive(Debug, Args)]
pub struct SyncRelocateArgs {
    /// Previous checkout root. It must no longer exist.
    #[arg(long, value_name = "OLD_DIR")]
    pub from: String,

    /// New checkout root containing the unchanged verified store.
    #[arg(long, value_name = "NEW_DIR")]
    pub to: String,
}

#[derive(Debug, Args)]
pub struct SyncRebindArgs {
    /// Exact canonical brain ULID currently pinned for the alias.
    #[arg(long, value_name = "OLD_BRAIN_ULID")]
    pub from: String,

    /// Exact canonical brain ULID the alias currently resolves to.
    #[arg(long, value_name = "NEW_BRAIN_ULID")]
    pub to: String,
}

#[derive(Debug, Args)]
pub struct SyncConflictsArgs {
    /// Remove expired and interrupted bundles.
    #[arg(long)]
    pub prune: bool,

    /// Also remove unexpired completed bundles. Requires `--prune`.
    #[arg(long, requires = "prune")]
    pub all: bool,

    /// Checkout containing `.dbmd/conflicts/`.
    #[arg(long, value_name = "DIR", default_value = ".")]
    pub dir: String,
}

#[derive(Debug, Args)]
pub struct SyncResolveArgs {
    /// Bundle ULID from SYNC_CONFLICT details.
    #[arg(value_name = "BUNDLE")]
    pub bundle: String,

    /// Author a fresh exact-head mutation from the unchanged working file.
    #[arg(
        long,
        required_unless_present_any = ["take_remote", "from"],
        conflicts_with_all = ["take_remote", "from"]
    )]
    pub keep_local: bool,

    /// Install the bundle's verified remote result locally.
    #[arg(long, conflicts_with = "from")]
    pub take_remote: bool,

    /// Use one bounded, no-follow UTF-8 file as the merged candidate. The
    /// bundle must contain exactly one conflicting path.
    #[arg(long, value_name = "SAFE_FILE")]
    pub from: Option<String>,

    /// Confirm an exact bulk preview returned by a preceding keep-local/from
    /// resolution attempt.
    #[arg(long, value_name = "ID:DIGEST")]
    pub confirm_bulk: Option<String>,

    /// Checkout containing `.dbmd/conflicts/<bundle>`.
    #[arg(long, value_name = "DIR", default_value = ".")]
    pub dir: String,

    /// Hub base URL for this invocation.
    #[arg(long, value_name = "URL")]
    pub hub: Option<String>,
}

/// `dbmd grant <sub>` — the capability model, owner-side.
#[derive(Debug, Args)]
pub struct GrantArgs {
    /// Which grant operation to run.
    #[command(subcommand)]
    pub command: GrantCommand,
}

/// The `dbmd grant` subcommands.
#[derive(Debug, Subcommand)]
pub enum GrantCommand {
    /// Issue (or refresh) a grant: `dbmd grant issue @brain someone@example.com
    /// --can read --scope records/clients/ --until 2026-09-01`.
    Issue(GrantIssueArgs),

    /// List the active grants (and pending invites) on a brain you own.
    List(GrantListArgs),

    /// Revoke a grant (or cancel a pending invite) by its id.
    Revoke(GrantRevokeArgs),
}

/// The two capabilities a v0 hub enforces.
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum GrantCapability {
    /// Read the granted slice.
    Read,
    /// Read and push (whole-store; a path-scoped grant is read-only).
    Write,
}

/// `dbmd grant issue <BRAIN> <GRANTEE>`.
#[derive(Debug, Args)]
pub struct GrantIssueArgs {
    /// The brain to grant on: its id or your slug (leading `@` accepted).
    #[arg(value_name = "BRAIN")]
    pub brain: String,

    /// The grantee — a hub principal named by email (v0; key-named grantees
    /// arrive with the protocol's signing layer).
    #[arg(value_name = "GRANTEE")]
    pub grantee: String,

    /// The capability to grant.
    #[arg(long, value_enum, default_value_t = GrantCapability::Read, value_name = "CAP")]
    pub can: GrantCapability,

    /// Limit the grant to a store-path prefix (e.g. `records/clients/`).
    /// A scoped grant is read-only.
    #[arg(long, value_name = "PREFIX")]
    pub scope: Option<String>,

    /// Expiry as an ISO 8601 instant or date (e.g. `2026-09-01`). Absent =
    /// until revoked.
    #[arg(long, value_name = "ISO8601")]
    pub until: Option<String>,

    /// Hub base URL for this invocation (beats `DBMD_HUB_URL` and `.dbmd/config`).
    #[arg(long, value_name = "URL")]
    pub hub: Option<String>,

    /// Directory whose `.dbmd/config` supplies the hub URL when the flag and
    /// env var are absent. Defaults to the current directory.
    #[arg(long, value_name = "DIR", default_value = ".")]
    pub dir: String,
}

/// `dbmd grant list <BRAIN>`.
#[derive(Debug, Args)]
pub struct GrantListArgs {
    /// The brain whose grants to list (id or your slug; leading `@` accepted).
    #[arg(value_name = "BRAIN")]
    pub brain: String,

    /// Hub base URL for this invocation (beats `DBMD_HUB_URL` and `.dbmd/config`).
    #[arg(long, value_name = "URL")]
    pub hub: Option<String>,

    /// Directory whose `.dbmd/config` supplies the hub URL when the flag and
    /// env var are absent. Defaults to the current directory.
    #[arg(long, value_name = "DIR", default_value = ".")]
    pub dir: String,
}

/// `dbmd grant revoke <BRAIN> <GRANT_ID>`.
#[derive(Debug, Args)]
pub struct GrantRevokeArgs {
    /// The brain the grant lives on (id or your slug; leading `@` accepted).
    #[arg(value_name = "BRAIN")]
    pub brain: String,

    /// The grant (or pending-invite) id to revoke, from `grant list`.
    #[arg(value_name = "GRANT_ID")]
    pub grant_id: String,

    /// Hub base URL for this invocation (beats `DBMD_HUB_URL` and `.dbmd/config`).
    #[arg(long, value_name = "URL")]
    pub hub: Option<String>,

    /// Directory whose `.dbmd/config` supplies the hub URL when the flag and
    /// env var are absent. Defaults to the current directory.
    #[arg(long, value_name = "DIR", default_value = ".")]
    pub dir: String,
}

/// `dbmd propose <SITE> --app <SLUG>` — evidence into a published inbox.
#[derive(Debug, Args)]
pub struct ProposeArgs {
    /// The published site handle to propose to (leading `@` accepted).
    #[arg(value_name = "SITE")]
    pub site: String,

    /// The site's app page that accepts submissions (a published page
    /// declaring the `write-inbox` capability).
    #[arg(long, value_name = "SLUG")]
    pub app: String,

    /// The submission text, inline.
    #[arg(long, value_name = "TEXT", conflicts_with = "body_file")]
    pub body: Option<String>,

    /// Read the submission text from this file (e.g. a record to propose).
    #[arg(long, value_name = "PATH")]
    pub body_file: Option<String>,

    /// Hub base URL for this invocation (beats `DBMD_HUB_URL` and `.dbmd/config`).
    #[arg(long, value_name = "URL")]
    pub hub: Option<String>,

    /// Directory whose `.dbmd/config` supplies the hub URL when the flag and
    /// env var are absent. Defaults to the current directory.
    #[arg(long, value_name = "DIR", default_value = ".")]
    pub dir: String,
}

/// `dbmd proposal <sub>` — drain a self-custodied brain's change queue.
#[derive(Debug, Args)]
pub struct ProposalArgs {
    #[command(subcommand)]
    pub command: ProposalCommand,
}

#[derive(Debug, Subcommand)]
pub enum ProposalCommand {
    /// List proposal envelopes without downloading their changed blobs.
    List(ProposalListArgs),
    /// Verify and show one proposal's canonical changeset and blob manifest.
    Show(ProposalTargetArgs),
    /// Accept the exact proposed operations against the current head and sign
    /// the independently verified candidate with `DBMD_BRAIN_KEY_FILE`.
    Accept(ProposalDecisionArgs),
    /// Reject a proposal with an auditable, idempotent reason.
    Reject(ProposalDecisionArgs),
}

#[derive(Debug, Args)]
pub struct ProposalListArgs {
    #[arg(value_name = "BRAIN")]
    pub brain: String,
    #[arg(long, default_value = "pending", value_name = "STATE")]
    pub state: String,
    #[arg(long, value_name = "CURSOR")]
    pub after: Option<String>,
    #[arg(long, default_value_t = 50, value_name = "N")]
    pub limit: usize,
    #[arg(long, value_name = "URL")]
    pub hub: Option<String>,
    #[arg(long, value_name = "DIR", default_value = ".")]
    pub dir: String,
}

#[derive(Debug, Args)]
pub struct ProposalTargetArgs {
    #[arg(value_name = "BRAIN")]
    pub brain: String,
    #[arg(value_name = "PROPOSAL_ID")]
    pub proposal_id: String,
    #[arg(long, value_name = "URL")]
    pub hub: Option<String>,
    #[arg(long, value_name = "DIR", default_value = ".")]
    pub dir: String,
}

#[derive(Debug, Args)]
pub struct ProposalDecisionArgs {
    #[arg(value_name = "BRAIN")]
    pub brain: String,
    #[arg(value_name = "PROPOSAL_ID")]
    pub proposal_id: String,
    /// Stable idempotency key. Reuse it only when retrying the same decision.
    #[arg(long, value_name = "ID")]
    pub mutation_id: String,
    #[arg(long, value_name = "TEXT")]
    pub reason: String,
    #[arg(long, value_name = "URL")]
    pub hub: Option<String>,
    #[arg(long, value_name = "DIR", default_value = ".")]
    pub dir: String,
}

/// `dbmd subscribe <BRAIN>` — follow the feed head.
#[derive(Debug, Args)]
pub struct SubscribeArgs {
    /// The brain to follow: its id or your slug (leading `@` accepted).
    #[arg(value_name = "BRAIN")]
    pub brain: String,

    /// Baseline sequence: emit an event only when the head moves past this.
    /// Defaults to the head observed on the first poll.
    #[arg(long, value_name = "SEQ")]
    pub since: Option<u64>,

    /// Seconds between polls (the hub serves head reads cheaply; stay
    /// polite). Minimum 1.
    #[arg(long, value_name = "SECS", default_value_t = 30)]
    pub interval: u64,

    /// Read the current head once, report it, and exit (no loop).
    #[arg(long)]
    pub once: bool,

    /// Hub base URL for this invocation (beats `DBMD_HUB_URL` and `.dbmd/config`).
    #[arg(long, value_name = "URL")]
    pub hub: Option<String>,

    /// Directory whose `.dbmd/config` supplies the hub URL when the flag and
    /// env var are absent. Defaults to the current directory.
    #[arg(long, value_name = "DIR", default_value = ".")]
    pub dir: String,
}

// (install-skill / uninstall-skill removed: the installer is text — `dbmd spec`
// + the repo-root `llms.txt` + the distributable `skills/db-md/SKILL.md`. Agents
// and harness skill-installers place the skill; dbmd ships no per-harness code.)

/// `dbmd key <sub>` — agent signing keys (link.md §8).
#[derive(Debug, Args)]
pub struct KeyArgs {
    /// Which key operation to run.
    #[command(subcommand)]
    pub command: KeyCommand,
}

/// The `dbmd key` subcommands.
#[derive(Debug, Subcommand)]
pub enum KeyCommand {
    /// Mint a fresh Ed25519 agent keypair: the PKCS#8 secret is written to
    /// `--out` (one base64url line, mode 0600, never overwriting), and the
    /// public identity (`multikey` + `publicKeySpki`) is printed for hub
    /// registration.
    Generate(KeyGenerateArgs),

    /// Rotate a self-custodied brain's key (link.md §9.1): mint a fresh
    /// keypair and durably write it to `--out` BEFORE asking the hub to commit
    /// its public half, then sign with the OLD key and re-verify the committed
    /// feed. An existing `--out` is reused after an ambiguous failure. History
    /// keeps verifying; retain the old key as recovery material.
    Rotate(KeyRotateArgs),
}

/// `dbmd key generate --out <FILE>`.
#[derive(Debug, Args)]
pub struct KeyGenerateArgs {
    /// Where to write the private key file (e.g. `~/.config/dbmd/agent.key`).
    #[arg(long, value_name = "FILE")]
    pub out: String,
}

/// `dbmd mirror <BRAIN> --dir <DIR>`.
#[derive(Debug, Args)]
pub struct MirrorArgs {
    /// The brain to mirror: its id (lowercase ULID) or your slug for it
    /// (leading `@` accepted).
    #[arg(value_name = "BRAIN")]
    pub brain: String,

    /// Where to materialize the mirror (created if absent).
    #[arg(long, value_name = "DIR")]
    pub dir: String,
}

/// `dbmd serve --dir <DIR> [--addr 127.0.0.1:0]`.
#[derive(Debug, Args)]
pub struct ServeArgs {
    /// The mirrored directory to serve (must contain `.dbmd/mirror/`).
    #[arg(long, value_name = "DIR", default_value = ".")]
    pub dir: String,

    /// Trusted Ed25519 anchor printed by `dbmd mirror`. This must come from the
    /// operator or another trusted checkpoint, not from files inside the mirror.
    #[arg(long, value_name = "ED25519:MULTIKEY")]
    pub pin: String,

    /// The address to bind. Loopback by default; port 0 picks a free port.
    #[arg(long, value_name = "ADDR", default_value = "127.0.0.1:0")]
    pub addr: String,

    /// Permit binding outside loopback. This exposes the full mirrored store
    /// without authentication; use only behind an authenticated reverse proxy.
    #[arg(long)]
    pub unsafe_public: bool,
}

/// `dbmd key rotate <BRAIN> --key-file <OLD> --out <NEW>`.
#[derive(Debug, Args)]
pub struct KeyRotateArgs {
    /// The brain to rotate: its id or your slug (leading `@` accepted).
    #[arg(value_name = "BRAIN")]
    pub brain: String,

    /// The CURRENT brain key file (what signs the rotation statement).
    #[arg(long, value_name = "FILE")]
    pub key_file: String,

    /// Durable home for the NEW private key (0600). It is created before the
    /// hub mutation and reused unchanged for safe retry/reconciliation.
    #[arg(long, value_name = "FILE")]
    pub out: String,
}

#[cfg(test)]
mod tests {
    use super::*;

    const OLD: &str = "01j5qc3v9k4ym8rwbn2tqe6f7d";
    const NEW: &str = "01j5qc3v9k4ym8rwbn2tqe6f7e";

    #[test]
    fn sync_parses_exact_withdrawal_intent_and_reason() {
        let cli = Cli::try_parse_from([
            "dbmd",
            "sync",
            "company",
            "--push",
            "--withdraw-from-hosting",
            "sources/private/a.md",
            "--withdraw-from-hosting",
            "assets/private.pdf",
            "--withdraw-reason",
            "approved retention change",
        ])
        .unwrap();
        let Command::Sync(args) = cli.command else {
            panic!("expected sync");
        };
        assert_eq!(
            args.withdraw_from_hosting,
            ["sources/private/a.md", "assets/private.pdf"]
        );
        assert_eq!(
            args.withdraw_reason.as_deref(),
            Some("approved retention change")
        );
    }

    #[test]
    fn sync_withdrawal_requires_a_reason() {
        assert!(Cli::try_parse_from([
            "dbmd",
            "sync",
            "company",
            "--withdraw-from-hosting",
            "sources/private/a.md",
        ])
        .is_err());
    }

    #[test]
    fn sync_parses_the_fail_closed_alias_rebind_shape() {
        let cli = Cli::try_parse_from([
            "dbmd", "sync", "company", "rebind", "--from", OLD, "--to", NEW,
        ])
        .unwrap();
        let Command::Sync(args) = cli.command else {
            panic!("expected sync");
        };
        let Some(SyncAction::Rebind(rebind)) = args.action else {
            panic!("expected rebind");
        };
        assert_eq!(rebind.from, OLD);
        assert_eq!(rebind.to, NEW);
    }

    #[test]
    fn sync_parses_the_checkout_relocation_shape() {
        let cli = Cli::try_parse_from([
            "dbmd",
            "sync",
            OLD,
            "relocate",
            "--from",
            "/tmp/stage/db",
            "--to",
            "/tmp/live/db",
        ])
        .unwrap();
        let Command::Sync(args) = cli.command else {
            panic!("expected sync");
        };
        let Some(SyncAction::Relocate(relocate)) = args.action else {
            panic!("expected relocate");
        };
        assert_eq!(relocate.from, "/tmp/stage/db");
        assert_eq!(relocate.to, "/tmp/live/db");
    }
}