mind-cli 0.48.0

A manager for agent tooling (skills, agents, rules, tools) that melds arbitrary git repos and links items into your agent directories.
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
//! Implementation of `mind dump` (DUMP-1 through DUMP-8).
//!
//! Writes a super-source `mind.toml` that reproduces the current melded and
//! installed state, so melding the output recreates the same source set and
//! install selection.

use std::collections::{BTreeSet, HashMap};
use std::io::Write;
use std::path::PathBuf;

use serde::Serialize;

use crate::catalog;
use crate::error::{MindError, Result};
use crate::manifest::Manifest;
use crate::mindfile::MindToml;
use crate::paths::Paths;
use crate::source::{Registry, Source};

// ---------------------------------------------------------------------------
// Serializable shapes that round-trip through `toml::from_str::<MindToml>`.
// Field names match the serde renames in mindfile.rs exactly (deny_unknown_fields).
// ---------------------------------------------------------------------------

/// Top-level emitted document.
#[derive(Serialize)]
struct DumpDoc {
    source: DumpSource,
    discover: DumpDiscover,
}

/// `[source]` section of the emitted document.
#[derive(Serialize)]
struct DumpSource {
    description: String,
}

/// `[discover]` section of the emitted document.
#[derive(Serialize)]
struct DumpDiscover {
    sources: Vec<DumpEntry>,
}

/// One `[[discover.sources]]` entry in the emitted document.
///
/// Fields must match the serde renames of `mindfile::NestedSource` exactly so
/// `toml::from_str::<MindToml>` accepts the output (DUMP-7, DSC-30).
///
/// DUMP-1 / DUMP-4 / DSC-65: the pin is emitted as `pin-ref = <commit>` for
/// every source with a recorded commit, regardless of the source's pin kind.
/// This is the authoritative per-entry pin (DSC-65) that re-melding the output
/// will apply unconditionally. A source with no recorded commit (e.g. a
/// never-synced linked local source) emits no pin field.
#[derive(Serialize)]
struct DumpEntry {
    source: String,

    #[serde(rename = "namespace", skip_serializing_if = "Option::is_none")]
    namespace: Option<String>,

    /// An item link's explicit kind (LNK-23, DSC-100): emitted only when the
    /// instance recorded one (STO-81). A kind resolved from the containing
    /// directory or the file's frontmatter re-resolves identically from the
    /// pinned clone, so it is not emitted.
    #[serde(skip_serializing_if = "Option::is_none")]
    kind: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    roots: Option<Vec<String>>,

    /// Consumer `--add-root` roots (STO-55, DUMP-11): emitted as `add-roots = [...]`
    /// when the source recorded them at meld time, so re-melding the output composes
    /// the same extra convention roots and reoffers the items they contribute.
    /// Absent when none. Mirrors how `roots` (DUMP-4) is emitted.
    #[serde(rename = "add-roots", skip_serializing_if = "Option::is_none")]
    add_roots: Option<Vec<String>>,

    /// Flat skill layout (DUMP-10): emitted as `flat-skills = true` when flat
    /// discovery is in effect for the source (the consumer override STO-44 or the
    /// source's own `[source].flat-skills`, DSC-74). Absent otherwise. Mirrors how
    /// `roots` (DUMP-4) is emitted.
    #[serde(rename = "flat-skills", skip_serializing_if = "Option::is_none")]
    flat_skills: Option<bool>,

    /// Pin: emit the recorded commit sha as `pin-ref` (DUMP-1, DUMP-4, DSC-65).
    /// Absent when no commit has been recorded for this source.
    #[serde(rename = "pin-ref", skip_serializing_if = "Option::is_none")]
    pin_ref: Option<String>,

    /// Under `--ranges`, a version-pinned source's range in place of
    /// `pin-ref` (VER-120).
    #[serde(rename = "pin-version", skip_serializing_if = "Option::is_none")]
    pin_version: Option<String>,

    /// A profile-tracked source's enabled profiles minus `default` (PROF-28).
    /// Never alongside `install = true`.
    #[serde(skip_serializing_if = "Option::is_none")]
    profiles: Option<Vec<String>>,

    /// `false` when a profile-tracked source has `default` disabled (PROF-28).
    #[serde(rename = "default-profile", skip_serializing_if = "Option::is_none")]
    default_profile: Option<bool>,

    // Exactly one of these two is emitted per entry (never both, never neither).
    // When install_items is Some the install bool is absent; when install_items
    // is None the bool is emitted. The filtering logic guarantees mutual
    // exclusion.
    #[serde(skip_serializing_if = "Option::is_none")]
    install: Option<bool>,

    #[serde(rename = "install-items", skip_serializing_if = "Option::is_none")]
    install_items: Option<Vec<String>>,

    /// The source's mind home when it is an extra home (HOME-10).
    #[serde(rename = "mind-home", skip_serializing_if = "Option::is_none")]
    mind_home: Option<String>,
}

// ---------------------------------------------------------------------------
// Public entry point
// ---------------------------------------------------------------------------

/// Run `mind dump`.
///
/// - `paths` - resolved paths for this invocation
/// - `output` - write to this file instead of stdout when `Some`
/// - `whole_sources` - when true, emit `install = true` for every source
///   regardless of what is actually installed (DUMP-3)
/// - `ranges` - when true, emit a version-pinned source's range as
///   `pin-version` instead of its commit (VER-120)
pub fn run(
    paths: &Paths,
    output: Option<PathBuf>,
    whole_sources: bool,
    ranges: bool,
) -> Result<()> {
    // spec: DUMP-1 DUMP-2 DUMP-3 DUMP-4 DUMP-5 DUMP-6 DUMP-7 DUMP-8 DUMP-9 LNK-13

    // DUMP-9: dump always writes TOML; --json has no effect on the output format.
    // Print a note to stderr so the caller is not confused by the TOML output.
    if crate::render::ctx().json {
        eprintln!("note: --json does not apply to dump; output is always TOML");
    }

    let registry = Registry::load(paths)?;
    let manifest = Manifest::load(paths)?;

    // spec: DUMP-8 — with no melded sources, emit a valid super-source whose
    // [discover].sources is empty, and exit 0.
    let entries = build_entries(paths, &registry, &manifest, whole_sources, ranges)?;

    let doc = DumpDoc {
        source: DumpSource {
            description: "Generated by `mind dump`. Meld this file to reproduce the recorded \
                          source set and install selection."
                .to_string(),
        },
        discover: DumpDiscover { sources: entries },
    };

    let text = toml::to_string(&doc).map_err(|e| MindError::TomlWrite {
        path: output.clone().unwrap_or_else(|| PathBuf::from("<stdout>")),
        source: e,
    })?;

    match output {
        None => {
            // spec: DUMP-1 — stdout by default
            let stdout = std::io::stdout();
            let mut out = stdout.lock();
            out.write_all(text.as_bytes())
                .and_then(|_| out.flush())
                .map_err(|e| MindError::io("<stdout>", e))
        }
        Some(path) => {
            // spec: DUMP-1 — --output <path>
            std::fs::write(&path, &text).map_err(|e| MindError::io(&path, e))
        }
    }
}

// ---------------------------------------------------------------------------
// Core logic
// ---------------------------------------------------------------------------

/// Build the `[[discover.sources]]` entry list.
fn build_entries(
    paths: &Paths,
    registry: &Registry,
    manifest: &Manifest,
    whole_sources: bool,
    ranges: bool,
) -> Result<Vec<DumpEntry>> {
    let mut entries = Vec::with_capacity(registry.sources.len());

    for source in &registry.sources {
        // spec: LNK-13 -- an item-link instance is dumped as a reconstructed
        // deep-URL entry rather than the generic per-source shape (DUMP-1/
        // DUMP-4), since a link's `source` spec is not the repo URL alone.
        if source.item_path.is_some() {
            match build_link_entry(paths, source, manifest, whole_sources)? {
                Some(entry) => entries.push(entry),
                None => {
                    // Defensive only: every link instance registered through
                    // the normal meld/learn/sync paths always has a recorded
                    // commit (LNK-3/LNK-4 -- the checkout point is never
                    // DefaultBranch for a link, so `meld_recursive` always
                    // resolves and records one). A hand-edited registry could
                    // still lack one; without a commit there is no ref to
                    // build a syntactically valid deep URL from, so skip with
                    // a note rather than emit an unpinned (and therefore
                    // non-reproducing) link entry.
                    eprintln!(
                        "note: skipping item link {} (no recorded commit to pin the \
                         reconstructed URL to)",
                        source.name
                    );
                }
            }
            continue;
        }
        let mut entry = build_entry(paths, source, manifest, whole_sources)?;
        // spec: VER-120 -- `--ranges` trades the frozen commit of a
        // version-pinned source for its range. An item link (above) keeps its
        // commit, which is also its URL's ref segment.
        if ranges && let crate::source::Pin::Version(vp) = &source.pin {
            entry.pin_ref = None;
            entry.pin_version = Some(vp.range.clone());
        }
        entries.push(entry);
    }

    Ok(entries)
}

/// Build a `[[discover.sources]]` entry for an item-link source instance
/// (LNK-13).
///
/// Reconstructs a deep tree URL that [`crate::source::parse_spec`] accepts as
/// an item link (item-link.md LNK-1) from the recorded `host`/`owner`/`repo`/
/// `item_path`, with the recorded commit as the URL's `<ref>` segment. Emits
/// `pin-ref = <commit>` alongside it, exactly like every other dump entry
/// (DUMP-1/DUMP-4/DSC-65): the pin-ref is the entry's authoritative pin
/// (curator pin outranks an item link's own URL-ref pin, DSC-65 over LNK-3),
/// so it is what actually pins the reproduction; the URL's ref segment is set
/// to the SAME commit so the two never disagree, and so the URL is
/// syntactically complete (a `tree`/`blob` link always requires a ref
/// segment) even before `pin-ref` is applied.
///
/// The `namespace` field carries the recorded IDENTITY alias (`as_alias`,
/// STO-58) rather than the display-only effective prefix that ordinary
/// entries emit (DUMP-4's `effective_prefix`): a link's alias is part of its
/// identity (`host/owner/repo#path@alias`, LNK-4), so re-melding must apply
/// the SAME alias value to `apply_alias` for the identity to round-trip. When
/// no identity alias was recorded, `namespace` is omitted and the source's
/// own `[source].prefix` (if any) is picked back up naturally when the link
/// entry is re-melded, exactly as it was at the original meld.
///
/// `roots`/`add-roots`/`flat-skills` are never emitted for a link entry: an
/// item-link instance's catalog is exactly its one skill (LNK-7), so
/// convention scan roots play no part in it.
fn build_link_entry(
    paths: &Paths,
    source: &Source,
    manifest: &Manifest,
    whole_sources: bool,
) -> Result<Option<DumpEntry>> {
    let Some(url) = build_link_url(source) else {
        return Ok(None);
    };

    let (install, install_items) = if whole_sources {
        (Some(true), None)
    } else {
        compute_install_directive(paths, source, manifest)?
    };

    Ok(Some(DumpEntry {
        source: url,
        namespace: source.as_alias.clone(),
        // spec: LNK-23 -- the recorded explicit kind, when there is one.
        kind: source.item_kind.map(|k| k.as_str().to_string()),
        roots: None,
        add_roots: None,
        flat_skills: None,
        pin_ref: source.commit.clone(),
        pin_version: None,
        profiles: None,
        default_profile: None,
        install,
        install_items,
        mind_home: dump_home(paths, source),
    }))
}

/// Reconstruct a deep item-link URL from a source's recorded `host`/`owner`/
/// `repo`/`item_path` and its recorded commit (LNK-13). Returns `None` when
/// the source has no `item_path` or no recorded commit.
///
/// A skill link always uses the `tree/<ref>/<path>` shape (never
/// `blob/.../SKILL.md`): `parse_link_tail` (source.rs) accepts a `tree` link
/// naming the skill directory directly, so there is no need to reconstruct the
/// `blob` + trailing `/SKILL.md` alternative. A FILE link (LNK-20) uses
/// `blob/<ref>/<path>` instead (LNK-23): a blob URL is what a forge uses to
/// name a file, and it is the shape the link was pasted in. A local
/// (`host == "local"`) source's
/// `url` field holds a bare filesystem path (no `file://` prefix, stripped at
/// parse time), so the `file://` scheme is re-added here to reach the local
/// link branch of `parse_spec`.
///
/// Built from the structural `host`/`owner`/`repo` fields, NOT `source.url`:
/// `url` is rewritten to the SSH form (`git@host:owner/repo`) whenever the
/// consumer has `ssh = true` in their config (`Source::prefer_ssh`), and that
/// SSH form is not a shape `parse_spec`'s item-link branch accepts, so
/// building from it would emit a URL that fails to re-meld (C32). A remote
/// link is therefore always reconstructed as `https://{host}/{owner}/{repo}`
/// regardless of the recorded `url`'s scheme; a consumer with `ssh = true`
/// still gets it rewritten to SSH again on re-meld via the same
/// `prefer_ssh` pass, so nothing is lost by emitting https here.
fn build_link_url(source: &Source) -> Option<String> {
    let item_path = source.item_path.as_deref()?;
    let commit = source.commit.as_deref()?;
    // spec: LNK-23 -- a file link is a blob URL, a skill link a tree URL.
    let marker = if crate::catalog::is_file_link(item_path) {
        "blob"
    } else {
        "tree"
    };
    if source.is_local() {
        // A local source's `url` is a bare filesystem path (never rewritten
        // by prefer_ssh), so it is still safe to build from directly here.
        Some(format!(
            "file://{}/{marker}/{commit}/{item_path}",
            source.url
        ))
    } else {
        Some(format!(
            "https://{}/{}/{}/{marker}/{commit}/{item_path}",
            source.host, source.owner, source.repo
        ))
    }
}

/// Build one `[[discover.sources]]` entry for a single melded source.
fn build_entry(
    paths: &Paths,
    source: &Source,
    manifest: &Manifest,
    whole_sources: bool,
) -> Result<DumpEntry> {
    // spec: DUMP-1 — use source URL for remote sources; use URL (path) for local.
    // For local sources `source.url` holds the filesystem path (see parse_spec).
    let source_spec = source.url.clone();

    // spec: DUMP-4 — effective prefix: consumer alias wins over the source's
    // own [source].prefix (the same precedence as catalog::scan_source_at).
    let effective_alias = effective_prefix(paths, source);

    // spec: DUMP-4 — scan roots recorded at meld time (STO-17).
    let roots = source.roots.clone();

    // spec: DUMP-11 — the consumer `--add-root` roots recorded at meld time
    // (STO-55). Emitted so re-melding the output composes the same extra
    // convention roots and reoffers the items an added root contributes. Like
    // `roots` (DUMP-4), only the recorded consumer override is emitted.
    let add_roots = source.add_roots.clone();

    // spec: DUMP-10 — emit flat-skills from the STO-44 consumer override only,
    // exactly mirroring how `roots` (DUMP-4) emits `source.roots` and NOT the
    // source's own `[source].flat-skills`. A source's own flat-skills is re-read
    // from its mind.toml when the output is re-melded, so emitting it here would
    // be redundant and would trip the DSC-60 "ignored" gate on re-meld.
    let flat_skills = source.flat_skills.then_some(true);

    // spec: DUMP-1 / DUMP-4 / DSC-65 — emit the recorded commit sha as `pin-ref`
    // for every source that has one. This is the authoritative per-entry pin
    // (DSC-65): a re-meld of the output will apply it unconditionally, pinning
    // each source to the exact revision recorded at dump time. A source with no
    // recorded commit (e.g. a never-synced linked local source) emits no pin.
    let pin_ref = source.commit.clone();

    // spec: DUMP-2 / DUMP-3 — item filtering.
    // spec: PROF-28 -- a profile-tracked source emits its enabled profiles and
    // the explicit extras instead of an install directive (never `install =
    // true` alongside `profiles`). `--whole-sources` is unchanged (DUMP-3).
    let (install, install_items, profiles, default_profile) = if whole_sources {
        // spec: DUMP-3 — --whole-sources: always install = true.
        (Some(true), None, None, None)
    } else if source.is_profile_tracked() {
        let (profiles, default_profile, extras) = profile_directive(source, manifest);
        (None, extras, Some(profiles), default_profile)
    } else {
        let (install, install_items) = compute_install_directive(paths, source, manifest)?;
        (install, install_items, None, None)
    };

    Ok(DumpEntry {
        source: source_spec,
        namespace: effective_alias,
        // An ordinary source is not an item link, so it carries no kind (LNK-23).
        kind: None,
        roots,
        add_roots,
        flat_skills,
        pin_ref,
        pin_version: None,
        profiles,
        default_profile,
        install,
        install_items,
        mind_home: dump_home(paths, source),
    })
}

/// The `mind-home` an entry records (HOME-10): the source's home when it is
/// an extra home, with a home-directory prefix written as `~`. A source in the
/// default home records none, so the output melds into whatever the default
/// home is where it is melded.
fn dump_home(paths: &Paths, source: &Source) -> Option<String> {
    crate::paths::source_home(&source.name)?;
    let home = paths.home_of(&source.name);
    if let Some(user) = dirs::home_dir()
        && let Ok(rest) = home.strip_prefix(&user)
    {
        return Some(format!("~/{}", rest.display()));
    }
    Some(home.display().to_string())
}

/// The profile directive for a profile-tracked source (PROF-28):
/// `(profiles, default_profile, install_items)`.
///
/// `profiles` is the recorded enabled set minus `default`; `default_profile` is
/// `Some(false)` when `default` is not enabled; `install_items` lists the
/// source's installed items that are explicit and whose bare `kind:name` is
/// outside the recorded snapshot (`None` when there are none). Reads only the
/// recorded state, never the catalog, so it stays pure.
fn profile_directive(
    source: &Source,
    manifest: &Manifest,
) -> (Vec<String>, Option<bool>, Option<Vec<String>>) {
    let enabled = source.profiles.as_deref().unwrap_or_default();
    let default_on = enabled.iter().any(|p| p == crate::profile::DEFAULT);
    let profiles: Vec<String> = enabled
        .iter()
        .filter(|p| *p != crate::profile::DEFAULT)
        .cloned()
        .collect();
    let snapshot: BTreeSet<&str> = source
        .profile_snapshot
        .as_deref()
        .unwrap_or_default()
        .iter()
        .map(String::as_str)
        .collect();
    let extras: BTreeSet<String> = manifest
        .items
        .values()
        .filter(|item| item.source == source.name && item.is_explicit())
        .map(|item| format!("{}:{}", item.kind.as_str(), item.bare_name))
        .filter(|key| !snapshot.contains(key.as_str()))
        .collect();
    let extras = (!extras.is_empty()).then(|| extras.into_iter().collect());
    (profiles, (!default_on).then_some(false), extras)
}

/// Compute the effective namespace prefix for a source, mirroring the
/// precedence used in `catalog::scan_source_at` (DUMP-4).
///
/// Returns `None` when neither the consumer alias nor the source's own
/// `[source].prefix` is set (or both are empty strings).
fn effective_prefix(paths: &Paths, source: &Source) -> Option<String> {
    // Consumer alias wins.
    if let Some(alias) = &source.alias {
        if !alias.is_empty() {
            return Some(alias.clone());
        }
        // An explicit empty alias suppresses the source's own prefix.
        return None;
    }
    // Fall back to the source's own [source].prefix from its mind.toml.
    let clone_root = source.clone_dir(paths);
    if let Ok(Some(mt)) = MindToml::load(&clone_root)
        && let Some(prefix) = mt.source.prefix
        && !prefix.is_empty()
    {
        return Some(prefix);
    }
    None
}

/// Compute the install directive for one source (DUMP-2).
///
/// Returns `(install, install_items)` where exactly one is `Some`.
///
/// - All offered items installed -> `(Some(true), None)`
/// - No offered items installed -> `(Some(false), None)`
/// - Proper subset installed -> `(None, Some(sorted_bare_refs))`
///
/// The `install_items = []` form is NEVER emitted; that case becomes
/// `install = false` (DUMP-2).
fn compute_install_directive(
    paths: &Paths,
    source: &Source,
    manifest: &Manifest,
) -> Result<(Option<bool>, Option<Vec<String>>)> {
    // Scan the source to find its offered items (bare names).
    let mut offered_items = Vec::new();
    catalog::scan_source(paths, source, &mut offered_items)?;

    // Build the set of offered bare "kind:name" refs from the catalog.
    let offered: BTreeSet<String> = offered_items
        .iter()
        .map(|item| format!("{}:{}", item.kind.as_str(), item.name))
        .collect();

    // Build the set of installed bare "kind:name" refs from the manifest that
    // belong to this source.
    // DUMP-5: items are listed by bare kind:name (catalog/source truth).
    // DUMP-6: items installed as within-source dependencies are included.
    let installed_for_source: HashMap<String, ()> = manifest
        .items
        .values()
        .filter(|item| item.source == source.name)
        .map(|item| {
            let bare_ref = format!("{}:{}", item.kind.as_str(), item.bare_name);
            (bare_ref, ())
        })
        .collect();

    // Intersect: only count installed items that the source actually offers
    // (an item installed from a previous catalog state but no longer offered
    // is excluded from the intersection).
    let installed_and_offered: BTreeSet<String> = offered
        .iter()
        .filter(|ref_| installed_for_source.contains_key(*ref_))
        .cloned()
        .collect();

    if offered.is_empty() {
        // Source offers nothing; emit install = false.
        return Ok((Some(false), None));
    }

    if installed_and_offered.is_empty() {
        // spec: DUMP-2 — none installed -> install = false.
        // Never emit install_items = [].
        return Ok((Some(false), None));
    }

    if installed_and_offered == offered {
        // spec: DUMP-2 — all offered items installed -> install = true.
        return Ok((Some(true), None));
    }

    // spec: DUMP-2 — proper subset -> install_items listing exactly those items.
    // Items are sorted deterministically (BTreeSet is already sorted).
    let items: Vec<String> = installed_and_offered.into_iter().collect();
    Ok((None, Some(items)))
}

// ---------------------------------------------------------------------------
// Unit tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error::ItemKind;
    use crate::manifest::InstalledItem;
    use crate::source::Source;

    // Helper: build a minimal Source struct for testing.
    fn make_source(name: &str, url: &str, commit: Option<&str>) -> Source {
        Source {
            name: name.to_string(),
            url: url.to_string(),
            host: "local".to_string(),
            owner: "test".to_string(),
            repo: name.split('/').next_back().unwrap_or(name).to_string(),
            commit: commit.map(str::to_string),
            description: None,
            alias: None,
            as_alias: None,
            pin: crate::source::Pin::default(),
            roots: None,
            flat_skills: false,
            full_history: false,
            add_roots: None,
            item_path: None,
            item_kind: None,
            curated_by: None,
            origin: None,
            plugin_version: None,
            install_hooks: vec![],
            items_hooks: vec![],
            install_hook: None,
            install_hook_commit: None,
            profiles: None,
            profile_snapshot: None,
            whole_snapshot: None,
            auto_update: None,
        }
    }

    // Helper: build a minimal InstalledItem.
    fn make_installed(kind: ItemKind, name: &str, bare: &str, source: &str) -> InstalledItem {
        InstalledItem {
            kind,
            name: name.to_string(),
            bare_name: bare.to_string(),
            source: source.to_string(),
            commit: "abc".to_string(),
            hash: "def".to_string(),
            store: "store/path".to_string(),
            links: vec![],
            description: None,
            install_hooks: Vec::new(),
            dropped_requires: Vec::new(),
            profiles: Vec::new(),
            explicit: false,
            version: None,
        }
    }

    // ----- Filtering logic (DUMP-2) -----

    #[test]
    fn filtering_all_installed_yields_install_true() {
        // spec: DUMP-2 — every offered item installed -> install = true.
        // (compute_install_directive requires disk access; we test the
        // all-installed branch via the emitted-TOML round-trip below.)
        //
        // Directly test the TOML emitter shape with a hand-crafted entry.
        let entry = DumpEntry {
            source: "/some/path".into(),
            namespace: None,
            kind: None,
            roots: None,
            add_roots: None,
            flat_skills: None,
            pin_ref: None,
            pin_version: None,
            profiles: None,
            default_profile: None,
            install: Some(true),
            install_items: None,
            mind_home: None,
        };
        let doc = DumpDoc {
            source: DumpSource {
                description: "test".into(),
            },
            discover: DumpDiscover {
                sources: vec![entry],
            },
        };
        let text = toml::to_string(&doc).unwrap();
        assert!(text.contains("install = true"), "must emit install = true");
        assert!(
            !text.contains("install-items"),
            "must NOT emit install-items when install = true"
        );
        // spec: DUMP-7 — parses back as a valid MindToml (DSC-3/DSC-30).
        let back: MindToml = toml::from_str(&text)
            .unwrap_or_else(|e| panic!("install=true output must parse as MindToml: {e}"));
        let ns = &back.discover.unwrap().sources[0];
        assert!(ns.install);
        assert!(ns.install_items.is_none());
    }

    #[test]
    fn filtering_none_installed_yields_install_false() {
        // spec: DUMP-2 — none installed -> install = false; never emit [].
        let entry = DumpEntry {
            source: "/some/path".into(),
            namespace: None,
            kind: None,
            roots: None,
            add_roots: None,
            flat_skills: None,
            pin_ref: None,
            pin_version: None,
            profiles: None,
            default_profile: None,
            install: Some(false),
            install_items: None,
            mind_home: None,
        };
        let doc = DumpDoc {
            source: DumpSource {
                description: "test".into(),
            },
            discover: DumpDiscover {
                sources: vec![entry],
            },
        };
        let text = toml::to_string(&doc).unwrap();
        assert!(
            text.contains("install = false"),
            "must emit install = false"
        );
        assert!(
            !text.contains("install-items"),
            "must NOT emit install-items when none installed"
        );
        // spec: DUMP-7
        let back: MindToml = toml::from_str(&text)
            .unwrap_or_else(|e| panic!("install=false output must parse as MindToml: {e}"));
        let ns = &back.discover.unwrap().sources[0];
        assert!(!ns.install);
        assert!(ns.install_items.is_none());
    }

    #[test]
    fn filtering_proper_subset_yields_install_items() {
        // spec: DUMP-2 DUMP-5 — proper subset -> install_items listing bare kind:name.
        // Never emit install_items = [].
        let items = vec!["agent:dev".to_string(), "skill:review".to_string()];
        let entry = DumpEntry {
            source: "/some/path".into(),
            namespace: None,
            kind: None,
            roots: None,
            add_roots: None,
            flat_skills: None,
            pin_ref: None,
            pin_version: None,
            profiles: None,
            default_profile: None,
            install: None,
            install_items: Some(items.clone()),
            mind_home: None,
        };
        let doc = DumpDoc {
            source: DumpSource {
                description: "test".into(),
            },
            discover: DumpDiscover {
                sources: vec![entry],
            },
        };
        let text = toml::to_string(&doc).unwrap();
        assert!(
            text.contains("install-items"),
            "must emit install-items for subset"
        );
        assert!(
            !text.contains("install = true"),
            "must NOT emit install = true when emitting install-items"
        );
        // spec: DUMP-7
        let back: MindToml = toml::from_str(&text)
            .unwrap_or_else(|e| panic!("install_items output must parse as MindToml: {e}"));
        let ns = &back.discover.unwrap().sources[0];
        assert!(
            !ns.install,
            "install bool must be false/absent for subset form"
        );
        let got = ns
            .install_items
            .as_deref()
            .expect("install_items must be present");
        assert_eq!(got, &["agent:dev", "skill:review"][..]);
    }

    #[test]
    fn empty_install_items_is_never_emitted() {
        // spec: DUMP-2 — install_items = [] is NEVER emitted; that case is
        // install = false.
        let entry = DumpEntry {
            source: "/some/path".into(),
            namespace: None,
            kind: None,
            roots: None,
            add_roots: None,
            flat_skills: None,
            pin_ref: None,
            pin_version: None,
            profiles: None,
            default_profile: None,
            install: Some(false),
            install_items: None,
            mind_home: None, // None, not Some([])
        };
        let doc = DumpDoc {
            source: DumpSource {
                description: "test".into(),
            },
            discover: DumpDiscover {
                sources: vec![entry],
            },
        };
        let text = toml::to_string(&doc).unwrap();
        assert!(
            !text.contains("install-items"),
            "install_items=[] must never appear; got: {text}"
        );
        assert!(text.contains("install = false"));
    }

    #[test]
    fn emitted_toml_parses_as_valid_mindtoml() {
        // spec: DUMP-7 — the emitted file is a valid super-source (parses under
        // DSC-3 and DSC-30 deny_unknown_fields) and carries [source].description.
        let doc = DumpDoc {
            source: DumpSource {
                description: "Generated by `mind dump`. Meld this file to reproduce the \
                              recorded source set and install selection."
                    .to_string(),
            },
            discover: DumpDiscover {
                sources: vec![
                    DumpEntry {
                        source: "/path/to/repo".into(),
                        namespace: Some("pfx".into()),
                        kind: None,
                        roots: Some(vec!["packages".into()]),
                        add_roots: Some(vec!["extra".into()]),
                        flat_skills: Some(true),
                        pin_ref: Some("deadbeefdeadbeef1234".into()),
                        pin_version: None,
                        profiles: None,
                        default_profile: None,
                        install: Some(true),
                        install_items: None,
                        mind_home: None,
                    },
                    DumpEntry {
                        source: "https://github.com/owner/repo".into(),
                        namespace: None,
                        kind: None,
                        roots: None,
                        add_roots: None,
                        flat_skills: None,
                        pin_ref: None,
                        pin_version: None,
                        profiles: None,
                        default_profile: None,
                        install: None,
                        install_items: Some(vec!["skill:review".into(), "agent:dev".into()]),
                        mind_home: None,
                    },
                ],
            },
        };
        let text =
            toml::to_string(&doc).unwrap_or_else(|e| panic!("serialization must not fail: {e}"));
        // Must parse back cleanly without unknown-field errors.
        let back: MindToml = toml::from_str(&text)
            .unwrap_or_else(|e| panic!("emitted TOML must parse as MindToml: {e}\nTOML:\n{text}"));
        // [source].description is present.
        assert!(
            back.source.description.is_some(),
            "emitted TOML must carry [source].description"
        );
        // Only [discover].sources; no items of its own.
        assert!(back.items.is_empty(), "emitted TOML must have no [[items]]");
        let disc = back.discover.expect("must have [discover]");
        assert_eq!(disc.sources.len(), 2);
        // First entry: install = true, pin-ref (commit pin) present, alias present.
        let e0 = &disc.sources[0];
        assert!(e0.install, "first entry: install must be true");
        assert_eq!(e0.namespace.as_deref(), Some("pfx"));
        assert_eq!(e0.roots.as_deref(), Some(&["packages".to_string()][..]));
        // spec: DUMP-11 — add-roots round-trips: emitted as `add-roots = ["extra"]`
        // and parses back onto NestedSource.add_roots on the first entry, while the
        // second entry (no add-roots) parses back None.
        assert!(
            text.contains("add-roots = [\"extra\"]"),
            "must emit add-roots for a source with recorded --add-root roots: {text}"
        );
        assert_eq!(
            e0.add_roots.as_deref(),
            Some(&["extra".to_string()][..]),
            "first entry: add_roots must round-trip"
        );
        // spec: DUMP-10 — flat-skills round-trips: emitted as `flat-skills = true`
        // and parses back as NestedSource.flat_skills on the first entry, while the
        // second entry (no flat layout) parses back false.
        assert!(
            text.contains("flat-skills = true"),
            "must emit flat-skills = true"
        );
        assert!(
            e0.flat_skills,
            "first entry: flat_skills must parse back true"
        );
        assert!(
            e0.pin_ref.is_some(),
            "pin-ref must be present for pinned entry"
        );
        // Second entry: install_items present, no install = true.
        let e1 = &disc.sources[1];
        assert!(!e1.install, "second entry: install must be false");
        assert!(
            !e1.flat_skills,
            "second entry: flat_skills must parse back false (no key emitted)"
        );
        // spec: DUMP-11 — second entry has no add-roots, so it parses back None.
        assert!(
            e1.add_roots.is_none(),
            "second entry: add_roots must be None (no key emitted)"
        );
        let items = e1
            .install_items
            .as_deref()
            .expect("install_items must be present");
        assert_eq!(items, &["skill:review", "agent:dev"][..]);
    }

    #[test]
    fn spec_string_round_trips_for_local_path() {
        // Verify that the spec string we emit for a local source round-trips
        // through parse_spec back to the same URL.
        // spec: DUMP-1 DUMP-4
        let source = make_source("local/dev/agents", "/home/dev/agents", Some("abc123"));
        // The emitted spec is source.url for local sources.
        let spec = source.url.clone();
        let parsed = crate::source::parse_spec(&spec)
            .unwrap_or_else(|e| panic!("local spec must round-trip: {e}"));
        assert_eq!(
            parsed.url, source.url,
            "local path spec must round-trip through parse_spec"
        );
    }

    #[test]
    fn spec_string_round_trips_for_https_url() {
        // spec: DUMP-1 DUMP-4
        let url = "https://github.com/owner/repo";
        let source = make_source("github.com/owner/repo", url, None);
        let spec = source.url.clone();
        let parsed = crate::source::parse_spec(&spec)
            .unwrap_or_else(|e| panic!("https spec must round-trip: {e}"));
        assert_eq!(parsed.url, url);
    }

    #[test]
    fn pin_ref_emitted_when_commit_recorded_regardless_of_pin_kind() {
        // spec: DUMP-1 DUMP-4 DSC-65 — the pin is always emitted as `pin-ref`
        // (the recorded commit sha) when the source has a recorded commit,
        // regardless of the source's pin kind (FollowBranch, Tag, Ref, or
        // DefaultBranch). A source with no recorded commit emits no pin.
        let entry_with_commit = DumpEntry {
            source: "/a/b".into(),
            namespace: None,
            kind: None,
            roots: None,
            add_roots: None,
            flat_skills: None,
            pin_ref: Some("deadbeefdeadbeef".into()),
            pin_version: None,
            profiles: None,
            default_profile: None,
            install: Some(true),
            install_items: None,
            mind_home: None,
        };
        let entry_no_commit = DumpEntry {
            source: "/a/b".into(),
            namespace: None,
            kind: None,
            roots: None,
            add_roots: None,
            flat_skills: None,
            pin_ref: None,
            pin_version: None,
            profiles: None,
            default_profile: None,
            install: Some(false),
            install_items: None,
            mind_home: None,
        };

        let text_with = toml::to_string(&DumpDoc {
            source: DumpSource {
                description: "t".into(),
            },
            discover: DumpDiscover {
                sources: vec![entry_with_commit],
            },
        })
        .unwrap();
        let text_without = toml::to_string(&DumpDoc {
            source: DumpSource {
                description: "t".into(),
            },
            discover: DumpDiscover {
                sources: vec![entry_no_commit],
            },
        })
        .unwrap();

        assert!(
            text_with.contains("pin-ref"),
            "must emit pin-ref when a commit is recorded: {text_with}"
        );
        assert!(
            text_with.contains("deadbeefdeadbeef"),
            "must emit the recorded commit sha as pin-ref: {text_with}"
        );
        assert!(
            !text_with.contains("follow-branch"),
            "must NOT emit follow-branch (replaced by pin-ref): {text_with}"
        );
        assert!(
            !text_without.contains("pin-ref"),
            "must NOT emit pin-ref when no commit is recorded: {text_without}"
        );
        // Both must parse as valid MindToml (DUMP-7): NestedSource now accepts pin-ref.
        let _: MindToml = toml::from_str(&text_with)
            .unwrap_or_else(|e| panic!("pinned entry must parse: {e}\n{text_with}"));
        let _: MindToml = toml::from_str(&text_without)
            .unwrap_or_else(|e| panic!("unpinned entry must parse: {e}\n{text_without}"));
    }

    #[test]
    fn install_items_sorted_deterministically() {
        // spec: DUMP-5 — install_items are sorted (kind then name) so output is stable.
        let mut items = [
            "skill:review".to_string(),
            "agent:dev".to_string(),
            "rule:style".to_string(),
        ];
        items.sort();
        assert_eq!(items[0], "agent:dev");
        assert_eq!(items[1], "rule:style");
        assert_eq!(items[2], "skill:review");
    }

    #[test]
    fn emitted_toml_has_no_items_of_its_own() {
        // spec: DUMP-7 — the emitted file declares only [discover].sources;
        // no [[items]] or item globs of its own.
        let doc = DumpDoc {
            source: DumpSource {
                description: "Generated by `mind dump`. test".into(),
            },
            discover: DumpDiscover { sources: vec![] },
        };
        let text = toml::to_string(&doc).unwrap();
        let back: MindToml =
            toml::from_str(&text).unwrap_or_else(|e| panic!("empty doc must parse: {e}"));
        assert!(back.items.is_empty(), "must have no [[items]]");
        assert!(
            !back.is_authoritative(),
            "empty discover.sources must not be authoritative (only sources, no item globs)"
        );
    }

    #[test]
    fn whole_sources_entry_has_install_true() {
        // spec: DUMP-3 — --whole-sources always emits install = true.
        let entry = DumpEntry {
            source: "/a/b".into(),
            namespace: None,
            kind: None,
            roots: None,
            add_roots: None,
            flat_skills: None,
            pin_ref: None,
            pin_version: None,
            profiles: None,
            default_profile: None,
            install: Some(true),
            install_items: None,
            mind_home: None,
        };
        let text = toml::to_string(&DumpDoc {
            source: DumpSource {
                description: "t".into(),
            },
            discover: DumpDiscover {
                sources: vec![entry],
            },
        })
        .unwrap();
        assert!(text.contains("install = true"));
        let back: MindToml = toml::from_str(&text).unwrap();
        assert!(back.discover.unwrap().sources[0].install);
    }

    #[test]
    fn dependency_item_treated_like_any_installed_item() {
        // spec: DUMP-6 — an item installed only as a within-source dependency
        // is part of the installed set just like any other manifest entry.
        // Here we verify that bare_name is what goes into install_items, not
        // the effective name (which may be prefixed).
        let item = make_installed(ItemKind::Skill, "pfx:review", "review", "local/dev/agents");
        // The bare_name is "review", so install_items should list "skill:review".
        let bare_ref = format!("{}:{}", item.kind.as_str(), item.bare_name);
        assert_eq!(bare_ref, "skill:review");
    }

    #[test]
    fn namespace_field_emitted_not_as_key() {
        // spec: DSC-78 — dump emits `namespace = "pfx"` (canonical key), not the
        // legacy `as = "pfx"`, and the value round-trips through NestedSource::namespace.
        let entry = DumpEntry {
            source: "/a/b".into(),
            namespace: Some("pfx".into()),
            kind: None,
            roots: None,
            add_roots: None,
            flat_skills: None,
            pin_ref: None,
            pin_version: None,
            profiles: None,
            default_profile: None,
            install: Some(true),
            install_items: None,
            mind_home: None,
        };
        let doc = DumpDoc {
            source: DumpSource {
                description: "t".into(),
            },
            discover: DumpDiscover {
                sources: vec![entry],
            },
        };
        let text = toml::to_string(&doc).unwrap();
        assert!(
            text.contains("namespace = \"pfx\""),
            "must emit `namespace = \"pfx\"` (canonical key): {text}"
        );
        assert!(
            !text.contains("as = "),
            "must NOT emit the legacy `as = ` key: {text}"
        );
        // Round-trip: the emitted `namespace` key populates NestedSource::namespace,
        // not ::alias.
        let back: MindToml = toml::from_str(&text)
            .unwrap_or_else(|e| panic!("namespace output must parse as MindToml: {e}\n{text}"));
        let ns = &back.discover.unwrap().sources[0];
        assert_eq!(
            ns.namespace.as_deref(),
            Some("pfx"),
            "emitted namespace key must populate NestedSource::namespace"
        );
        assert!(
            ns.alias.is_none(),
            "emitted namespace key must NOT populate NestedSource::alias"
        );
    }

    // ----- PROF-28: profile-tracked sources -----

    const PSRC: &str = "local/test/prof";

    fn tracked(profiles: &[&str], snapshot: &[&str]) -> Source {
        let mut s = make_source(PSRC, "/p/prof", Some("abc"));
        s.profiles = Some(profiles.iter().map(|p| p.to_string()).collect());
        s.profile_snapshot = Some(snapshot.iter().map(|p| p.to_string()).collect());
        s
    }

    /// An installed item of `PSRC` with the given profile reasons / explicit flag.
    fn prof_item(name: &str, profiles: &[&str], explicit: bool) -> InstalledItem {
        let mut i = make_installed(ItemKind::Skill, &format!("pfx:{name}"), name, PSRC);
        i.profiles = profiles.iter().map(|p| p.to_string()).collect();
        i.explicit = explicit;
        i
    }

    fn manifest_of(items: Vec<InstalledItem>) -> Manifest {
        let mut m = Manifest::default();
        for i in items {
            m.items.insert(i.key().into(), i);
        }
        m
    }

    /// Emit and re-parse the `[[discover.sources]]` entry the tracked branch of
    /// `build_entry` produces for `source`.
    fn emit_tracked(
        source: &Source,
        manifest: &Manifest,
    ) -> (String, crate::mindfile::NestedSource) {
        let (profiles, default_profile, extras) = profile_directive(source, manifest);
        let entry = DumpEntry {
            source: source.url.clone(),
            namespace: None,
            kind: None,
            roots: None,
            add_roots: None,
            flat_skills: None,
            pin_ref: source.commit.clone(),
            pin_version: None,
            profiles: Some(profiles),
            default_profile,
            install: None,
            install_items: extras,
            mind_home: None,
        };
        let text = toml::to_string(&DumpDoc {
            source: DumpSource {
                description: "t".into(),
            },
            discover: DumpDiscover {
                sources: vec![entry],
            },
        })
        .unwrap();
        let back: MindToml = toml::from_str(&text)
            .unwrap_or_else(|e| panic!("profile entry must parse as MindToml: {e}\n{text}"));
        let ns = back.discover.unwrap().sources.remove(0);
        (text, ns)
    }

    #[test]
    fn tracked_source_with_default_enabled_emits_profiles_without_default() {
        // spec: PROF-28
        let s = tracked(&["default", "full"], &["skill:a", "skill:b"]);
        let m = manifest_of(vec![
            prof_item("a", &["default", "full"], false),
            prof_item("b", &["full"], false),
        ]);
        let (text, ns) = emit_tracked(&s, &m);
        assert_eq!(ns.profiles.as_deref(), Some(&["full".to_string()][..]));
        assert_eq!(ns.default_profile, None, "default enabled: key omitted");
        assert!(ns.install_items.is_none(), "no explicit extras: {text}");
        assert!(!ns.install, "never install = true with profiles: {text}");
        assert!(!text.contains("install = true"), "{text}");
        ns.validate(std::path::Path::new("mind.toml"))
            .expect("valid entry");
    }

    #[test]
    fn tracked_source_with_default_disabled_emits_default_profile_false() {
        // spec: PROF-28
        let s = tracked(&["full"], &["skill:a"]);
        let m = manifest_of(vec![prof_item("a", &["full"], false)]);
        let (text, ns) = emit_tracked(&s, &m);
        assert_eq!(ns.profiles.as_deref(), Some(&["full".to_string()][..]));
        assert_eq!(ns.default_profile, Some(false), "{text}");
    }

    #[test]
    fn tracked_source_with_only_default_emits_empty_profiles() {
        // spec: PROF-28
        let s = tracked(&["default"], &["skill:a"]);
        let m = manifest_of(vec![prof_item("a", &["default"], false)]);
        let (_, ns) = emit_tracked(&s, &m);
        assert_eq!(ns.profiles.as_deref(), Some(&[][..]));
        assert_eq!(ns.default_profile, None);
    }

    #[test]
    fn tracked_source_emits_explicit_items_outside_the_snapshot() {
        // spec: PROF-28
        let s = tracked(&["default"], &["skill:member", "skill:forgotten-member"]);
        let m = manifest_of(vec![
            // Profile member, installed for the profile: not explicit.
            prof_item("member", &["default"], false),
            // Explicit AND a member (in the snapshot): inside the expansion.
            prof_item("explicit-member", &["default"], true),
            // Hand-installed, no reasons (implicitly explicit), outside it.
            prof_item("extra", &[], false),
            // Explicit with reasons, outside the snapshot.
            prof_item("extra2", &["default"], true),
            // Another source's item never leaks in.
            {
                let mut o = prof_item("other", &[], false);
                o.source = "local/test/other".into();
                o
            },
        ]);
        let mut s = s;
        s.profile_snapshot
            .as_mut()
            .unwrap()
            .push("skill:explicit-member".into());
        let (text, ns) = emit_tracked(&s, &m);
        assert_eq!(
            ns.install_items.as_deref(),
            Some(&["skill:extra".to_string(), "skill:extra2".to_string()][..]),
            "{text}"
        );
        assert!(!text.contains("install = true"), "{text}");
    }

    #[test]
    fn untracked_source_is_not_given_profile_keys() {
        // spec: PROF-28 -- a source with no recorded profile state is emitted
        // exactly as before: the tracked branch is gated on is_profile_tracked.
        let s = make_source(PSRC, "/p/prof", Some("abc"));
        assert!(!s.is_profile_tracked());
        let entry = DumpEntry {
            source: s.url.clone(),
            namespace: None,
            kind: None,
            roots: None,
            add_roots: None,
            flat_skills: None,
            pin_ref: None,
            pin_version: None,
            profiles: None,
            default_profile: None,
            install: Some(true),
            install_items: None,
            mind_home: None,
        };
        let text = toml::to_string(&DumpDoc {
            source: DumpSource {
                description: "t".into(),
            },
            discover: DumpDiscover {
                sources: vec![entry],
            },
        })
        .unwrap();
        assert!(!text.contains("profiles"), "{text}");
        assert!(!text.contains("default-profile"), "{text}");
    }

    #[test]
    fn dump_8_empty_registry_produces_valid_super_source() {
        // spec: DUMP-8 — with no melded sources the document is valid with
        // [discover].sources = [].
        let doc = DumpDoc {
            source: DumpSource {
                description: "Generated by `mind dump`. Meld this file to reproduce the \
                              recorded source set and install selection."
                    .to_string(),
            },
            discover: DumpDiscover { sources: vec![] },
        };
        let text = toml::to_string(&doc).unwrap();
        let back: MindToml =
            toml::from_str(&text).unwrap_or_else(|e| panic!("empty-registry doc must parse: {e}"));
        let disc = back.discover.expect("must have [discover]");
        assert!(disc.sources.is_empty(), "sources must be empty");
    }

    // ----- LNK-13: item-link entry reconstruction -----

    /// Helper: a minimal item-link `Source` (mirrors what `parse_spec` builds
    /// for a deep tree/blob URL). `host = "local"` and `url` a bare path
    /// reproduces the local `file://` link shape; any other host reproduces a
    /// remote forge link.
    fn make_link_source(
        host: &str,
        owner: &str,
        repo: &str,
        url: &str,
        item_path: &str,
        commit: Option<&str>,
    ) -> Source {
        let mut s = make_source(&format!("{host}/{owner}/{repo}"), url, commit);
        s.host = host.to_string();
        s.owner = owner.to_string();
        s.repo = repo.to_string();
        s.item_path = Some(item_path.to_string());
        s
    }

    const SHA: &str = "0123456789abcdef0123456789abcdef01234567";

    #[test]
    fn link_url_reconstructs_and_reparses_for_a_remote_source() {
        // spec: LNK-13 — a remote item-link source's recorded fields
        // reconstruct a `tree/<commit>/<path>` URL that `parse_spec` accepts
        // back as the SAME item-link identity (host/owner/repo#path).
        let source = make_link_source(
            "github.com",
            "acme",
            "repo",
            "https://github.com/acme/repo",
            "skills/foo",
            Some(SHA),
        );
        let url = build_link_url(&source).expect("commit + item_path present");
        assert_eq!(
            url,
            format!("https://github.com/acme/repo/tree/{SHA}/skills/foo")
        );
        let reparsed = crate::source::parse_spec(&url)
            .unwrap_or_else(|e| panic!("reconstructed link URL must reparse: {e}"));
        assert_eq!(reparsed.name, "github.com/acme/repo#skills/foo");
        assert_eq!(reparsed.item_path.as_deref(), Some("skills/foo"));
        assert_eq!(reparsed.pin, crate::source::Pin::Ref(SHA.to_string()));
    }

    #[test]
    fn link_url_reconstructs_and_reparses_for_a_local_file_source() {
        // spec: LNK-13 — a local (`file://`) link source round-trips too: the
        // reconstructed URL re-adds the `file://` scheme the bare `url` field
        // was stripped of at parse time, and reparses to the same identity.
        let source = make_link_source(
            "local",
            "dev",
            "agents",
            "/home/me/dev/agents",
            "skills/foo",
            Some(SHA),
        );
        let url = build_link_url(&source).expect("commit + item_path present");
        assert_eq!(
            url,
            format!("file:///home/me/dev/agents/tree/{SHA}/skills/foo")
        );
        let reparsed = crate::source::parse_spec(&url)
            .unwrap_or_else(|e| panic!("reconstructed file link URL must reparse: {e}"));
        assert_eq!(reparsed.host, "local");
        assert_eq!(reparsed.name, "local/dev/agents#skills/foo");
        assert_eq!(reparsed.url, "/home/me/dev/agents");
        assert_eq!(reparsed.item_path.as_deref(), Some("skills/foo"));
    }

    #[test]
    fn link_url_uses_https_even_when_recorded_url_is_ssh_form() {
        // spec: LNK-13 — when the consumer has `ssh = true` in config,
        // `prefer_ssh` rewrites the recorded `url` on the source to the SSH
        // form (`git@host:owner/repo`), but `parse_spec`'s SSH branch never
        // routes through the item-link parser, so an SSH-form URL is not
        // re-meldable as a link. build_link_url must ignore `source.url` and
        // build from the structural host/owner/repo fields instead, always
        // emitting https, so the reconstructed URL reparses to the SAME
        // item-link identity (C32).
        let source = make_link_source(
            "github.com",
            "o",
            "r",
            "git@github.com:o/r",
            "skills/foo",
            Some(SHA),
        );
        let url = build_link_url(&source).expect("commit + item_path present");
        assert_eq!(
            url,
            format!("https://github.com/o/r/tree/{SHA}/skills/foo"),
            "must build from host/owner/repo, not the SSH-rewritten url: {url}"
        );
        let reparsed = crate::source::parse_spec(&url)
            .unwrap_or_else(|e| panic!("reconstructed https link URL must reparse: {e}"));
        assert_eq!(reparsed.host, "github.com");
        assert_eq!(reparsed.owner, "o");
        assert_eq!(reparsed.repo, "r");
        assert_eq!(reparsed.item_path.as_deref(), Some("skills/foo"));
        assert_eq!(reparsed.name, "github.com/o/r#skills/foo");
    }

    #[test]
    fn link_url_is_none_without_a_recorded_commit() {
        // spec: LNK-13 — no commit means no ref to build a valid URL from;
        // build_link_url reports None so the caller emits the skip note
        // rather than a broken/unpinned entry.
        let source = make_link_source(
            "github.com",
            "acme",
            "repo",
            "https://github.com/acme/repo",
            "skills/foo",
            None,
        );
        assert!(
            build_link_url(&source).is_none(),
            "no recorded commit must yield None, not a guessed ref"
        );
    }

    #[test]
    fn link_entry_namespace_carries_the_identity_alias_not_the_display_prefix() {
        // spec: LNK-13 — the emitted `namespace` for a link entry must be the
        // recorded IDENTITY alias (`as_alias`, STO-58), not the general
        // `effective_prefix()` used for ordinary sources: only `as_alias` is
        // what `apply_alias` needs fed back in to reproduce
        // `host/owner/repo#path@alias` on re-meld. Here `alias` and
        // `as_alias` are deliberately set to DIFFERENT values, mimicking a
        // post-clone display-prefix override (STO-58's carve-out) applying on
        // top of a `--as` identity alias: the entry must still carry the
        // identity one, not the display one.
        let mut source = make_link_source(
            "github.com",
            "acme",
            "repo",
            "https://github.com/acme/repo",
            "skills/foo",
            Some(SHA),
        );
        source.as_alias = Some("fork".into());
        source.alias = Some("displayonly".into());

        let url = build_link_url(&source).unwrap();
        assert_eq!(source.commit.clone(), Some(SHA.to_string()));
        // Directly exercise the field the entry would carry (namespace), the
        // same value `build_link_entry` assigns.
        assert_eq!(source.as_alias.as_deref(), Some("fork"));
        // Reparsing the URL plus applying that alias reproduces the exact
        // instance identity the source was originally registered under.
        let mut reparsed = crate::source::parse_spec(&url).unwrap();
        reparsed.apply_alias(source.as_alias.clone());
        assert_eq!(reparsed.name, "github.com/acme/repo#skills/foo@fork");
    }
}