str-format 0.10.0

STR 结构化树资源格式(.str)的读写库、校验器与 CLI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
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
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
//! CLI 子命令实现(规范第 9 章)。

use std::path::{Path, PathBuf};

use serde_json::Value as JValue;

use crate::bundle::{Bundle, Scan};
use crate::error::{Error, Result, code};
use crate::meta::{Author, Entry, Kind, Meta, MetaLoad, RefItem};
use crate::meta_edit::{meta_from_text, render_branch_meta, render_root_meta, toml_str};
use crate::util::{self, SCHEMA_DIR};
use crate::{SPEC_VERSION, STR_MAJOR};

// ─────────────────────────── 公共辅助 ───────────────────────────

/// 打开 bundle:`<dir>` 可为 bundle 根,也可为其内部的分支/内容目录。
///
/// 解析规则(见 [`bundle_root_of`]):向上找到真正持有这份 bundle 的根目录再整体扫描 ——
/// 因此 `str <cmd> <bundle>/<分支>` 与在分支目录内执行 `str <cmd>` 等价,
/// `[uuid]` 的缺省目标随之成为「当前节点」(见 [`target_branch`])。
pub fn open(dir: &Path) -> Result<Bundle> {
    Bundle::new(bundle_root_of(dir)?)
}

/// 从 `<dir>` 向上解析 bundle 根:停在**第一个**满足下列条件之一的目录(含自身)——
///
/// 1. 目录名以 `.str` 结尾(规范 §3.5:`.str` 目录是 bundle 硬边界);
/// 2. 其父目录不含 `.str.toml`(元数据链顶端;兼容无 `.str` 后缀的 bundle 与文件系统根)。
///
/// 由此子 bundle 边界不会被向上穿越(`examples/客户运营.str` 内部解析到它自身为止)。
fn bundle_root_of(dir: &Path) -> Result<PathBuf> {
    let mut cur = std::fs::canonicalize(dir).map_err(|e| Error::io(dir, e))?;
    loop {
        let name = cur
            .file_name()
            .map(|s| s.to_string_lossy().to_string())
            .unwrap_or_default();
        let parent_has_meta = cur
            .parent()
            .map(|p| p.join(util::META_FILE).is_file())
            .unwrap_or(false);
        if name.ends_with(".str") || !parent_has_meta {
            return Ok(cur);
        }
        match cur.parent() {
            Some(p) => cur = p.to_path_buf(),
            None => return Ok(cur),
        }
    }
}

/// 定位某 uuid 对应的 visit 下标。
pub fn locate(scan: &Scan, uuid: &str) -> Option<usize> {
    scan.resolve(uuid)
}

/// 依据扩展名猜测媒体类型。
pub fn media_type_for(name: &str) -> Option<String> {
    let ext = Path::new(name)
        .extension()
        .map(|s| s.to_string_lossy().to_lowercase())
        .unwrap_or_default();
    let s = match ext.as_str() {
        "json" => "application/json",
        "toml" => "application/toml",
        "md" => "text/markdown",
        "txt" => "text/plain",
        "csv" => "text/csv",
        "yaml" | "yml" => "application/yaml",
        "png" => "image/png",
        "jpg" | "jpeg" => "image/jpeg",
        "gif" => "image/gif",
        "webp" => "image/webp",
        "svg" => "image/svg+xml",
        "pdf" => "application/pdf",
        "zip" => "application/zip",
        _ => return None,
    };
    Some(s.to_string())
}

/// 目录直接子项数(排除 `.str.toml`)。
fn child_count(dir: &Path) -> Option<i64> {
    crate::validate::dir_child_count(dir)
}

// ─────────────────────────── init ───────────────────────────

/// 创建一个新的 `.str` bundle。
pub fn init(
    dir: &Path,
    name: Option<String>,
    title: Option<String>,
    summary: Option<String>,
    id_version: usize,
) -> Result<()> {
    if !matches!(id_version, 4 | 7) {
        return Err(Error::BadArg(format!(
            "`--id-version` = {id_version} 不受支持(`policies.id_version` 只允许 4 或 7)"
        )));
    }
    let target = if dir.extension().map(|e| e == "str").unwrap_or(false) {
        dir.to_path_buf()
    } else {
        PathBuf::from(format!("{}.str", dir.display()))
    };
    if target.exists() {
        return Err(Error::BadArg(format!("{} 已存在", target.display())));
    }
    let bundle_name = name.clone().unwrap_or_else(|| {
        target
            .file_stem()
            .map(|s| s.to_string_lossy().to_string())
            .unwrap_or_else(|| "bundle".to_string())
    });

    std::fs::create_dir_all(target.join(SCHEMA_DIR)).map_err(|e| Error::io(&target, e))?;
    for (file, body) in crate::EMBEDDED_SCHEMAS {
        let p = target.join(SCHEMA_DIR).join(file);
        std::fs::write(&p, body).map_err(|e| Error::io(&p, e))?;
    }

    let created = util::now_rfc3339();
    let root_id = util::new_uuid(id_version);
    let text = render_root_meta(
        &bundle_name,
        title.as_deref(),
        summary.as_deref(),
        &root_id,
        &created,
        id_version,
    );
    let meta = meta_from_text(&text)?;
    let meta_path = target.join(util::META_FILE);
    meta.save(&meta_path)?;

    println!("已创建 bundle:{}", target.display());
    println!("  spec = {SPEC_VERSION}  str = {STR_MAJOR}");
    println!("  policies.id_version = {id_version}");
    println!(
        "  {} 内已写入 {} 份校验 Schema",
        SCHEMA_DIR,
        crate::EMBEDDED_SCHEMAS.len()
    );
    Ok(())
}

/// ROOT `policies.id_version`(缺省 7)—— 生成端必须产出同版本的 UUID,否则 `E_ID_VERSION`。
fn root_id_version(bundle: &Bundle) -> usize {
    match bundle.read_meta(&bundle.root) {
        Ok(MetaLoad::Ok(m, _)) => m.policies.id_version,
        _ => 7,
    }
}

/// 写回一份 `.str.toml` 并登记 `E_REVISION_STALE` 的历史基线(见 [`crate::baseline`])。
fn save_meta(bundle: &Bundle, dir: &Path, meta: &Meta) -> Result<()> {
    meta.save(&bundle.meta_path(dir))?;
    crate::baseline::record(bundle, dir, meta);
    Ok(())
}

/// 取目标分支下标:给了 `uuid` 就解析;缺省目标为**当前节点**。
///
/// 规范 §9(v1.11.0 起):`[uuid]` 省略时,`[dir]` 为 bundle 根即 ROOT,
/// `[dir]` 指向 bundle 内部时为其所属分支(`<dir>` 本身或最近含 `.str.toml` 的祖先)。
/// 本函数是这条规则的唯一实现点 —— 新增命令时复用它,不要各自内联缺省逻辑。
fn target_branch(bundle: &Bundle, scan: &Scan, dir: &Path, uuid: Option<&str>) -> Result<usize> {
    match uuid {
        Some(u) => {
            locate(scan, u).ok_or_else(|| Error::BadArg(format!("找不到分支 id `{u}`")))
        }
        None => {
            let mut probe = std::fs::canonicalize(dir).map_err(|e| Error::io(dir, e))?;
            loop {
                if let Some(i) = scan.visits.iter().position(|v| v.dir == probe) {
                    return Ok(i);
                }
                match probe.parent() {
                    // `probe` 已到 bundle 根仍无 visit(根缺 `.str.toml`)→ 交由 root_index 报因
                    Some(p) if probe != bundle.root => probe = p.to_path_buf(),
                    _ => {
                        return scan
                            .root_index
                            .ok_or_else(|| Error::BadArg("bundle 缺少 `.str.toml`".into()));
                    }
                }
            }
        }
    }
}

/// `--out` 的统一出口:缺省或 `-` 走 stdout,其余路径写文件。
fn emit(text: &str, out: Option<&str>) -> Result<()> {
    match out {
        None | Some("-") => {
            print!("{text}");
            Ok(())
        }
        Some(p) => std::fs::write(p, text).map_err(|e| Error::io(p, e)),
    }
}

/// `str export` 的产物是派生数据,**不得**写回 bundle 内部(规范 §9)。
///
/// 比较前把目标路径的**最深已存在祖先**也 canonicalize:否则 `Bundle::new` 归一化过的
/// 根路径与未归一化的 `--out`(macOS `/var` → `/private/var` 这类符号链接)会对不上,
/// 判定形同虚设。
fn resolve_out_path(bundle: &Bundle, out: &str) -> Result<PathBuf> {
    let p = abs(out);
    let probe = match p.parent() {
        Some(dir) => canonical_ancestor(dir),
        None => p.clone(),
    };
    if probe.starts_with(&bundle.root) {
        return Err(Error::BadArg(format!(
            "`--out` 不得指向 bundle 内部({} 在 {} 内):export 的产物是派生数据",
            p.display(),
            bundle.root.display()
        )));
    }
    Ok(p)
}

/// `dir` 的最深已存在祖先(canonicalize 后);一层都不存在时原样返回。
fn canonical_ancestor(dir: &Path) -> PathBuf {
    let mut cur = dir.to_path_buf();
    loop {
        if let Ok(resolved) = std::fs::canonicalize(&cur) {
            return resolved;
        }
        match cur.parent() {
            Some(parent) if parent != cur => cur = parent.to_path_buf(),
            _ => return dir.to_path_buf(),
        }
    }
}

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

/// 校验整个 bundle。
pub fn validate(dir: &Path, strict: bool, json: bool, fix_manifest: bool) -> Result<i32> {
    let bundle = open(dir)?;
    if fix_manifest {
        // 规范 §9:`--fix-manifest` 是「校验前先修正清单」——必须**真正写盘**。
        // 属显式修复意图,豁免 sync 的批量删除门禁(软连接条目本就不在对账范围)。
        sync(dir, false, true)?;
    }
    let mut report = crate::validate::validate(&bundle)?;
    if strict {
        // `--strict`:把告警也视为失败(CI 用)
        for i in &mut report.issues {
            if i.level == crate::error::Level::Warn {
                i.level = crate::error::Level::Error;
            }
        }
    }
    if json {
        println!(
            "{}",
            serde_json::to_string_pretty(&report.to_json()).unwrap_or_default()
        );
    } else {
        println!("{}", report.to_text());
    }
    Ok(report.exit_code())
}

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

/// 渲染分支树(含 `refs` 关联线)。
pub fn tree(
    dir: &Path,
    max_depth: Option<usize>,
    show_refs: bool,
    show_entries: bool,
    ascii: bool,
) -> Result<()> {
    let bundle = open(dir)?;
    let scan = bundle.scan()?;
    let Some(ri) = scan.root_index else {
        println!("(缺少 `.str.toml`,无法渲染)");
        return Ok(());
    };
    // 根节点与子节点同样式:`[0] 标题  (type)`;根无 `type` 时以档位 `root` 兜底。
    let v = &scan.visits[ri];
    match v.meta.as_ref() {
        Some(m) => {
            let title = m
                .title
                .clone()
                .or_else(|| m.name.clone())
                .unwrap_or_else(|| bundle.name());
            let kind_label = m.r#type.clone().unwrap_or_else(|| "root".to_string());
            let mut line = format!("[0] {title}  ({kind_label})");
            if !v.readable {
                line.push_str("  ! 解析失败");
            }
            println!("{line}");
        }
        None => println!("[0] {}  ! 解析失败", bundle.name()),
    }
    if show_entries {
        render_entries(&scan, ri, "  ");
    }
    render_children(&scan, ri, "", max_depth, show_refs, show_entries, ascii);
    Ok(())
}

/// 渲染某分支的内容清单(`entries[]`,保持落盘次序;`node` / `branch` 结构行由树本身呈现,跳过)。
fn render_entries(scan: &Scan, idx: usize, prefix: &str) {
    let Some(meta) = scan.visits[idx].meta.as_ref() else {
        return;
    };
    for e in &meta.entries {
        if e.role == "node" || e.role == "branch" {
            continue;
        }
        let mut line = format!("{prefix}· {}  ({})", e.path, e.role);
        if let Some(t) = &e.title {
            line.push_str(&format!("  {t}"));
        }
        if let Some(s) = e.size {
            line.push_str(&format!("  {s}B"));
        }
        println!("{line}");
    }
}

/// 树形符号:`(false)` 为 Unicode 制表符,`(true)` 为纯 ASCII(`--ascii`)。
fn marks(ascii: bool) -> (&'static str, &'static str, &'static str, &'static str) {
    if ascii {
        ("|-- ", "`-- ", "|   ", "    ")
    } else {
        ("├─ ", "└─ ", "│  ", "   ")
    }
}

/// 子分支下标,顺序取父级 `entries[]` 的 `(order, path)`(规范 §4.6:`order` 为同层排序键)。
///
/// 与 §4.9 的落盘顺序同源,因此 `str tree` 的次序与 `.str.toml` 中的条目次序一致。
fn ordered_children(scan: &Scan, idx: usize) -> Vec<usize> {
    let parent = scan.visits[idx].meta.as_ref();
    let mut children: Vec<(i64, String, usize)> = Vec::new();
    for (i, v) in scan.visits.iter().enumerate() {
        if v.parent != Some(idx) {
            continue;
        }
        let name = v
            .dir
            .file_name()
            .map(|s| s.to_string_lossy().to_string())
            .unwrap_or_default();
        let order = parent
            .and_then(|m| m.entries.iter().find(|e| e.path == name))
            .and_then(|e| e.order)
            .unwrap_or(i64::MAX);
        children.push((order, name, i));
    }
    children.sort_by(|a, b| (a.0, &a.1).cmp(&(b.0, &b.1)));
    children.into_iter().map(|(_, _, i)| i).collect()
}

fn render_children(
    scan: &Scan,
    idx: usize,
    prefix: &str,
    max_depth: Option<usize>,
    show_refs: bool,
    show_entries: bool,
    ascii: bool,
) {
    let Some(meta) = scan.visits[idx].meta.as_ref() else {
        return;
    };
    let children = ordered_children(scan, idx);
    let (mid, last_mark, pipe, blank) = marks(ascii);
    if show_refs {
        let arrow = if ascii { "->" } else { "⇢" };
        for r in &meta.refs {
            let target = scan
                .resolve(&r.target)
                .map(|i| scan.visits[i].rel.clone())
                .unwrap_or_else(|| format!("{}(未解析)", r.target));
            println!("{prefix}{arrow} 关联: {target}  --{}--", r.rel);
        }
    }
    for (n, ci) in children.iter().enumerate() {
        let last = n + 1 == children.len();
        let v = &scan.visits[*ci];
        let (title, type_) = match v.meta.as_ref() {
            Some(m) => (
                m.title.clone().unwrap_or_default(),
                m.r#type.clone().unwrap_or_default(),
            ),
            None => (String::new(), String::new()),
        };
        let mark = if last { last_mark } else { mid };
        let mut line = format!("{prefix}{mark}[{}] {}", n + 1, title);
        if !type_.is_empty() {
            line.push_str(&format!("  ({type_})"));
        }
        if v.meta.is_none() {
            line.push_str("  ! 解析失败");
        }
        println!("{line}");
        let next_prefix = format!("{prefix}{}", if last { blank } else { pipe });
        if show_entries {
            render_entries(scan, *ci, &next_prefix);
        }
        if max_depth.map(|d| v.depth < d).unwrap_or(true) {
            render_children(scan, *ci, &next_prefix, max_depth, show_refs, show_entries, ascii);
        }
    }
}

// ─────────────────────────── ls / show ───────────────────────────

/// 列出某分支的清单(读 `.str.toml`)或磁盘原始内容。
pub fn ls(dir: &Path, uuid: Option<String>, raw: bool) -> Result<()> {
    let bundle = open(dir)?;
    let scan = bundle.scan()?;
    let idx = target_branch(&bundle, &scan, dir, uuid.as_deref())?;
    let v = &scan.visits[idx];
    println!("{}  ({})", v.rel, if raw { "磁盘原始" } else { "清单" });
    if raw {
        for (name, is_dir) in bundle.list_names(&v.dir)? {
            if util::is_meta_file(&name) {
                continue;
            }
            println!("  {}{}", if is_dir { "d " } else { "- " }, name);
        }
        return Ok(());
    }
    let Some(meta) = v.meta.as_ref() else {
        println!("  (`.str.toml` 解析失败)");
        return Ok(());
    };
    for e in &meta.entries {
        let mut line = format!("  {:<28} {}", e.path, e.role);
        if let Some(t) = &e.title {
            line.push_str(&format!("  {t}"));
        }
        if let Some(s) = e.size {
            line.push_str(&format!("  {s}B"));
        }
        if e.optional {
            line.push_str("  (optional)");
        }
        println!("{line}");
    }
    Ok(())
}

/// 打印某分支的 `.str.toml`(归一化 JSON)。(规范 §9:`<UUID>` 缺省为当前节点。)
pub fn show(dir: &Path, uuid: Option<String>, full: bool) -> Result<()> {
    let bundle = open(dir)?;
    let scan = bundle.scan()?;
    let idx = target_branch(&bundle, &scan, dir, uuid.as_deref())?;
    let v = &scan.visits[idx];
    let Some(meta) = v.meta.as_ref() else {
        return Err(Error::BadArg(format!("{} 的 `.str.toml` 解析失败", v.rel)));
    };
    println!(
        "{}",
        serde_json::to_string_pretty(&meta.to_json()).unwrap_or_default()
    );
    if full {
        for e in &meta.entries {
            if (e.role == "payload" || e.role == "asset") && !e.path.is_empty() {
                let p = v.dir.join(&e.path);
                if let Ok(text) = std::fs::read_to_string(&p) {
                    println!("\n── {} ──\n{}", e.path, text);
                }
            }
        }
    }
    Ok(())
}

// ─────────────────────────── node / branch ───────────────────────────

/// 新增独立节点(深度 1,只能登记在 ROOT 下)。
pub fn node_add(
    dir: &Path,
    type_: Option<String>,
    title: Option<String>,
    summary: Option<String>,
) -> Result<()> {
    let bundle = open(dir)?;
    // `[dir]` 指向分支/内容目录时明确拒绝 —— 独立节点只能挂在 ROOT,避免「在分支里
    // 执行 node add 却把节点加到了 ROOT」的静默意外(规范 §9:拒绝必须带原因)。
    let cur = std::fs::canonicalize(dir).map_err(|e| Error::io(dir, e))?;
    if cur != bundle.root {
        return Err(Error::BadArg(
            "当前目录不是 bundle 根:`node add` 只能向 ROOT 新增深度 1 的独立节点;\
             在分支下新增请改用 `branch add`"
                .into(),
        ));
    }
    let root = match bundle.read_meta(&bundle.root)? {
        MetaLoad::Ok(m, _) => m,
        MetaLoad::Failed(_) => {
            return Err(Error::BadArg("root `.str.toml` 解析失败,无法新增节点".into()));
        }
    };
    if root.kind != Some(Kind::Root) {
        return Err(Error::BadArg("root `.str.toml` 的 kind 不是 root".into()));
    }
    let id = util::new_uuid(root.policies.id_version);
    let created = util::now_rfc3339();
    let child_dir = bundle.root.join(&id);
    std::fs::create_dir_all(&child_dir).map_err(|e| Error::io(&child_dir, e))?;
    let text = render_branch_meta(
        Kind::Node,
        &id,
        type_.as_deref(),
        title.as_deref(),
        summary.as_deref(),
        &created,
    );
    let child = meta_from_text(&text)?;
    save_meta(&bundle, &child_dir, &child)?;

    let mut root = root;
    let order = root
        .entries
        .iter()
        .filter(|e| e.role == "node")
        .filter_map(|e| e.order)
        .max()
        .unwrap_or(0)
        + 1;
    let entry = Entry {
        path: id.clone(),
        role: "node".into(),
        id: Some(id.clone()),
        r#type: type_,
        title,
        summary,
        order: Some(order),
        ..Default::default()
    };
    root.upsert_entry(&entry);
    root.sort_collections();
    root.touch();
    save_meta(&bundle, &bundle.root, &root)?;
    println!("已新增独立节点 {id}(深度 1)");
    Ok(())
}

/// 在指定分支下新增关联分支(任意深度)。
///
/// 规范 §9:`<ANCHOR-UUID>` 缺省为**当前节点**(`[dir]` 即 bundle 根时为 ROOT);但真 ROOT 的
/// 直接子分支是 `node` 而非 `branch`,因此缺省/显式落到真 ROOT 时由下方的深度判据拒绝并指引到
/// `str node add`。
pub fn branch_add(
    dir: &Path,
    anchor: Option<String>,
    type_: Option<String>,
    title: Option<String>,
    summary: Option<String>,
    order: Option<i64>,
) -> Result<()> {
    let bundle = open(dir)?;
    let scan = bundle.scan()?;
    let idx = target_branch(&bundle, &scan, dir, anchor.as_deref())?;
    if scan.visits[idx].depth == 0 {
        return Err(Error::BadArg(
            "ROOT 的直接子分支应使用 `str node add`(role = node);\
             `branch add` 的锚点须是深度 ≥ 1 的分支"
                .into(),
        ));
    }
    let anchor_dir = scan.visits[idx].dir.clone();
    let mut parent = match bundle.read_meta(&anchor_dir)? {
        MetaLoad::Ok(m, _) => m,
        MetaLoad::Failed(_) => return Err(Error::BadArg("锚点 `.str.toml` 解析失败".into())),
    };

    let id = util::new_uuid(root_id_version(&bundle));
    let created = util::now_rfc3339();
    let child_dir = anchor_dir.join(&id);
    std::fs::create_dir_all(&child_dir).map_err(|e| Error::io(&child_dir, e))?;
    let text = render_branch_meta(
        Kind::Branch,
        &id,
        type_.as_deref(),
        title.as_deref(),
        summary.as_deref(),
        &created,
    );
    let child = meta_from_text(&text)?;
    save_meta(&bundle, &child_dir, &child)?;

    let order = order.unwrap_or_else(|| {
        parent
            .entries
            .iter()
            .filter(|e| e.is_branch())
            .filter_map(|e| e.order)
            .max()
            .unwrap_or(0)
            + 1
    });
    let entry = Entry {
        path: id.clone(),
        role: "branch".into(),
        id: Some(id.clone()),
        r#type: type_,
        title,
        summary,
        order: Some(order),
        ..Default::default()
    };
    parent.upsert_entry(&entry);
    parent.sort_collections();
    parent.touch();
    save_meta(&bundle, &anchor_dir, &parent)?;
    println!("已在 {} 下新增关联分支 {id}(深度 {})", scan.visits[idx].rel, scan.visits[idx].depth + 1);
    Ok(())
}

/// 删除关联分支(含其全部下级)。
///
/// 规范 §9:`<UUID>` 缺省为**当前节点** —— `[dir]` 指向某分支目录时即删除该分支本身
/// (父级 `entries[]` 由全树扫描修复);`[dir]` 为 bundle 根时目标为 ROOT,而 ROOT 不可删除,
/// 故缺省调用会得到明确拒绝(而不是靠「参数缺失」这种不含原因的错误挡住)。
pub fn branch_rm(dir: &Path, uuid: Option<String>, force: bool) -> Result<()> {
    let bundle = open(dir)?;
    let scan = bundle.scan()?;
    let idx = target_branch(&bundle, &scan, dir, uuid.as_deref())?;
    let v = &scan.visits[idx];
    if v.depth == 0 {
        return Err(Error::BadArg(
            "不能删除 ROOT(`[dir]` 为 bundle 根时 `<UUID>` 缺省即 ROOT;\
             要删除某个分支,把 `[dir]` 指向它或显式给出其 id)"
                .into(),
        ));
    }
    if !force {
        return Err(Error::BadArg(format!(
            "删除 {} 会移除其全部下级,请加 `--force` 确认",
            v.rel
        )));
    }
    let target = v.dir.clone();
    let rel = v.rel.clone();
    let parent_idx = v.parent;
    // 规范 §4.6.1 规则 6:删除真身 MUST 一并摘除全 bundle 内指向它的软连接
    // (含其全部后代),不得留下悬空。必须在删目录**之前**算好目标集合。
    let prefix = format!("{}/", v.rel);
    let doomed: std::collections::HashSet<String> = scan
        .visits
        .iter()
        .filter(|x| x.rel == v.rel || x.rel.starts_with(&prefix))
        .filter_map(|x| x.meta.as_ref()?.id.clone())
        .collect();
    let purged = purge_links_to(&bundle, &scan, &doomed)?;
    std::fs::remove_dir_all(&target).map_err(|e| Error::io(&target, e))?;

    if let Some(pi) = parent_idx {
        let parent_dir = scan.visits[pi].dir.clone();
        let name = target
            .file_name()
            .map(|s| s.to_string_lossy().to_string())
            .unwrap_or_default();
        let mut parent = match bundle.read_meta(&parent_dir)? {
            MetaLoad::Ok(m, _) => m,
            MetaLoad::Failed(_) => return Ok(()),
        };
        parent.remove_entry_path(&name);
        parent.touch();
        save_meta(&bundle, &parent_dir, &parent)?;
    }
    // 重扫一遍以丢弃被删分支的基线条目(否则 `E_REVISION_STALE` 基线会残留)
    if let Ok(after) = bundle.scan() {
        crate::baseline::record_scan(&bundle, &after);
    }
    if purged == 0 {
        println!("已删除 {rel}");
    } else {
        println!("已删除 {rel}(并移除 {purged} 条指向它的软连接)");
    }
    Ok(())
}

/// 摘除全 bundle 内指向 `doomed` 中任一分支 id 的软连接(删除真身时的收尾)。
fn purge_links_to(
    bundle: &Bundle,
    scan: &Scan,
    doomed: &std::collections::HashSet<String>,
) -> Result<usize> {
    let mut removed = 0usize;
    for v in &scan.visits {
        let Some(meta) = v.meta.as_ref() else {
            continue;
        };
        let hits: Vec<String> = meta
            .entries
            .iter()
            .filter(|e| e.is_link() && e.target.as_deref().is_some_and(|t| doomed.contains(t)))
            .map(|e| e.path.clone())
            .collect();
        if hits.is_empty() {
            continue;
        }
        let mut m = match bundle.read_meta(&v.dir)? {
            MetaLoad::Ok(m, _) => m,
            MetaLoad::Failed(_) => continue,
        };
        for p in &hits {
            m.remove_entry_path(p);
        }
        m.touch();
        save_meta(bundle, &v.dir, &m)?;
        removed += hits.len();
    }
    Ok(removed)
}

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

/// 软连接成环预检(与 `check_link_cycles` 同源):图的边集 = 真实父子边 ∪ 挂载边,
/// 从 dst 出发能回到 src 即成环 —— 「挂进自己的祖先」因此而按环拒绝。
fn link_would_cycle(scan: &Scan, src: usize, dst: usize) -> bool {
    if src == dst {
        return true;
    }
    let mut out_edges: Vec<Vec<usize>> = vec![Vec::new(); scan.visits.len()];
    for (i, v) in scan.visits.iter().enumerate() {
        if let Some(p) = v.parent {
            out_edges[p].push(i);
        }
        if let Some(meta) = v.meta.as_ref() {
            for e in &meta.entries {
                if !e.is_link() {
                    continue;
                }
                if let Some(t) = &e.target {
                    if let Some(j) = scan.resolve(t) {
                        out_edges[i].push(j);
                    }
                }
            }
        }
    }
    let mut stack = vec![dst];
    let mut seen: std::collections::HashSet<usize> = std::collections::HashSet::new();
    while let Some(i) = stack.pop() {
        if i == src {
            return true;
        }
        if !seen.insert(i) {
            continue;
        }
        if let Some(next) = out_edges.get(i) {
            stack.extend(next.iter().copied());
        }
    }
    false
}

/// 挂载一个链接子分支(规范 §4.6.1):`role = "link"` + `target`,磁盘不新建任何东西。
/// `mode = "soft"`(缺省,目标完整视图)|`"hard"`(仅内容关联、只读)。
pub fn link_add(
    dir: &Path,
    uuid: Option<String>,
    target: &str,
    mode: &str,
    title: Option<String>,
    order: Option<i64>,
    note: Option<String>,
) -> Result<()> {
    if mode != "soft" && mode != "hard" {
        return Err(Error::BadArg(format!(
            "`mode` = {mode:?} 非法(只允许 \"soft\" / \"hard\")"
        )));
    }
    let bundle = open(dir)?;
    let scan = bundle.scan()?;
    let idx = target_branch(&bundle, &scan, dir, uuid.as_deref())?;
    let dst = locate(&scan, target)
        .ok_or_else(|| Error::BadArg(format!("找不到目标分支 id `{target}`")))?;
    if scan.visits[dst].depth == 0 {
        return Err(Error::BadArg(
            "链接的目标不得是 ROOT(可挂载对象只有 `node` / `branch`)".into(),
        ));
    }
    if scan.by_id.get(target).map(|v| v.len()).unwrap_or(0) > 1 {
        return Err(Error::BadArg(format!(
            "目标 id 在多个分支上重复,无法唯一指向:{target}"
        )));
    }
    if link_would_cycle(&scan, idx, dst) {
        return Err(Error::BadArg(
            "该挂载会让挂载图成环(沿已挂载链可回到本分支)".into(),
        ));
    }
    let src_dir = scan.visits[idx].dir.clone();
    let mut meta = match bundle.read_meta(&src_dir)? {
        MetaLoad::Ok(m, _) => m,
        MetaLoad::Failed(_) => return Err(Error::BadArg("源分支 `.str.toml` 解析失败".into())),
    };
    if mode == "soft"
        && meta
            .entries
            .iter()
            .any(|e| e.is_link() && e.path == target)
    {
        return Err(Error::BadArg(format!("本分支下已挂载目标 `{target}`")));
    }
    // 硬链接 = 有身份的真实分支:`path` = `id` = 自身目录名(参与清单比对),
    // 目录与 `.str.toml` 现在创建;内容所有权仍在目标分支(自有 entries 只允许子分支)。
    // 别名(--title)留空时,自身标题默认取**目标标题**。
    let own_title = match &title {
        Some(t) => Some(t.clone()),
        None => scan.visits[dst]
            .meta
            .as_ref()
            .and_then(|m| m.title.clone()),
    };
    let (entry_path, entry_id, entry_title) = if mode == "hard" {
        let id_version = scan
            .visits
            .first()
            .and_then(|v| v.meta.as_ref())
            .map(|m| m.policies.id_version)
            .unwrap_or(7);
        let id = util::new_uuid(id_version);
        let dir = src_dir.join(&id);
        std::fs::create_dir_all(&dir)
            .map_err(|err| Error::BadArg(format!("创建硬链接分支目录失败:{err}")))?;
        let kind = if scan.visits[idx].depth == 0 {
            Kind::Node
        } else {
            Kind::Branch
        };
        let text = crate::meta_edit::render_branch_meta(
            kind,
            &id,
            None,
            own_title.as_deref(),
            None,
            &util::now_rfc3339(),
        );
        std::fs::write(bundle.meta_path(&dir), text)
            .map_err(|err| Error::BadArg(format!("写入硬链接 `.str.toml` 失败:{err}")))?;
        (id.clone(), Some(id), None)
    } else {
        (target.to_string(), None, title)
    };
    let ord = order.unwrap_or(meta.entries.len() as i64 + 1);
    meta.upsert_entry(&Entry {
        path: entry_path,
        role: "link".into(),
        id: entry_id,
        target: Some(target.to_string()),
        mode: Some(mode.to_string()),
        title: entry_title,
        order: Some(ord),
        note,
        ..Default::default()
    });
    meta.touch();
    save_meta(&bundle, &src_dir, &meta)?;
    let kind = if mode == "hard" { "硬链接" } else { "软连接" };
    println!("已挂载{kind} {} → {target}", scan.visits[idx].rel);
    Ok(())
}

/// 摘除一条链接:软连接**只摘引用**(目标与其数据不动);硬链接摘引用时**连同
/// 自身目录**一并删除(它是有身份的真实分支,摘了引用目录即成清单幽灵)——
/// 目标分支与其数据始终不动。
pub fn link_rm(dir: &Path, uuid: Option<String>, target: &str) -> Result<()> {
    let bundle = open(dir)?;
    let scan = bundle.scan()?;
    let idx = target_branch(&bundle, &scan, dir, uuid.as_deref())?;
    let src_dir = scan.visits[idx].dir.clone();
    let mut meta = match bundle.read_meta(&src_dir)? {
        MetaLoad::Ok(m, _) => m,
        MetaLoad::Failed(_) => return Err(Error::BadArg("源分支 `.str.toml` 解析失败".into())),
    };
    // 定位:软连接 `path` = target;硬链接 `path` = 自身 id(target 在 `target` 字段)。
    let row = meta
        .entries
        .iter()
        .find(|e| {
            e.is_link()
                && (e.path == target || e.target.as_deref() == Some(target))
        })
        .cloned();
    let Some(row) = row else {
        return Err(Error::BadArg(format!(
            "本分支下没有指向 `{target}` 的链接"
        )));
    };
    let hard = row.mode.as_deref() == Some("hard");
    meta.remove_entry_path(&row.path);
    meta.touch();
    save_meta(&bundle, &src_dir, &meta)?;
    if hard {
        let link_dir = src_dir.join(&row.path);
        std::fs::remove_dir_all(&link_dir)
            .map_err(|err| Error::io(&link_dir, err))?;
        println!(
            "已摘除硬链接 {} → {target}(连同其自有子结构目录 `{}`,目标分支数据不动)",
            scan.visits[idx].rel,
            row.path
        );
    } else {
        println!("已摘除软连接 {} → {target}", scan.visits[idx].rel);
    }
    Ok(())
}

// ─────────────────────────── ref ───────────────────────────

/// 新增跨枝关联线。(规范 §9:源分支 `<UUID>` 缺省为当前节点;`--target` 仍必填。)
pub fn ref_add(
    dir: &Path,
    uuid: Option<String>,
    target: &str,
    rel: String,
    title: Option<String>,
    note: Option<String>,
) -> Result<()> {
    let bundle = open(dir)?;
    let scan = bundle.scan()?;
    let idx = target_branch(&bundle, &scan, dir, uuid.as_deref())?;
    if locate(&scan, target).is_none() {
        return Err(Error::BadArg(format!("找不到目标分支 id `{target}`")));
    }
    let src_dir = scan.visits[idx].dir.clone();
    let mut meta = match bundle.read_meta(&src_dir)? {
        MetaLoad::Ok(m, _) => m,
        MetaLoad::Failed(_) => return Err(Error::BadArg("源分支 `.str.toml` 解析失败".into())),
    };
    let ref_id = util::new_uuid_v7();
    let order = meta.refs.len() as i64 + 1;
    meta.push_ref(&RefItem {
        id: ref_id.clone(),
        target: target.to_string(),
        rel,
        title,
        order: Some(order),
        note,
    });
    meta.touch();
    save_meta(&bundle, &src_dir, &meta)?;
    // 源分支可能是缺省来的 ROOT / 当前节点(其 `id` 与目录名无关),故打印解析后的真实 `id`
    let src_id = meta
        .id
        .clone()
        .unwrap_or_else(|| scan.visits[idx].rel.clone());
    println!("已新增关联线 {ref_id}:{src_id} → {target}");
    Ok(())
}

/// 删除关联线。
///
/// 规范 §9 的形式是 `str ref rm <dir> <ref-uuid>`:只给关联线 id,由 CLI 在全 bundle 内定位
/// 它所属的源分支。`--uuid <源分支>` 可把搜索范围钉死在一个分支上(旧版 `--ref` 形式等价)。
pub fn ref_rm(dir: &Path, uuid: Option<String>, ref_id: &str) -> Result<()> {
    let bundle = open(dir)?;
    let scan = bundle.scan()?;
    let has_ref = |i: usize| -> bool {
        scan.visits[i]
            .meta
            .as_ref()
            .map(|m| m.refs.iter().any(|r| r.id == ref_id))
            .unwrap_or(false)
    };
    let idx = match uuid {
        Some(u) => {
            let i = locate(&scan, &u).ok_or_else(|| Error::BadArg(format!("找不到分支 id `{u}`")))?;
            if !has_ref(i) {
                return Err(Error::BadArg(format!("分支 `{u}` 内找不到关联线 `{ref_id}`")));
            }
            i
        }
        None => {
            let hits: Vec<usize> = (0..scan.visits.len()).filter(|i| has_ref(*i)).collect();
            match hits.as_slice() {
                [only] => *only,
                [] => return Err(Error::BadArg(format!("找不到关联线 `{ref_id}`"))),
                _ => {
                    let rels: Vec<String> =
                        hits.iter().map(|i| scan.visits[*i].rel.clone()).collect();
                    return Err(Error::BadArg(format!(
                        "关联线 `{ref_id}` 在多个分支中出现({}),请用 `--uuid` 指定源分支",
                        rels.join("、")
                    )));
                }
            }
        }
    };
    let rel = scan.visits[idx].rel.clone();
    let src_dir = scan.visits[idx].dir.clone();
    let mut meta = match bundle.read_meta(&src_dir)? {
        MetaLoad::Ok(m, _) => m,
        MetaLoad::Failed(_) => return Err(Error::BadArg("分支 `.str.toml` 解析失败".into())),
    };
    if !meta.remove_ref(ref_id) {
        return Err(Error::BadArg(format!("找不到关联线 `{ref_id}`")));
    }
    meta.touch();
    save_meta(&bundle, &src_dir, &meta)?;
    println!("已删除关联线 {ref_id}(源分支 {rel})");
    Ok(())
}

// ─────────────────── meta / entry / author(写入既有字段)───────────────────

/// 允许的 `authors[].role`(规范 §4.4 与 `.str.schema` 枚举一致)。
const AUTHOR_ROLES: &[&str] = &["owner", "editor", "viewer", "agent"];

/// 读取目标分支的 `.str.toml`(供字段写入类命令复用)。
fn read_target_meta(bundle: &Bundle, dir: &Path) -> Result<Meta> {
    match bundle.read_meta(dir)? {
        MetaLoad::Ok(m, _) => Ok(*m),
        MetaLoad::Failed(_) => Err(Error::BadArg(format!(
            "{} 的 `.str.toml` 解析失败",
            bundle.rel(dir)
        ))),
    }
}

/// 至少给出一个字段,否则拒绝执行(避免「无参数空写」把 `revision` 白白推进)。
fn need_one(given: bool, hint: &str) -> Result<()> {
    if given {
        Ok(())
    } else {
        Err(Error::BadArg(format!("至少需要指定一个字段({hint})")))
    }
}

/// `str meta set`:设置分支自身(`.str.toml` 顶层)的元信息字段。
///
/// 空串表示**移除**该字段。字段语义见规范 §4.3。
pub fn meta_set(
    dir: &Path,
    uuid: Option<String>,
    type_: Option<String>,
    title: Option<String>,
    summary: Option<String>,
    name: Option<String>,
    tags: Option<Vec<String>>,
) -> Result<()> {
    need_one(
        type_.is_some() || title.is_some() || summary.is_some() || name.is_some() || tags.is_some(),
        "--type / --title / --summary / --name / --tags",
    )?;
    let bundle = open(dir)?;
    let scan = bundle.scan()?;
    let idx = target_branch(&bundle, &scan, dir, uuid.as_deref())?;
    let target_dir = scan.visits[idx].dir.clone();
    let rel = scan.visits[idx].rel.clone();
    let mut meta = read_target_meta(&bundle, &target_dir)?;

    if let Some(v) = &type_ {
        meta.set_str_or_remove("type", v);
    }
    if let Some(v) = &title {
        meta.set_str_or_remove("title", v);
    }
    if let Some(v) = &summary {
        meta.set_str_or_remove("summary", v);
    }
    if let Some(v) = &name {
        meta.set_str_or_remove("name", v);
    }
    if let Some(v) = &tags {
        // `--tags ""` → 清空;顺带滤掉空项(否则写出 `tags = [""]` 会被 Schema 拒绝)
        let cleaned: Vec<String> = v.iter().filter(|s| !s.is_empty()).cloned().collect();
        meta.set_str_array("tags", &cleaned);
    }

    meta.touch();
    save_meta(&bundle, &target_dir, &meta)?;
    println!("已更新 {rel} 的元信息");
    Ok(())
}

/// `str entry set` 的字段补丁:`None` 表示不改动,`Some("")` 表示移除该键。
#[derive(Debug, Clone, Default)]
pub struct EntryPatch {
    /// 子分支类型。
    pub type_: Option<String>,
    /// 展示名。
    pub title: Option<String>,
    /// 子分支摘要。
    pub summary: Option<String>,
    /// 备注。
    pub note: Option<String>,
    /// 同层排序键。
    pub order: Option<i64>,
}

impl EntryPatch {
    /// 是否一个字段都没给。
    pub fn is_empty(&self) -> bool {
        self.type_.is_none()
            && self.title.is_none()
            && self.summary.is_none()
            && self.note.is_none()
            && self.order.is_none()
    }
}

/// `str entry set`:设置某分支 `entries[]` 中指定 `path` 条目的字段。
///
/// `str sync` 补登出来的行只有 `path` / `role` / `id`,其 `type` / `title` / `summary`
/// 由此命令补齐 —— 不再需要「手改 `.str.toml` 的唯一例外」。空串表示移除该字段。
pub fn entry_set(dir: &Path, uuid: Option<String>, path: &str, patch: &EntryPatch) -> Result<()> {
    need_one(
        !patch.is_empty(),
        "--type / --title / --summary / --note / --order",
    )?;
    let bundle = open(dir)?;
    let scan = bundle.scan()?;
    let idx = target_branch(&bundle, &scan, dir, uuid.as_deref())?;
    let target_dir = scan.visits[idx].dir.clone();
    let rel = scan.visits[idx].rel.clone();
    let mut meta = read_target_meta(&bundle, &target_dir)?;

    let mut applied = false;
    for (key, val) in [
        ("type", &patch.type_),
        ("title", &patch.title),
        ("summary", &patch.summary),
        ("note", &patch.note),
    ] {
        if let Some(v) = val {
            applied |= meta.set_entry_str(path, key, v);
        }
    }
    if let Some(n) = patch.order {
        applied |= meta.set_entry_int(path, "order", Some(n));
    }
    if !applied {
        return Err(Error::BadArg(format!(
            "{rel} 的 `entries[]` 内找不到 `path` = {path:?}"
        )));
    }

    meta.touch();
    save_meta(&bundle, &target_dir, &meta)?;
    println!("已更新 {rel} 的条目 {path}");
    Ok(())
}

/// `str author add`:按 `id` 新增 / 覆盖一条 `[[authors]]`(规范 §4.4)。
pub fn author_add(
    dir: &Path,
    uuid: Option<String>,
    id: String,
    name: Option<String>,
    role: String,
    at: Option<String>,
) -> Result<()> {
    if !AUTHOR_ROLES.contains(&role.as_str()) {
        return Err(Error::BadArg(format!(
            "`--role` = {role:?} 非法(owner / editor / viewer / agent)"
        )));
    }
    let at = match at {
        Some(v) => {
            let dt = v.parse::<toml_edit::Datetime>().map_err(|_| {
                Error::BadArg(format!(
                    "`--at` = {v:?} 不是合法 offset date-time(如 2026-09-14T10:03:11+08:00)"
                ))
            })?;
            if dt.offset.is_none() {
                return Err(Error::BadArg(format!("`--at` = {v:?} 缺少时区偏移(规范 4.1)")));
            }
            Some(dt.to_string())
        }
        None => Some(util::now_rfc3339()),
    };

    let bundle = open(dir)?;
    let scan = bundle.scan()?;
    let idx = target_branch(&bundle, &scan, dir, uuid.as_deref())?;
    let target_dir = scan.visits[idx].dir.clone();
    let rel = scan.visits[idx].rel.clone();
    let mut meta = read_target_meta(&bundle, &target_dir)?;

    let added = meta.upsert_author(&Author {
        id: id.clone(),
        name,
        role: role.clone(),
        at,
    });
    meta.touch();
    save_meta(&bundle, &target_dir, &meta)?;
    println!(
        "已{} {rel} 的协作者 {id}(role = {role})",
        if added { "新增" } else { "更新" }
    );
    Ok(())
}

/// `str author rm`:按 `id` 删除一条 `[[authors]]`。
pub fn author_rm(dir: &Path, uuid: Option<String>, id: &str) -> Result<()> {
    let bundle = open(dir)?;
    let scan = bundle.scan()?;
    let idx = target_branch(&bundle, &scan, dir, uuid.as_deref())?;
    let target_dir = scan.visits[idx].dir.clone();
    let rel = scan.visits[idx].rel.clone();
    let mut meta = read_target_meta(&bundle, &target_dir)?;
    if !meta.remove_author(id) {
        return Err(Error::BadArg(format!("{rel} 内找不到协作者 `{id}`")));
    }
    meta.touch();
    save_meta(&bundle, &target_dir, &meta)?;
    println!("已删除 {rel} 的协作者 {id}");
    Ok(())
}

// ─────────────────────────── entry add / entry rm ───────────────────────────

/// `entries[]` 的全部合法 role。
const ENTRY_ROLES: &[&str] = &[
    "node", "branch", "payload", "asset", "dir", "schema", "cache", "other",
];
/// 要求磁盘对象是目录的 role。
const DIR_ROLES: &[&str] = &["node", "branch", "dir", "schema", "cache"];

/// `str entry add` 的可选字段。
#[derive(Debug, Clone, Default)]
pub struct EntryNew {
    /// role(缺省按磁盘对象自动推断)。
    pub role: Option<String>,
    /// 子分支类型。
    pub type_: Option<String>,
    /// 展示名。
    pub title: Option<String>,
    /// 摘要。
    pub summary: Option<String>,
    /// 备注。
    pub note: Option<String>,
    /// 同层排序键。
    pub order: Option<i64>,
    /// 媒体类型(仅文件类条目;缺省按扩展名推断)。
    pub media_type: Option<String>,
    /// 登记为 `optional = true`(缺失被允许)。
    pub optional: bool,
}

/// `str entry add`:向目标分支 `entries[]` 登记一个实体条目。
///
/// - `--path` 必须是单段名,且不得与既有登记重复;
/// - 磁盘对象存在时自动补 `size` / `sha256`(文件)或 `count`(目录),
///   `role` 缺省按对象类型推断(含 `.str.toml` 的目录按深度推断 node/branch);
/// - 磁盘对象不存在时必须给 `--optional`(先登记占位);
/// - 显式 `--role node|branch` 仅用于「收编」已含 `.str.toml` 的目录 —— 新建分支结构
///   仍应使用 `node add` / `branch add`。
pub fn entry_add(dir: &Path, uuid: Option<String>, path: &str, e: &EntryNew) -> Result<()> {
    if path.is_empty() || path.contains('/') || path.contains('\\') {
        return Err(Error::BadArg(format!(
            "`--path` = {path:?} 非法:须是单段名(不含路径分隔符)"
        )));
    }
    if util::is_reserved_name(path)
        || path.starts_with("._")
        || path == util::META_FILE
        || path == util::LOCK_FILE
    {
        return Err(Error::BadArg(format!(
            "`--path` = {path:?} 属格式保留名(`.str.` 命名空间或 AppleDouble `._` 模式),禁止登记为业务条目"
        )));
    }
    if let Some(r) = &e.role {
        if !ENTRY_ROLES.contains(&r.as_str()) {
            return Err(Error::BadArg(format!(
                "`--role` = {r:?} 非法({})",
                ENTRY_ROLES.join(" / ")
            )));
        }
        if r == "other" && e.note.is_none() {
            return Err(Error::BadArg(
                "`role = \"other\"` 必须提供 `--note` 说明(规范 §4.6)".into(),
            ));
        }
    }

    let bundle = open(dir)?;
    let scan = bundle.scan()?;
    let idx = target_branch(&bundle, &scan, dir, uuid.as_deref())?;
    let target_dir = scan.visits[idx].dir.clone();
    let rel = scan.visits[idx].rel.clone();
    let mut meta = read_target_meta(&bundle, &target_dir)?;

    if meta.entries.iter().any(|x| x.path == path) {
        return Err(Error::BadArg(format!(
            "{rel} 的 `entries[]` 已登记 {path:?}(改字段用 `str entry set`)"
        )));
    }

    let fs_path = target_dir.join(path);
    let exists = fs_path.symlink_metadata().is_ok();
    let is_dir = fs_path.is_dir();
    if !exists && !e.optional {
        return Err(Error::BadArg(format!(
            "磁盘不存在 {rel}/{path};若要先登记占位请加 `--optional`"
        )));
    }

    // role 推断 / 磁盘一致性校验
    let role = match &e.role {
        Some(r) => {
            let dir_role = DIR_ROLES.contains(&r.as_str());
            if exists {
                if dir_role && !is_dir {
                    return Err(Error::BadArg(format!(
                        "`--role {r}` 要求目录,但磁盘上是文件"
                    )));
                }
                if !dir_role && is_dir {
                    return Err(Error::BadArg(format!(
                        "`--role {r}` 要求文件,但磁盘上是目录"
                    )));
                }
            }
            if matches!(r.as_str(), "node" | "branch") {
                if exists && !bundle.has_meta(&fs_path) {
                    return Err(Error::BadArg(format!(
                        "{rel}/{path} 不含 `.str.toml`,不能登记为分支(新建分支用 `node add` / `branch add`)"
                    )));
                }
                let want = if scan.visits[idx].depth == 0 { "node" } else { "branch" };
                if r != want {
                    return Err(Error::BadArg(format!(
                        "深度 {} 的子分支必须是 `role = \"{want}\"`(`node` 仅限 ROOT 直下)",
                        scan.visits[idx].depth
                    )));
                }
            }
            r.clone()
        }
        None => {
            if !exists {
                "payload".to_string()
            } else if is_dir {
                if bundle.has_meta(&fs_path) {
                    if scan.visits[idx].depth == 0 { "node" } else { "branch" }.to_string()
                } else {
                    "dir".to_string()
                }
            } else {
                guess_file_role(path).to_string()
            }
        }
    };

    let is_branch_role = matches!(role.as_str(), "node" | "branch");
    let mut entry = if exists && is_dir {
        if is_branch_role {
            Entry {
                path: path.to_string(),
                role: role.clone(),
                id: Some(path.to_string()),
                ..Default::default()
            }
        } else {
            Entry {
                path: path.to_string(),
                role: role.clone(),
                count: child_count(&fs_path),
                ..Default::default()
            }
        }
    } else if exists {
        Entry {
            path: path.to_string(),
            role: role.clone(),
            media_type: e.media_type.clone().or_else(|| media_type_for(path)),
            size: std::fs::metadata(&fs_path).ok().map(|m| m.len() as i64),
            sha256: util::sha256_file(&fs_path).ok(),
            ..Default::default()
        }
    } else {
        // 占位登记(--optional):不带指纹,由 sync 在实体落盘后补齐
        Entry {
            path: path.to_string(),
            role: role.clone(),
            ..Default::default()
        }
    };
    entry.r#type = e.type_.clone();
    entry.title = e.title.clone();
    entry.summary = e.summary.clone();
    entry.note = e.note.clone();
    entry.order = e.order;
    entry.optional = e.optional;

    meta.upsert_entry(&entry);
    meta.sort_collections();
    meta.touch();
    save_meta(&bundle, &target_dir, &meta)?;
    println!("已登记 {rel}/{path}  role={role}");
    Ok(())
}

/// `str entry rm`:把一个条目从目标分支 `entries[]` 的登记中移除。
///
/// **只移除登记,不删除磁盘文件**;磁盘文件由作者自行处置
/// (`str sync` 之后会因「磁盘有、清单无」而重新补登)。
pub fn entry_rm(dir: &Path, uuid: Option<String>, path: &str) -> Result<()> {
    let bundle = open(dir)?;
    let scan = bundle.scan()?;
    let idx = target_branch(&bundle, &scan, dir, uuid.as_deref())?;
    let target_dir = scan.visits[idx].dir.clone();
    let rel = scan.visits[idx].rel.clone();
    let mut meta = read_target_meta(&bundle, &target_dir)?;
    if !meta.entries.iter().any(|x| x.path == path) {
        return Err(Error::BadArg(format!(
            "{rel} 的 `entries[]` 内没有 {path:?}"
        )));
    }
    meta.remove_entry_path(path);
    meta.touch();
    save_meta(&bundle, &target_dir, &meta)?;
    println!("已移除登记 {rel}/{path}(磁盘文件未删除)");
    Ok(())
}

// ─────────────────────────── ignore / policies ───────────────────────────

/// `str ignore add`:向 ROOT `[policies].ignore` 追加一条模式(幂等)。
pub fn ignore_add(dir: &Path, pattern: &str) -> Result<()> {
    let pattern = pattern.trim();
    if pattern.is_empty() {
        return Err(Error::BadArg("忽略模式不能为空".into()));
    }
    let bundle = open(dir)?;
    let mut meta = read_target_meta(&bundle, &bundle.root)?;
    let mut cur = meta.policies.ignore.clone();
    if cur.iter().any(|p| p == pattern) {
        println!("已存在(忽略名单未变化):{pattern}");
        return Ok(());
    }
    cur.push(pattern.to_string());
    meta.set_policies_str_array("ignore", &cur);
    meta.canonicalize();
    meta.touch();
    save_meta(&bundle, &bundle.root, &meta)?;
    println!("已加入忽略名单(共 {} 条):{pattern}", cur.len());
    Ok(())
}

/// `str ignore rm`:从 ROOT `[policies].ignore` 移除一条模式。
pub fn ignore_rm(dir: &Path, pattern: &str) -> Result<()> {
    let bundle = open(dir)?;
    let mut meta = read_target_meta(&bundle, &bundle.root)?;
    let mut cur = meta.policies.ignore.clone();
    let Some(pos) = cur.iter().position(|p| p == pattern) else {
        return Err(Error::BadArg(format!(
            "忽略名单中没有 {pattern:?}(`str ignore list` 查看)"
        )));
    };
    cur.remove(pos);
    meta.set_policies_str_array("ignore", &cur);
    meta.canonicalize();
    meta.touch();
    save_meta(&bundle, &bundle.root, &meta)?;
    println!("已移出忽略名单(剩 {} 条):{pattern}", cur.len());
    Ok(())
}

/// `str ignore list`:查看 `policies.ignore` 与检测到的 `.gitignore` 来源。
pub fn ignore_list(dir: &Path) -> Result<()> {
    let bundle = open(dir)?;
    let scan = bundle.scan()?;
    let policies = scan.visits[0]
        .meta
        .as_ref()
        .map(|m| m.policies.clone())
        .unwrap_or_default();
    println!("policies.gitignore = {}", policies.gitignore);
    if policies.ignore.is_empty() {
        println!("policies.ignore:(空)");
    } else {
        println!("policies.ignore:");
        for p in &policies.ignore {
            println!("  - {p}");
        }
    }
    println!(".gitignore 来源:");
    let mut found = 0usize;
    for v in &scan.visits {
        if v.dir.join(".gitignore").is_file() {
            let scope = if v.rel == "." { "bundle 根" } else { &v.rel };
            println!("  - {scope}");
            found += 1;
        }
    }
    if found == 0 {
        println!("  (无)");
    }
    Ok(())
}

/// `str policies set`:写入 ROOT `[policies]` 的标量键。
///
/// `ignore` 是数组键,须用 `str ignore add` / `str ignore rm` 维护。
pub fn policies_set(dir: &Path, key: &str, val: &str) -> Result<()> {
    use toml_edit::value;
    let item = match key {
        "id_version" => {
            let v: usize = val.parse().map_err(|_| bad_policy(key, val))?;
            if v != 4 && v != 7 {
                return Err(bad_policy(key, val));
            }
            value(v as i64)
        }
        "max_depth" | "deep_tree_warn" => {
            let v: i64 = val.parse().map_err(|_| bad_policy(key, val))?;
            if v < 1 {
                return Err(bad_policy(key, val));
            }
            value(v)
        }
        "large_asset_bytes" => {
            let v: u64 = val.parse().map_err(|_| bad_policy(key, val))?;
            value(v as i64)
        }
        "manifest" => match val {
            "strict" | "advisory" => value(val.to_string()),
            _ => return Err(bad_policy(key, val)),
        },
        "sha256" => match val {
            "required" | "optional" | "off" => value(val.to_string()),
            _ => return Err(bad_policy(key, val)),
        },
        "gitignore" => match val {
            "true" | "false" => value(val == "true"),
            _ => return Err(bad_policy(key, val)),
        },
        "ignore" => {
            return Err(Error::BadArg(
                "`ignore` 是数组键:追加 / 移除请用 `str ignore add` / `str ignore rm`,\
                 `str ignore list` 查看"
                    .into(),
            ))
        }
        other => {
            return Err(Error::BadArg(format!(
                "未知策略键 {other:?}(id_version / max_depth / manifest / sha256 / \
                 gitignore / large_asset_bytes / deep_tree_warn)"
            )))
        }
    };
    let bundle = open(dir)?;
    let mut meta = read_target_meta(&bundle, &bundle.root)?;
    meta.set_policies_value(key, Some(item));
    meta.canonicalize();
    meta.touch();
    save_meta(&bundle, &bundle.root, &meta)?;
    println!("policies.{key} = {val}");
    Ok(())
}

fn bad_policy(key: &str, value: &str) -> Error {
    Error::BadArg(format!("`policies.{key}` = {value:?} 非法"))
}

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

/// 校验并规整 `spec` 版本串。
///
/// 只接受形如 `1.<minor>.<patch>` 的值 —— 与 `.str.schema` 里 `^1\.[0-9]+\.[0-9]+$` 的正则一致
/// (写进去的必须能通过 bundle 自己声明的 Schema);允许 `v` 前缀,规整时去掉。
/// `str` 主版本固定为 `1`(规范 §13:只有 `str` 主版本需要工具显式支持)。
fn normalize_spec_version(raw: &str) -> Result<String> {
    let v = raw.trim().trim_start_matches('v').trim().to_string();
    let parts: Vec<&str> = v.split('.').collect();
    let ok = parts.len() == 3
        && parts[0] == "1"
        && parts[1].parse::<u64>().is_ok()
        && parts[2].parse::<u64>().is_ok();
    if !ok {
        return Err(Error::BadArg(format!(
            "`spec` 版本串 {raw:?} 非法:须形如 `1.<minor>.<patch>`(`str` 主版本固定为 `1`)。\
             注意自规范 v1.10.0 起 `spec set` 的参数顺序为 `<VERSION> [dir]`(如 `str spec set 1.10.0`)"
        )));
    }
    Ok(v)
}

/// `str spec set`:把整份 bundle 声明的规范版本(`.str.toml.spec`)统一改写为 `version`。
///
/// 为什么是**整份 bundle**:`spec` 在三种档位里都是必填字段(规范 §4.3),只改 ROOT 会让
/// 其余分支的声明与 ROOT 不一致 —— 文档就在说谎。子 bundle(`.str` 目录)是硬边界(§3.5),
/// 不进入。只改写与目标值不同的分支,因此**幂等**(第二次「已更新 0 份」)。
///
/// 这是「不再需要手改 `.str.toml`」的最后一块:v1.9.0 之前 `spec` 没有任何 CLI 写入命令。
pub fn spec_set(dir: &Path, version: &str, dry_run: bool) -> Result<()> {
    let version = normalize_spec_version(version)?;
    let bundle = open(dir)?;
    let scan = bundle.scan()?;

    // 先整体体检:任何一份 `.str.toml` 解析失败就拒绝执行 —— 既不半途写一半,也不静默跳过
    let broken: Vec<String> = scan
        .visits
        .iter()
        .filter(|v| v.meta.is_none())
        .map(|v| v.rel.clone())
        .collect();
    if !broken.is_empty() {
        return Err(Error::BadArg(format!(
            "{} 份 `.str.toml` 解析失败({}),改 `spec` 前请先修复",
            broken.len(),
            broken.join("、")
        )));
    }

    // 计划:只挑 `spec` 与目标值不同的分支
    let mut plan: Vec<(usize, String)> = Vec::new();
    for (i, v) in scan.visits.iter().enumerate() {
        let from = v
            .meta
            .as_ref()
            .and_then(|m| m.spec.clone())
            .unwrap_or_else(|| "(缺失)".to_string());
        if from == version {
            continue;
        }
        plan.push((i, from));
    }
    for (i, from) in &plan {
        println!("~ {}  spec: {from} → {version}", scan.visits[*i].rel);
    }
    if !plan.is_empty() && version != SPEC_VERSION {
        println!(
            "注意:目标 `spec` = {version} 与本实现对应的规范版本({SPEC_VERSION})不同;\
             `spec` 仅用于人类追溯,工具只强校验 `str` 主版本(规范 §13)"
        );
    }

    if plan.is_empty() {
        println!(
            "全部 `.str.toml` 的 `spec` 已是 {version}({} 份)",
            scan.visits.len()
        );
        return Ok(());
    }
    if dry_run {
        println!("(dry-run)将更新 {} 份 `.str.toml`", plan.len());
        return Ok(());
    }

    for (i, _) in &plan {
        let branch_dir = scan.visits[*i].dir.clone();
        let mut work = match bundle.read_meta(&branch_dir)? {
            MetaLoad::Ok(m, _) => m,
            MetaLoad::Failed(_) => {
                // 体检已通过,此处仅防御并发改动;一旦发生就中止,不留下写一半的结果
                return Err(Error::BadArg(format!(
                    "{} 的 `.str.toml` 解析失败,已中止(未写出部分结果)",
                    scan.visits[*i].rel
                )));
            }
        };
        let had_spec = work.doc.as_table().contains_key("spec");
        work.set_str("spec", &version);
        if !had_spec {
            // 缺失时插入会落到文件末尾,而 TOML 要求裸键写在任何表头之前 → 用 §4.9 规范化归位
            work.canonicalize();
        }
        work.touch();
        save_meta(&bundle, &branch_dir, &work)?;
    }
    println!("已更新 {} 份 `.str.toml`", plan.len());
    Ok(())
}

// ─────────────────────────── sync ───────────────────────────

/// `sync` 未显式确认(`--yes`)时允许直接移除的条目数上限;
/// 达到即拒绝执行,要求先 `--dry-run` 预览或 `--yes` 确认(规范 §9)。
pub const SYNC_REMOVE_GATE: usize = 10;

/// 用磁盘实际状态修正全部 `entries`,并更新 `size` / `sha256`。
///
/// 规范 §4.6.1 规则 1:软连接(`role = "link"` 且非 `mode = "hard"`)是声明式挂载、
/// 磁盘上**没有**对应目录(`path` 即目标分支 id,位于 bundle 其它位置),
/// **不参与清单比对** —— 本命令同样不得将其视为「已消失」而移除。
///
/// 删除类变更必须醒目(规范 §9):
/// - 移除条目数 > 0 时输出 `WARN:` 汇总行(dry-run 亦然);
/// - 移除条目数 ≥ [`SYNC_REMOVE_GATE`] 且未带 `--yes`(非 dry-run)时拒绝执行,
///   杜绝「0 errors 0 warnings 但批量删除条目」的静默破坏。
pub fn sync(dir: &Path, dry_run: bool, yes: bool) -> Result<()> {
    let bundle = open(dir)?;
    let scan = bundle.scan()?;
    let mut changed = 0usize;
    let mut planned: Vec<String> = Vec::new();
    let mut removals = 0usize;
    let mut writes: Vec<(PathBuf, Meta)> = Vec::new();

    for v in &scan.visits {
        if v.meta.is_none() {
            continue;
        }
        let dir_path = v.dir.clone();
        let rel = v.rel.clone();
        let mut work = match bundle.read_meta(&v.dir)? {
            MetaLoad::Ok(m, _) => m,
            MetaLoad::Failed(_) => continue,
        };
        let real = crate::validate::real_entries(&dir_path, &rel, &scan.ignore);
        let declared: Vec<Entry> = work.entries.clone();
        let mut touched = false;

        // 补登
        for (name, is_dir) in &real {
            if declared.iter().any(|e| e.path == *name) {
                continue;
            }
            let path = dir_path.join(name);
            let e = if *is_dir {
                if bundle.has_meta(&path) {
                    Entry {
                        path: name.clone(),
                        role: if v.depth == 0 { "node" } else { "branch" }.into(),
                        id: Some(name.clone()),
                        order: Some(declared.len() as i64 + 1),
                        ..Default::default()
                    }
                } else {
                    Entry {
                        path: name.clone(),
                        role: "dir".into(),
                        count: child_count(&path),
                        ..Default::default()
                    }
                }
            } else {
                let meta_info = std::fs::metadata(&path).ok();
                let size = meta_info.map(|m| m.len() as i64);
                let sha = util::sha256_file(&path).ok();
                Entry {
                    path: name.clone(),
                    role: guess_file_role(name).into(),
                    media_type: media_type_for(name),
                    size,
                    sha256: sha,
                    ..Default::default()
                }
            };
            planned.push(format!("+ {rel}/{name}  role={}", e.role));
            work.upsert_entry(&e);
            touched = true;
        }

        // 移除已消失的条目 + 刷新指纹
        for e in &declared {
            // 规范 §4.6.1 规则 1:软连接是声明式挂载、磁盘上没有对应目录
            // (`path` = 目标分支 id,位于 bundle 其它位置),不参与清单比对 ——
            // 绝不能因「磁盘不存在」而移除。硬链接(`mode = "hard"`)目录真实存在,
            // 目录缺失照常按「已消失」对账(受下方告警 / 门禁保护)。
            if e.is_link() && e.mode.as_deref() != Some("hard") {
                continue;
            }
            let path = dir_path.join(&e.path);
            if !path.exists() {
                if !e.optional {
                    planned.push(format!("- {rel}/{}", e.path));
                    removals += 1;
                    work.remove_entry_path(&e.path);
                    touched = true;
                }
                continue;
            }
            if !e.is_file_like() {
                continue;
            }
            let size = std::fs::metadata(&path).ok().map(|m| m.len() as i64);
            let sha = util::sha256_file(&path).ok();
            if size != e.size || sha != e.sha256 {
                planned.push(format!("~ {rel}/{}  指纹更新", e.path));
                let mut ne = e.clone();
                ne.size = size;
                ne.sha256 = sha;
                if ne.media_type.is_none() {
                    ne.media_type = media_type_for(&e.path);
                }
                work.upsert_entry(&ne);
                touched = true;
            }
        }

        if touched {
            work.sort_collections();
            work.touch();
            changed += 1;
            writes.push((bundle.meta_path(&dir_path), *work));
        }
    }

    for line in &planned {
        println!("{line}");
    }
    // 删除类变更必须醒目:只要发生移除就打 WARN 汇总(规范 §9)。
    if removals > 0 {
        println!("WARN: 本次对账将移除 {removals} 个条目(上方以 `-` 列出)");
    }

    // 批量删除门禁:达到阈值且未显式确认时拒绝执行、一字不写。
    if !dry_run && removals >= SYNC_REMOVE_GATE && !yes {
        return Err(Error::Other(format!(
            "拒绝执行:本次对账将移除 {removals} 个条目(≥ 门禁 {SYNC_REMOVE_GATE})。\
             先用 `str sync {} --dry-run` 预览,确认后加 `--yes` 显式执行",
            dir.display()
        )));
    }

    if dry_run {
        println!("(dry-run)将更新 {changed} 份 `.str.toml`");
        return Ok(());
    }
    for (path, work) in writes {
        work.save(&path)?;
    }
    // `sync` 是「与磁盘对齐」的总入口:顺手把 `E_REVISION_STALE` 的基线刷成当前状态。
    if let Ok(after) = bundle.scan() {
        crate::baseline::record_scan(&bundle, &after);
    }
    println!("已更新 {changed} 份 `.str.toml`");
    Ok(())
}

fn guess_file_role(name: &str) -> &'static str {
    match media_type_for(name).as_deref() {
        Some("application/json")
        | Some("application/toml")
        | Some("application/yaml")
        | Some("text/csv")
        | Some("text/markdown")
        | Some("text/plain") => "payload",
        _ => "asset",
    }
}

// ─────────────────────────── fmt ───────────────────────────

/// 按规范 §4.9 键序 / 表序重写 `.str.toml`(保注释)。
///
/// 规范化**不触碰** `revision` / `updated_at`,因此不影响 `E_REVISION_STALE` 基线。
pub fn fmt(dir: &Path, check: bool, strip_comments: bool) -> Result<i32> {
    let bundle = open(dir)?;
    let scan = bundle.scan()?;
    let mut would_change = 0usize;
    for v in &scan.visits {
        if v.meta.is_none() {
            continue;
        }
        let meta = match bundle.read_meta(&v.dir)? {
            MetaLoad::Ok(m, _) => m,
            MetaLoad::Failed(_) => continue,
        };
        let text = meta.canonical_text(strip_comments);
        let path = bundle.meta_path(&v.dir);
        let current = std::fs::read_to_string(&path).unwrap_or_default();
        if current != text {
            would_change += 1;
            if !check {
                std::fs::write(&path, text).map_err(|e| Error::io(&path, e))?;
                println!("已规范化 {}", v.rel);
            }
        }
    }
    if check {
        if would_change == 0 {
            println!("全部 `.str.toml` 已是规范形式");
            return Ok(0);
        }
        println!("{would_change} 份 `.str.toml` 需要规范化");
        return Ok(1);
    }
    if would_change == 0 {
        println!("全部 `.str.toml` 已是规范形式");
    }
    Ok(0)
}

// ─────────────────────────── norm / context / export ───────────────────────────

/// 输出归一化 JSON。
///
/// `--out -`(或缺省)写 stdout;给路径则写文件(规范 §9)。
/// `<UUID>` 缺省为当前节点。
pub fn norm(dir: &Path, uuid: Option<String>, out: Option<String>) -> Result<()> {
    let bundle = open(dir)?;
    let scan = bundle.scan()?;
    let idx = target_branch(&bundle, &scan, dir, uuid.as_deref())?;
    let Some(meta) = scan.visits[idx].meta.as_ref() else {
        return Err(Error::BadArg("`.str.toml` 解析失败".into()));
    };
    let mut text = serde_json::to_string_pretty(&meta.to_json()).unwrap_or_default();
    text.push('\n');
    emit(&text, out.as_deref())
}

/// 生成供 AI 使用的上下文片段。(规范 §9:`<UUID>` 缺省为当前节点。)
pub fn context(dir: &Path, uuid: Option<String>, depth: usize, budget: usize) -> Result<()> {
    let bundle = open(dir)?;
    let scan = bundle.scan()?;
    let idx = target_branch(&bundle, &scan, dir, uuid.as_deref())?;
    let mut out = String::new();
    out.push_str(&format!("# STR 上下文:{}\n\n", bundle.name()));
    render_context(&scan, idx, depth, &mut out, 0);
    if out.len() > budget {
        out.truncate(floor_char_boundary(&out, budget));
        out.push_str("\n…(已按 --budget 截断)\n");
    }
    print!("{out}");
    Ok(())
}

fn render_context(scan: &Scan, idx: usize, depth: usize, out: &mut String, level: usize) {
    let v = &scan.visits[idx];
    let Some(meta) = v.meta.as_ref() else {
        return;
    };
    let indent = "  ".repeat(level);
    out.push_str(&format!(
        "{indent}- `{}` **{}** ({}) depth={}\n",
        meta.id.clone().unwrap_or_default(),
        meta.title.clone().unwrap_or_else(|| v.rel.clone()),
        meta.r#type.clone().unwrap_or_else(|| "-".into()),
        v.depth
    ));
    if let Some(s) = &meta.summary {
        out.push_str(&format!("{indent}  {s}\n"));
    }
    if !meta.tags.is_empty() {
        out.push_str(&format!("{indent}  tags: {}\n", meta.tags.join(", ")));
    }
    let files: Vec<String> = meta
        .entries
        .iter()
        .filter(|e| !e.is_branch())
        .map(|e| format!("{}({})", e.path, e.role))
        .collect();
    if !files.is_empty() {
        out.push_str(&format!("{indent}  内容:{}\n", files.join("、")));
    }
    for r in &meta.refs {
        let t = scan
            .resolve(&r.target)
            .map(|i| scan.visits[i].rel.clone())
            .unwrap_or_else(|| r.target.clone());
        out.push_str(&format!("{indent}  关联线 → {t} ({})\n", r.rel));
    }
    if level >= depth {
        return;
    }
    let children = ordered_children(scan, idx);
    for c in children {
        render_context(scan, c, depth, out, level + 1);
    }
}

fn floor_char_boundary(s: &str, mut i: usize) -> usize {
    if i >= s.len() {
        return s.len();
    }
    while i > 0 && !s.is_char_boundary(i) {
        i -= 1;
    }
    i
}

/// 导出为单一 JSON / TOML(派生数据,只读)。
///
/// `--out -`(或缺省)写 stdout;给路径则写文件,且**不得**落在 bundle 内部(规范 §9)。
pub fn export(
    dir: &Path,
    format: String,
    depth: Option<usize>,
    out: Option<String>,
) -> Result<()> {
    if !matches!(format.as_str(), "json" | "toml") {
        return Err(Error::BadArg(format!(
            "`--format` = {format:?} 非法(只允许 json / toml)"
        )));
    }
    let bundle = open(dir)?;
    let scan = bundle.scan()?;
    let Some(root_idx) = scan.root_index else {
        return Err(Error::BadArg("bundle 缺少 `.str.toml`".into()));
    };
    let value = export_node(&scan, root_idx, depth);
    let mut text = if format == "toml" {
        toml_from_json(&value, 0)
    } else {
        serde_json::to_string_pretty(&value).unwrap_or_default()
    };
    if !text.ends_with('\n') {
        text.push('\n');
    }
    match out.as_deref() {
        None | Some("-") => emit(&text, None),
        Some(p) => {
            let path = resolve_out_path(&bundle, p)?;
            std::fs::write(&path, text).map_err(|e| Error::io(&path, e))
        }
    }
}

fn export_node(scan: &Scan, idx: usize, depth: Option<usize>) -> JValue {
    let v = &scan.visits[idx];
    let meta = match v.meta.as_ref() {
        Some(m) => m.to_json(),
        None => serde_json::json!({ "id": null, "error": "parse_failed" }),
    };
    let children = ordered_children(scan, idx);
    let descend = depth.map(|d| v.depth < d).unwrap_or(true);
    let kids: Vec<JValue> = if descend {
        children.iter().map(|c| export_node(scan, *c, depth)).collect()
    } else {
        Vec::new()
    };
    serde_json::json!({
        "path": v.rel,
        "depth": v.depth,
        "meta": meta,
        "children": kids,
    })
}

/// 简易 JSON → TOML(仅用于 `str export --format toml`)。
fn toml_from_json(v: &JValue, indent: usize) -> String {
    let pad = "  ".repeat(indent);
    match v {
        JValue::Object(m) => {
            let mut scalars = String::new();
            let mut tables = String::new();
            for (k, val) in m {
                match val {
                    JValue::Object(_) | JValue::Array(_) => {
                        tables.push_str(&format!("\n{pad}[{k}]\n{}", toml_from_json(val, indent + 1)));
                    }
                    _ => scalars.push_str(&format!("{pad}{k} = {}\n", toml_from_json(val, 0))),
                }
            }
            format!("{scalars}{tables}")
        }
        JValue::Array(items) => {
            if items.iter().all(|i| matches!(i, JValue::Object(_))) {
                let mut s = String::new();
                for it in items {
                    s.push_str(&format!("{pad}[[_item]]\n{}", toml_from_json(it, indent + 1)));
                }
                s
            } else {
                let inner: Vec<String> = items.iter().map(|i| toml_from_json(i, 0)).collect();
                format!("[{}]", inner.join(", "))
            }
        }
        JValue::String(s) => toml_str(s),
        JValue::Bool(b) => b.to_string(),
        JValue::Number(n) => n.to_string(),
        JValue::Null => "\"\"".to_string(),
    }
}

// ─────────────────────────── find / grep / tags / where / get ───────────────────────────
//
// 「定位 → 精读」链路(面向 AI 的渐进式读取,规范 §9):
//   `str tags`  看导航维度      →  `str find` / `str grep`  按元数据 / 正文定位
//   →  `str where`  面包屑确认位置  →  `str get` / `str show`  精读目标内容。
// 本组命令全部**只读**:不推进 `revision`、不写任何 `.str.toml`。

/// 不区分大小写的子串匹配。
fn ci_contains(s: Option<&str>, q: &str) -> bool {
    s.map(|x| x.to_lowercase().contains(q)).unwrap_or(false)
}

/// 按字符数截断长行(全文检索的命中行保底预算)。
fn clip_line(s: &str, max_chars: usize) -> String {
    if s.chars().count() <= max_chars {
        return s.to_string();
    }
    let cut: String = s.chars().take(max_chars).collect();
    format!("{cut}…")
}

/// 查询命令的范围解析:`--scope` 接受**分支 id** 或 **bundle 相对路径**;
/// 缺省沿用 §9 `[uuid]` 缺省规则 —— 当前节点(`[dir]` 为 bundle 根即 ROOT = 全 bundle,
/// 指向分支目录即该分支子树)。
fn resolve_scope(bundle: &Bundle, scan: &Scan, dir: &Path, scope: Option<&str>) -> Result<usize> {
    match scope {
        Some(s) => {
            if let Some(i) = locate(scan, s) {
                return Ok(i);
            }
            if let Some(i) = scan.visits.iter().position(|v| v.rel == s) {
                return Ok(i);
            }
            Err(Error::BadArg(format!(
                "`--scope` = {s:?} 无法解析:既不是分支 id,也不是 bundle 相对路径(用 `str tree` / `str where` 查看)"
            )))
        }
        None => target_branch(bundle, scan, dir, None),
    }
}

/// `idx` 是否在 `scope` 子树内(含自身)。
fn within_subtree(scan: &Scan, idx: usize, scope: usize) -> bool {
    let mut cur = Some(idx);
    while let Some(i) = cur {
        if i == scope {
            return true;
        }
        cur = scan.visits[i].parent;
    }
    false
}

/// `str find` 的收集段:在分支自身字段与 `entries[]` 行字段中找关键词,
/// 或按 `type` / 标签做纯过滤。命中按 `(depth, rel)` 排序;恒含绝对路径 `path_abs` 字段。
#[allow(clippy::too_many_arguments)]
pub fn find_hits(
    dir: &Path,
    query: Option<String>,
    type_: Option<&str>,
    tags: &[String],
    field: Option<&str>,
    scope: Option<&str>,
    depth: Option<usize>,
    limit: Option<usize>,
) -> Result<Vec<JValue>> {
    const FIELDS: &[&str] = &["all", "title", "summary", "type", "tags", "note", "path"];
    let field = field.unwrap_or("all");
    if !FIELDS.contains(&field) {
        return Err(Error::BadArg(format!(
            "`--field` = {field:?} 非法(可选:{})",
            FIELDS.join(" / ")
        )));
    }
    let q = query.as_deref().map(str::to_lowercase);
    let bundle = open(dir)?;
    let scan = bundle.scan()?;
    let scope = resolve_scope(&bundle, &scan, dir, scope)?;
    let mut hits: Vec<JValue> = Vec::new();
    for (vi, v) in scan.visits.iter().enumerate() {
        if !within_subtree(&scan, vi, scope) {
            continue;
        }
        if depth.is_some_and(|d| v.depth > d) {
            continue;
        }
        let Some(meta) = v.meta.as_ref() else {
            continue;
        };
        if let Some(t) = type_
            && meta.r#type.as_deref() != Some(t)
        {
            continue;
        }
        if !tags.is_empty()
            && !tags
                .iter()
                .all(|t| meta.tags.iter().any(|mt| mt.eq_ignore_ascii_case(t)))
        {
            continue;
        }
        let mut matched: Vec<String> = Vec::new();
        if let Some(q) = &q {
            let mut want = |name: String, on: bool| {
                if on && (field == "all" || field == name.rsplit('.').next().unwrap_or(&name))
                    && !matched.iter().any(|m| m == &name)
                {
                    matched.push(name);
                }
            };
            want("title".into(), ci_contains(meta.title.as_deref(), q));
            want("summary".into(), ci_contains(meta.summary.as_deref(), q));
            want("type".into(), ci_contains(meta.r#type.as_deref(), q));
            want(
                "tags".into(),
                meta.tags.iter().any(|t| t.to_lowercase().contains(q)),
            );
            // 结构类条目(子分支 / 链接)的行字段不参与检索:子分支自身会被单独访问,
            // 否则同一份数据会在父级与本命中重复出现。
            for e in meta.entries.iter().filter(|e| !e.is_branch() && !e.is_link()) {
                let base = format!("entries[].{}", e.path);
                want(
                    format!("{base}.title"),
                    ci_contains(e.title.as_deref(), q),
                );
                want(
                    format!("{base}.summary"),
                    ci_contains(e.summary.as_deref(), q),
                );
                want(format!("{base}.note"), ci_contains(e.note.as_deref(), q));
                want("path".into(), e.path.to_lowercase().contains(q));
            }
            if matched.is_empty() {
                continue;
            }
        }
        hits.push(serde_json::json!({
            "path": v.rel,
            "path_abs": bundle.root.join(&v.rel).display().to_string(),
            "depth": v.depth,
            "id": meta.id,
            "kind": meta.kind.map(|k| k.as_str()),
            "title": meta.title,
            "type": meta.r#type,
            "summary": meta.summary,
            "tags": meta.tags,
            "matched": matched,
        }));
    }
    hits.sort_by(|a, b| {
        let ka = (
            a["depth"].as_u64().unwrap_or(0),
            a["path"].as_str().unwrap_or(""),
        );
        let kb = (
            b["depth"].as_u64().unwrap_or(0),
            b["path"].as_str().unwrap_or(""),
        );
        ka.cmp(&kb)
    });
    if let Some(n) = limit {
        hits.truncate(n);
    }
    Ok(hits)
}

/// `str find`:元数据检索(打印 [`find_hits`] 的结果;`--json` 输出 JSON 数组)。
/// `--real-path` 让文本输出使用绝对路径(便于管道给其它命令);JSON 恒含 `path_abs`。
#[allow(clippy::too_many_arguments)]
pub fn find(
    dir: &Path,
    query: Option<String>,
    type_: Option<&str>,
    tags: &[String],
    field: Option<&str>,
    scope: Option<&str>,
    depth: Option<usize>,
    limit: Option<usize>,
    real_path: bool,
    json: bool,
) -> Result<()> {
    let hits = find_hits(dir, query, type_, tags, field, scope, depth, limit)?;
    if json {
        println!("{}", serde_json::to_string_pretty(&hits).unwrap_or_default());
        return Ok(());
    }
    if hits.is_empty() {
        println!("(无命中)");
        return Ok(());
    }
    for h in &hits {
        let loc = if real_path {
            h["path_abs"].as_str().unwrap_or(".")
        } else {
            h["path"].as_str().unwrap_or(".")
        };
        let mut line = format!(
            "{}  {}  {}",
            loc,
            h["id"].as_str().unwrap_or("-"),
            h["title"].as_str().unwrap_or("(无标题)")
        );
        if let Some(t) = h["type"].as_str() {
            line.push_str(&format!("  ({t})"));
        }
        let tags: Vec<&str> = h["tags"]
            .as_array()
            .map(|a| a.iter().filter_map(|x| x.as_str()).collect())
            .unwrap_or_default();
        if !tags.is_empty() {
            line.push_str(&format!("  [{}]", tags.join(",")));
        }
        let m: Vec<&str> = h["matched"]
            .as_array()
            .map(|a| a.iter().filter_map(|x| x.as_str()).collect())
            .unwrap_or_default();
        if !m.is_empty() {
            line.push_str(&format!("  命中: {}", m.join(", ")));
        }
        println!("{line}");
    }
    Ok(())
}

/// `str grep` 的收集段:正文全文检索(字面子串,非正则)。
///
/// 缺省遍历每个分支目录**磁盘上**的全部文本文件 —— 覆盖已登记的 `payload` / `asset`
/// 条目、内容文件夹(`role = "dir"`)的未登记子项与未登记散落文件;
/// `manifest_only = true` 时退回「仅清单登记条目」口径。
/// 不进入:其它分支目录(各自作为 visit 单独遍历)、含 `.str.toml` 的目录、
/// 保留名 / 系统噪声 / `.lock`、被忽略名单(`Scan.ignore`)剪中的路径。
/// 二进制(含 NUL 字节)与非 UTF-8 文件跳过;命中行截断到 200 字符。
/// 返回 `(命中列表, 是否因 --limit 提前停止)`;命中恒含绝对路径 `file` 字段。
pub fn grep_hits(
    dir: &Path,
    pattern: &str,
    glob: Option<&str>,
    ignore_case: bool,
    manifest_only: bool,
    scope: Option<&str>,
    limit: Option<usize>,
) -> Result<(Vec<JValue>, bool)> {
    use std::collections::HashSet;
    if pattern.is_empty() {
        return Err(Error::BadArg("检索文本不能为空".into()));
    }
    let matcher = match glob {
        Some(g) => Some(
            globset::Glob::new(g)
                .map_err(|e| Error::BadArg(format!("`--glob` = {g:?} 非法:{e}")))?
                .compile_matcher(),
        ),
        None => None,
    };
    let needle = if ignore_case {
        pattern.to_lowercase()
    } else {
        String::new()
    };
    let bundle = open(dir)?;
    let scan = bundle.scan()?;
    let scope = resolve_scope(&bundle, &scan, dir, scope)?;
    let visit_dirs: HashSet<&PathBuf> = scan.visits.iter().map(|v| &v.dir).collect();
    let mut hits: Vec<JValue> = Vec::new();
    let mut stopped = false;
    'outer: for (vi, v) in scan.visits.iter().enumerate() {
        if !within_subtree(&scan, vi, scope) {
            continue;
        }
        let Some(meta) = v.meta.as_ref() else {
            continue;
        };
        let branch_json = serde_json::json!({ "path": v.rel, "id": meta.id, "title": meta.title });
        // 候选文件:`(分支内相对路径, 磁盘路径, 是否已登记)`
        let mut candidates: Vec<(String, PathBuf, bool)> = Vec::new();
        if manifest_only {
            for e in &meta.entries {
                if e.is_file_like() {
                    candidates.push((e.path.clone(), v.dir.join(&e.path), true));
                }
            }
        } else {
            for entry in walkdir::WalkDir::new(&v.dir)
                .min_depth(1)
                .sort_by_file_name()
                .into_iter()
                .filter_entry(|e| {
                    if e.depth() == 0 {
                        return true;
                    }
                    let name = e.file_name().to_string_lossy().to_string();
                    // 保留名 / 系统噪声 / 锁文件 / 子 bundle(`.str` 硬边界)
                    if util::is_reserved_name(&name)
                        || util::is_lock_file(&name)
                        || util::is_os_noise(&name)
                        || util::is_sub_bundle(&name)
                    {
                        return false;
                    }
                    // 其它分支目录(含 `.str.toml` 的目录)不进入:各自作为 visit 单独遍历
                    let p = e.path();
                    if e.file_type().is_dir()
                        && (visit_dirs.contains(&p.to_path_buf())
                            || p.join(util::META_FILE).is_file())
                    {
                        return false;
                    }
                    if scan.ignore.is_empty() {
                        return true;
                    }
                    let rel = bundle.rel(p);
                    let is_dir = e.file_type().is_dir();
                    !scan.ignore.is_ignored(&rel, is_dir)
                })
                .flatten()
            {
                if !entry.file_type().is_file() {
                    continue;
                }
                let rel = entry
                    .path()
                    .strip_prefix(&v.dir)
                    .map(|p| p.to_string_lossy().to_string())
                    .unwrap_or_default();
                let registered = meta.entries.iter().any(|e| e.path == rel);
                candidates.push((rel, entry.path().to_path_buf(), registered));
            }
        }
        for (rel, p, registered) in candidates {
            if let Some(m) = &matcher
                && !m.is_match(&rel)
            {
                continue;
            }
            let Ok(bytes) = std::fs::read(&p) else {
                continue;
            };
            if bytes.contains(&0u8) || String::from_utf8(bytes.clone()).is_err() {
                continue;
            }
            let text = String::from_utf8_lossy(&bytes);
            for (i, line) in text.lines().enumerate() {
                let hit = if ignore_case {
                    line.to_lowercase().contains(&needle)
                } else {
                    line.contains(pattern)
                };
                if !hit {
                    continue;
                }
                hits.push(serde_json::json!({
                    "branch": branch_json,
                    "entry": rel,
                    "file": p.display().to_string(),
                    "registered": registered,
                    "line": i + 1,
                    "text": clip_line(line, 200),
                }));
                if limit.is_some_and(|n| hits.len() >= n) {
                    stopped = true;
                    break 'outer;
                }
            }
        }
    }
    Ok((hits, stopped))
}

/// `str grep`:正文全文检索(打印 [`grep_hits`] 的结果,按分支分组)。
/// `--real-path` 让命中行显示绝对路径(便于管道给其它命令);JSON 恒含 `file` 绝对路径;
/// `--scope` / `[dir]` 决定检索范围(缺省当前节点)。
#[allow(clippy::too_many_arguments)]
pub fn grep(
    dir: &Path,
    pattern: &str,
    glob: Option<&str>,
    ignore_case: bool,
    manifest_only: bool,
    scope: Option<&str>,
    real_path: bool,
    limit: Option<usize>,
    json: bool,
) -> Result<()> {
    let (hits, stopped) =
        grep_hits(dir, pattern, glob, ignore_case, manifest_only, scope, limit)?;
    if json {
        println!("{}", serde_json::to_string_pretty(&hits).unwrap_or_default());
    } else if hits.is_empty() {
        println!("(无命中)");
    } else {
        let mut last_branch = String::new();
        for h in &hits {
            let bp = h["branch"]["path"].as_str().unwrap_or(".").to_string();
            if bp != last_branch {
                println!(
                    "{bp}  {}  {}",
                    h["branch"]["id"].as_str().unwrap_or("-"),
                    h["branch"]["title"].as_str().unwrap_or("(无标题)")
                );
                last_branch = bp;
            }
            let loc = if real_path {
                h["file"].as_str().unwrap_or("")
            } else {
                h["entry"].as_str().unwrap_or("")
            };
            println!(
                "  {}:{}: {}",
                loc,
                h["line"].as_u64().unwrap_or(0),
                h["text"].as_str().unwrap_or("")
            );
        }
    }
    if stopped {
        let n = limit.unwrap_or(0);
        println!("…(已达 --limit = {n},提前停止)");
    }
    Ok(())
}

/// `str tags` 的收集段:全 bundle 的分支级标签词表(按使用次数降序,再按标签名升序)。
pub fn tag_counts(dir: &Path) -> Result<Vec<(String, usize)>> {
    let bundle = open(dir)?;
    let scan = bundle.scan()?;
    let mut counts: std::collections::BTreeMap<String, usize> = Default::default();
    for v in &scan.visits {
        if let Some(meta) = v.meta.as_ref() {
            for t in &meta.tags {
                *counts.entry(t.clone()).or_default() += 1;
            }
        }
    }
    let mut rows: Vec<(String, usize)> = counts.into_iter().collect();
    rows.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
    Ok(rows)
}

/// `str tags`:打印 [`tag_counts`] 的结果。
pub fn tags(dir: &Path, json: bool) -> Result<()> {
    let rows = tag_counts(dir)?;
    if json {
        let arr: Vec<JValue> = rows
            .iter()
            .map(|(t, c)| serde_json::json!({ "tag": t, "count": c }))
            .collect();
        println!("{}", serde_json::to_string_pretty(&arr).unwrap_or_default());
        return Ok(());
    }
    if rows.is_empty() {
        println!("(bundle 内尚无标签)");
        return Ok(());
    }
    for (t, c) in &rows {
        println!("{c}\t{t}");
    }
    Ok(())
}

/// `str where` 的收集段:目标分支与 ROOT → 目标的链条(面包屑 JSON)。
pub fn where_json(dir: &Path, uuid: Option<String>) -> Result<JValue> {
    let bundle = open(dir)?;
    let scan = bundle.scan()?;
    let idx = target_branch(&bundle, &scan, dir, uuid.as_deref())?;
    let chain: Vec<usize> = scan.ancestors(idx);
    let node_json = |i: usize| {
        let v = &scan.visits[i];
        let m = v.meta.as_ref();
        serde_json::json!({
            "path": v.rel,
            "depth": v.depth,
            "id": m.and_then(|m| m.id.clone()),
            "title": m.and_then(|m| m.title.clone()),
            "type": m.and_then(|m| m.r#type.clone()),
        })
    };
    Ok(serde_json::json!({
        "bundle": bundle.name(),
        "target": node_json(idx),
        "chain": chain.iter().map(|i| node_json(*i)).collect::<Vec<JValue>>(),
    }))
}

/// `str where`:定位分支 —— 打印从 ROOT 到目标的完整链条(面包屑)。
pub fn where_(dir: &Path, uuid: Option<String>, json: bool) -> Result<()> {
    let v = where_json(dir, uuid)?;
    if json {
        println!("{}", serde_json::to_string_pretty(&v).unwrap_or_default());
        return Ok(());
    }
    let chain = v["chain"].as_array().cloned().unwrap_or_default();
    let target_path = v["target"]["path"].as_str().unwrap_or(".").to_string();
    for (level, node) in chain.iter().enumerate() {
        let rel = node["path"].as_str().unwrap_or(".");
        let title = node["title"].as_str().unwrap_or("(无标题)");
        let id = node["id"].as_str().unwrap_or("-");
        let type_ = node["type"].as_str().unwrap_or("-");
        let indent = "  ".repeat(level);
        let mark = if level == 0 { "" } else { "└─ " };
        let tail = if rel == target_path { "  ← 目标" } else { "" };
        println!("{indent}{mark}{rel}  {id}  {title}({type_}){tail}");
    }
    Ok(())
}

/// `str get` 的公共解析段:校验 `--path` 并定位目标分支上的条目。
///
/// 两种合法形态:① **已登记**条目(单段名,任意实体 role);
/// ② **内容文件夹子项**(多段路径,首段须是已登记 `role = "dir"` 的条目,
/// 其余段为磁盘上的未登记子项 —— 内容文件夹的子项本就不参与清单比对,规范 §4.8)。
struct LocatedEntry {
    /// 条目所在分支的目录。
    dir: PathBuf,
    /// 条目所在分支的 bundle 相对路径。
    rel: String,
    /// 分支 id / 标题(`--info` 用)。
    branch_id: Option<String>,
    branch_title: Option<String>,
    /// 命中的条目行(内容文件夹子项为按磁盘合成的行)。
    entry: Entry,
    /// 是否来自 `entries[]` 清单(false = 内容文件夹未登记子项)。
    registered: bool,
}

fn get_entry(dir: &Path, uuid: Option<String>, path: &str) -> Result<LocatedEntry> {
    let invalid = |why: &str| {
        Error::BadArg(format!("`--path` = {path:?} 非法:{why}(先 `str ls` 查看清单)"))
    };
    if path.is_empty()
        || path.starts_with('/')
        || path.ends_with('/')
        || path.split('/').any(|s| s.is_empty() || s == "." || s == "..")
    {
        return Err(invalid("路径段不得为空 / `.` / `..`"));
    }
    let bundle = open(dir)?;
    let scan = bundle.scan()?;
    let idx = target_branch(&bundle, &scan, dir, uuid.as_deref())?;
    let v = &scan.visits[idx];
    let meta = v
        .meta
        .as_ref()
        .ok_or_else(|| Error::BadArg(format!("{} 的 `.str.toml` 解析失败", v.rel)))?;
    // ① 已登记条目(精确匹配)
    if let Some(entry) = meta.entries.iter().find(|e| e.path == path) {
        return Ok(LocatedEntry {
            dir: v.dir.clone(),
            rel: v.rel.clone(),
            branch_id: meta.id.clone(),
            branch_title: meta.title.clone(),
            entry: entry.clone(),
            registered: true,
        });
    }
    // ② 内容文件夹子项:首段必须是已登记的 `dir` 条目,其余段按磁盘解析
    let (first, _) = path.split_once('/').ok_or_else(|| {
        Error::BadArg(format!(
            "{} 的清单中未登记条目 `{path}`(先 `str ls` 查看;磁盘上新文件请先 `str sync` 补登)",
            v.rel
        ))
    })?;
    let dir_entry = meta
        .entries
        .iter()
        .find(|e| e.path == first && e.role == "dir")
        .ok_or_else(|| {
            Error::BadArg(format!(
                "`{first}` 不是已登记的内容目录(role = dir):未登记的散落文件请先 `str sync` 补登"
            ))
        })?;
    let p = v.dir.join(&dir_entry.path).join(&path[first.len() + 1..]);
    let meta_of = std::fs::metadata(&p).map_err(|e| Error::io(&p, e))?;
    if !meta_of.is_file() {
        return Err(Error::BadArg(format!(
            "`{path}` 不是文件(目录请用 `str ls` 查看)"
        )));
    }
    let size = meta_of.len() as i64;
    let sha256 = util::sha256_file(&p).ok();
    let media_type = crate::cmd::media_type_for(path);
    let role = if media_type.is_some() { "payload" } else { "asset" };
    Ok(LocatedEntry {
        dir: v.dir.clone(),
        rel: v.rel.clone(),
        branch_id: meta.id.clone(),
        branch_title: meta.title.clone(),
        entry: Entry {
            path: path.to_string(),
            role: role.into(),
            media_type,
            size: Some(size),
            sha256,
            ..Default::default()
        },
        registered: false,
    })
}

/// `str get --info` 的收集段:目标条目的元信息 JSON(含所属分支)。
pub fn get_info(dir: &Path, uuid: Option<String>, path: &str) -> Result<JValue> {
    let loc = get_entry(dir, uuid, path)?;
    Ok(serde_json::json!({
        "branch": { "path": loc.rel, "id": loc.branch_id, "title": loc.branch_title },
        "registered": loc.registered,
        "entry": {
            "path": loc.entry.path,
            "role": loc.entry.role,
            "id": loc.entry.id,
            "type": loc.entry.r#type,
            "title": loc.entry.title,
            "summary": loc.entry.summary,
            "note": loc.entry.note,
            "media_type": loc.entry.media_type,
            "size": loc.entry.size,
            "sha256": loc.entry.sha256,
            "count": loc.entry.count,
            "optional": loc.entry.optional,
            "schema": loc.entry.schema,
        },
    }))
}

/// `str get` 的收集段:读取目标条目正文(结构类条目一律拒绝并指路)。
pub fn get_bytes(dir: &Path, uuid: Option<String>, path: &str) -> Result<Vec<u8>> {
    let loc = get_entry(dir, uuid, path)?;
    let entry = &loc.entry;
    if entry.is_branch() {
        return Err(Error::BadArg(format!(
            "`{}` 是子分支条目(role = {}):元信息用 `str show` 查看,正文请对其中的具体条目再 `str get`",
            entry.path, entry.role
        )));
    }
    if entry.is_link() {
        return Err(Error::BadArg(format!(
            "`{}` 是链接条目(role = link):请对目标分支 `{}` 使用 `str get`",
            entry.path,
            entry.target.as_deref().unwrap_or("-")
        )));
    }
    if loc.registered && entry.role == "dir" {
        return Err(Error::BadArg(format!(
            "`{0}` 是内容目录(role = dir):请用 `str ls` 查看其内容,或用多段路径读其中的文件(如 `--path {0}/<文件>`)",
            entry.path
        )));
    }
    // 两种形态下 entry.path 都是相对分支目录的完整路径(未登记子项为「首段/余段」)
    let p = loc.dir.join(&entry.path);
    std::fs::read(&p).map_err(|e| Error::io(&p, e))
}

/// `str get`:读取一个**已登记**条目的正文(单文件直出 stdout,不展开整树)。
/// `--info` 只打印该条目的元信息 JSON。
pub fn get(dir: &Path, uuid: Option<String>, path: &str, info: bool) -> Result<()> {
    if info {
        let j = get_info(dir, uuid, path)?;
        println!("{}", serde_json::to_string_pretty(&j).unwrap_or_default());
        return Ok(());
    }
    let bytes = get_bytes(dir, uuid, path)?;
    use std::io::Write as _;
    std::io::stdout()
        .write_all(&bytes)
        .map_err(|e| Error::Other(e.to_string()))
}

// ─────────────────────────── reveal ───────────────────────────

/// 平台适配:macOS 上把 `.str` 目录标记为 bundle,并让 `.str.toml` 可见。
pub fn reveal(dir: &Path) -> Result<()> {
    let bundle = open(dir)?;
    let scan = bundle.scan()?;
    let root = bundle.root.display().to_string();
    if cfg!(target_os = "macos") {
        // Finder 里显示包内容的前提是 bundle 位(SetFile 属于 Xcode CLI 工具)
        let status = std::process::Command::new("SetFile")
            .args(["-a", "B", &root])
            .status();
        match status {
            Ok(s) if s.success() => println!("已设置 bundle 位:{root}"),
            _ => println!(
                "未找到 `SetFile`(需 Xcode Command Line Tools)。手动执行:SetFile -a B {}",
                root
            ),
        }
        let mut n = 0;
        for v in &scan.visits {
            let p = bundle.meta_path(&v.dir);
            let _ = std::process::Command::new("chflags")
                .args(["nohidden", &p.display().to_string()])
                .status();
            n += 1;
        }
        println!("已取消 {n} 个 `.str.toml` 的隐藏标记");
    } else {
        println!("当前平台无 bundle 概念:`.str` 就是普通目录,`.str.toml` 为点文件(可能默认隐藏)。");
    }
    Ok(())
}

// ─────────────────────────── codes ───────────────────────────

/// 列出全部错误码(测试矩阵用)。
pub fn list_codes() {
    for c in code::ALL {
        println!("{c}");
    }
}

/// 便捷:把相对路径映射为绝对路径。
pub fn abs(p: &str) -> PathBuf {
    let path = Path::new(p);
    if path.is_absolute() {
        path.to_path_buf()
    } else {
        std::env::current_dir()
            .unwrap_or_else(|_| PathBuf::from("."))
            .join(path)
    }
}