surjection-core 1.2.0

Core library of Surjection: MCP servers, skills and secret references for AI coding clients
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
//! Migration from SkillDock (SPEC 15.1): the synthetic
//! `fixtures/skilldock-home` (a home folder with `~/.skilldock` and the
//! client files SkillDock wrote) migrates to a golden store; `~/.skilldock`
//! is never changed; SkillDock's wrappers are offered for replacement;
//! plaintext values go to the extraction wizard and never reach the store;
//! the report lists every item. Everything lives in a `TempHome`.

mod support;

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

use sha2::{Digest, Sha256};
use support::{Fx, copy_dir, fixtures};
use surjection_core::adapters::detect::NoRegistry;
use surjection_core::apply::{Action, Decision, EntryState, OnConflict, PlanOptions};
use surjection_core::migrate::{self, ItemKind, ItemStatus, Offer, Report};
use surjection_core::remote::git::SystemRunner;
use surjection_core::skills::link::{self, SkillLedger};
use surjection_core::skills::{LinkKind, LinkStatus, SkillsEnv};
use surjection_core::store::tags::TagKind;

static RUNNER: SystemRunner = SystemRunner {
    idle_timeout: Duration::from_secs(60),
};
static NO_REGISTRY: NoRegistry = NoRegistry;

/// Values written in plain text in the fixture; none may reach the store.
const PLAINTEXT: [&str; 7] = [
    "fixture-env-value",
    "fixture-arg-value",
    "fixture-header-value",
    "fixture-placeholder",
    "fixture-remote-env-value",
    "fixture-unused",
    "fixture-url-pass",
];

struct Setup {
    fx: Fx,
    /// HEAD of `~/.skilldock/skills/team-review` (a git repository).
    team_review_head: String,
    /// HEAD of `~/.skilldock/backup/repo`.
    backup_head: String,
}

fn skilldock(fx: &Fx) -> PathBuf {
    fx.th.home().join(".skilldock")
}

/// A git repository at `dir` on `main` with every file committed once,
/// with a fixed signature so the commit id does not depend on the clock.
fn git_repo(dir: &Path, origin: Option<&str>) -> String {
    let mut options = git2::RepositoryInitOptions::new();
    options.initial_head("main").external_template(false);
    let repo = git2::Repository::init_opts(dir, &options).unwrap();
    if let Some(url) = origin {
        repo.remote("origin", url).unwrap();
    }
    let mut index = repo.index().unwrap();
    index
        .add_all(["*"].iter(), git2::IndexAddOption::DEFAULT, None)
        .unwrap();
    index.write().unwrap();
    let tree = repo.find_tree(index.write_tree().unwrap()).unwrap();
    let signature =
        git2::Signature::new("test", "test@example.invalid", &git2::Time::new(0, 0)).unwrap();
    repo.commit(Some("HEAD"), &signature, &signature, "fixture", &tree, &[])
        .unwrap()
        .to_string()
}

/// A directory link at `link` to `target`: a junction on Windows, a
/// symbolic link elsewhere.
fn dir_link(target: &Path, link: &Path) {
    std::fs::create_dir_all(link.parent().unwrap()).unwrap();
    #[cfg(windows)]
    junction::create(target, link).unwrap();
    #[cfg(unix)]
    std::os::unix::fs::symlink(target, link).unwrap();
}

/// The fixture home, plus what a repository cannot hold: the git
/// repositories, links from Claude Code's skill folder into SkillDock's
/// library (one named like the skill, one not), a skill holding a
/// token-shaped value and one whose TOML file holds a random value under a
/// credential key (both assembled here).
fn setup() -> Setup {
    let fx = Fx::new();
    copy_dir(&fixtures().join("skilldock-home"), &fx.th.home());
    let sd = skilldock(&fx);
    let team_review_head = git_repo(
        &sd.join("skills").join("team-review"),
        Some("https://example.invalid/team/team-review.git"),
    );
    let backup = sd.join("backup").join("repo");
    std::fs::create_dir_all(backup.join("mcp")).unwrap();
    std::fs::write(
        backup.join("mcp").join("servers.json"),
        "{\"servers\": []}\n",
    )
    .unwrap();
    let backup_head = git_repo(&backup, None);
    let leaky = sd.join("skills").join("leaky");
    std::fs::create_dir_all(&leaky).unwrap();
    let token = ["gh", "p_", "FAKE0000000000000000000000000000000000"].concat();
    std::fs::write(
        leaky.join("SKILL.md"),
        format!("---\nname: leaky\n---\n\nexport GH={token}\n"),
    )
    .unwrap();
    // Not a token format: only the store's TOML rule (a high-entropy value
    // under a credential key) catches it.
    let toml_secret = sd.join("skills").join("toml-secret");
    std::fs::create_dir_all(&toml_secret).unwrap();
    std::fs::write(
        toml_secret.join("SKILL.md"),
        "---\nname: toml-secret\n---\n\nReads config.toml.\n",
    )
    .unwrap();
    let random = ["Xq7vR2pL9m", "K4tW8zN3bY", "6cH1jF5dG0sA"].concat();
    std::fs::write(
        toml_secret.join("config.toml"),
        format!("api_token = \"{random}\"\n"),
    )
    .unwrap();
    let claude_skills = fx.th.home().join(".claude").join("skills");
    dir_link(
        &sd.join("skills").join("repo-notes"),
        &claude_skills.join("repo-notes"),
    );
    dir_link(
        &sd.join("skills").join("team-review"),
        &claude_skills.join("old-review"),
    );
    Setup {
        fx,
        team_review_head,
        backup_head,
    }
}

/// A hash of every path, file and link target below `dir` (links are not
/// followed).
fn tree_hash(dir: &Path) -> String {
    fn walk(root: &Path, dir: &Path, hasher: &mut Sha256) {
        let mut entries: Vec<_> = std::fs::read_dir(dir)
            .unwrap()
            .map(|entry| entry.unwrap().path())
            .collect();
        entries.sort();
        for path in entries {
            let relative = path.strip_prefix(root).unwrap().to_string_lossy();
            let meta = std::fs::symlink_metadata(&path).unwrap();
            hasher.update(relative.as_bytes());
            if meta.file_type().is_symlink() {
                hasher.update(b"link");
                hasher.update(
                    std::fs::read_link(&path)
                        .unwrap()
                        .to_string_lossy()
                        .as_bytes(),
                );
            } else if meta.is_dir() {
                hasher.update(b"dir");
                walk(root, &path, hasher);
            } else {
                hasher.update(b"file");
                hasher.update(std::fs::read(&path).unwrap());
                hasher.update(meta.len().to_le_bytes());
            }
        }
    }
    let mut hasher = Sha256::new();
    walk(dir, dir, &mut hasher);
    hasher
        .finalize()
        .iter()
        .map(|byte| format!("{byte:02x}"))
        .collect()
}

/// Every store file except `.git` and the store identity (a fresh ULID),
/// as `== path ==` blocks; line endings as LF (the fixture checks out with
/// CRLF where git converts them).
fn store_tree(fx: &Fx, redact: &[(&str, &str)]) -> String {
    fn walk(root: &Path, dir: &Path, out: &mut Vec<(String, String)>) {
        for entry in std::fs::read_dir(dir).unwrap() {
            let path = entry.unwrap().path();
            let relative = path
                .strip_prefix(root)
                .unwrap()
                .to_string_lossy()
                .replace('\\', "/");
            if relative == ".git" || relative == "loadout.toml" {
                continue;
            }
            if path.is_dir() {
                walk(root, &path, out);
            } else {
                let text = std::fs::read_to_string(&path)
                    .unwrap()
                    .replace("\r\n", "\n");
                out.push((relative, text));
            }
        }
    }
    let root = fx.home.store_dir();
    let mut files = Vec::new();
    walk(&root, &root, &mut files);
    files.sort();
    let mut text = String::new();
    for (path, content) in files {
        text.push_str(&format!("== {path} ==\n{content}"));
        if !content.ends_with('\n') {
            text.push('\n');
        }
    }
    for (from, to) in redact {
        text = text.replace(from, to);
    }
    text
}

/// The report as one line per item, then the extractions.
fn report_text(report: &Report) -> String {
    let mut text = String::new();
    for item in &report.items {
        text.push_str(&format!(
            "[{}] {} {}{}: {}{}\n",
            item.status.as_str(),
            item.kind.as_str(),
            item.name,
            item.id
                .as_ref()
                .map_or_else(String::new, |id| format!(" -> {id}")),
            item.detail,
            item.code
                .map_or_else(String::new, |code| format!(" ({code})")),
        ));
        for offer in &item.offers {
            text.push_str(&format!(
                "    offer: {}\n",
                serde_json::to_string(offer).unwrap()
            ));
        }
    }
    for extraction in &report.extractions {
        text.push_str(&format!(
            "extract {} {} -> ${{secret:{}}} ({}, default {})\n",
            extraction.server,
            extraction.field,
            extraction.alias,
            extraction.reason,
            extraction.suggested_ref
        ));
    }
    text
}

fn item<'a>(report: &'a Report, kind: ItemKind, name: &str) -> &'a migrate::Item {
    report
        .items
        .iter()
        .find(|item| item.kind == kind && item.name == name)
        .unwrap_or_else(|| panic!("no {kind:?} item {name:?} in\n{}", report_text(report)))
}

#[test]
fn the_dry_run_creates_nothing_and_lists_every_item() {
    let s = setup();
    let fx = &s.fx;
    let before = tree_hash(&skilldock(fx));
    let claude = fx.read(&fx.claude());
    let migration = migrate::plan(None, &fx.ax()).unwrap();
    assert_eq!(tree_hash(&skilldock(fx)), before, "~/.skilldock changed");
    assert_eq!(fx.read(&fx.claude()), claude);
    assert!(
        !fx.home.store_dir().exists() && !fx.home.state_dir().exists(),
        "the dry run created Surjection data"
    );
    let report = &migration.report;
    assert_eq!(report.source, "~/.skilldock");

    // Every top-level entry of ~/.skilldock, and every record and skill
    // folder, is in the report.
    let names: Vec<&str> = report.items.iter().map(|i| i.name.as_str()).collect();
    for record in [
        "context7",
        "fetch",
        "Remote-Docs",
        "notes",
        "time",
        "Docs-Search",
        "linear",
        "plugin-helper",
        "broken",
    ] {
        assert!(
            names.contains(&record),
            "no item for record {record:?}: {names:?}"
        );
    }
    for skill in [
        "repo-notes",
        "team-review",
        "market-helper",
        "gh-tree-skill",
        "leaky",
        "toml-secret",
        "retired-skill",
    ] {
        assert!(
            names.contains(&skill),
            "no item for skill {skill:?}: {names:?}"
        );
    }
    for path in [
        "~/.skilldock/credentials/github.json",
        "~/.skilldock/credentials/skillhub.json",
        "~/.skilldock/data/publishing",
        "~/.skilldock/plugins",
        "~/.skilldock/logs",
        "~/.skilldock/backup/repo",
        "~/.skilldock/backup/last-sync.json",
        "~/.skilldock/skills/README.txt",
    ] {
        assert!(names.contains(&path), "no item for {path}: {names:?}");
    }
    for key in [
        "theme",
        "agentSkillsCompatibilityEnabled",
        "skillInstallActivation",
        "mcpInstallActivation",
        "defaultOpenToolId",
        "language",
        "githubBackup",
    ] {
        item(report, ItemKind::Setting, key);
    }
    assert_eq!(
        item(report, ItemKind::Server, "plugin-helper").status,
        ItemStatus::Skipped
    );
    assert_eq!(
        item(report, ItemKind::Server, "broken").status,
        ItemStatus::NeedsReview
    );
    let leaky = item(report, ItemKind::Skill, "leaky");
    assert_eq!(leaky.status, ItemStatus::NeedsReview);
    assert_eq!(leaky.code, Some("leak_detected"));
    let credential = item(
        report,
        ItemKind::Credential,
        "~/.skilldock/credentials/github.json",
    );
    assert_eq!(credential.status, ItemStatus::NeedsReview);
    assert!(matches!(
        credential.offers[..],
        [Offer::KeyringToken { .. }]
    ));
    let notes = item(report, ItemKind::Server, "notes");
    assert!(notes.offers.contains(&Offer::MachinePath {
        server: "notes".to_owned()
    }));
    assert!(notes.detail.contains("legacy-ide"), "{}", notes.detail);
    // A file the store's TOML rule refuses is caught before the commit.
    let toml_secret = item(report, ItemKind::Skill, "toml-secret");
    assert_eq!(
        toml_secret.code,
        Some("leak_detected"),
        "{}",
        toml_secret.detail
    );
    // SkillDock's tag keys: `<name>\n<path>`, an older bare lower-cased
    // name, and `installedSkills[].tag`.
    for (folder, tag) in [
        ("repo-notes", "tags: docs"),
        ("team-review", "tags: team"),
        ("market-helper", "tags: tools"),
    ] {
        let skill = item(report, ItemKind::Skill, folder);
        assert!(skill.detail.contains(tag), "{folder}: {}", skill.detail);
    }
    assert!(!names.iter().any(|name| name.contains('\n')));
    // `github-copilot` is Surjection's `copilot`.
    let docs = item(report, ItemKind::Server, "Docs-Search");
    assert!(
        docs.detail.contains("enabled for copilot"),
        "{}",
        docs.detail
    );
    assert!(
        !docs.detail.contains("no Surjection adapter"),
        "{}",
        docs.detail
    );
    // mcp-remote with env: the header takes the env value (then a secret
    // reference), env is dropped, the unused key is named; the source URL
    // with a password is left out of the homepage.
    let linear = item(report, ItemKind::Server, "linear");
    assert_eq!(linear.status, ItemStatus::NeedsReview);
    assert!(
        linear
            .detail
            .contains("headers.Authorization may be a secret"),
        "{}",
        linear.detail
    );
    assert!(
        linear
            .detail
            .contains("did not use were dropped: UNUSED_KEY"),
        "{}",
        linear.detail
    );
    assert!(
        linear.detail.contains("left out of meta.homepage"),
        "{}",
        linear.detail
    );
    // Non-git sources stay local, with a note; a GitHub tree URL is split.
    let market = item(report, ItemKind::Skill, "market-helper");
    assert_eq!(market.status, ItemStatus::NeedsReview);
    assert!(
        market
            .detail
            .contains("marketplace source has no update path"),
        "{}",
        market.detail
    );
    assert!(market.detail.contains("source: local"), "{}", market.detail);
    let tree = item(report, ItemKind::Skill, "gh-tree-skill");
    assert!(
        tree.detail
            .contains("source: https://github.com/example-org/skills;"),
        "{}",
        tree.detail
    );
    // A link not named like the skill id is listed, not recorded.
    let old = item(report, ItemKind::SkillLink, "claude-code/old-review");
    assert_eq!(old.status, ItemStatus::NeedsReview);
    assert_eq!(old.id.as_deref(), Some("team-review"));
    // No report text holds a plaintext value or an absolute temp path.
    let text = report_text(report);
    for value in PLAINTEXT {
        assert!(!text.contains(value), "{value} in the report");
    }
    let root = fx.th.root().to_string_lossy().into_owned();
    assert!(!text.contains(&root), "an absolute path in the report");
    insta::assert_snapshot!("dry_run_report", text);
    assert!(migration.files().any(|f| f == "servers/context7.toml"));
}

#[test]
fn the_fixture_migrates_to_a_golden_store() {
    let s = setup();
    let fx = &s.fx;
    let store = fx.store();
    let head_before = store.head().unwrap();
    let commits_before = fx.commit_count();
    let before = tree_hash(&skilldock(fx));
    let claude = fx.read(&fx.claude());

    let applied = migrate::apply(&store, &fx.ax()).unwrap();

    assert_eq!(tree_hash(&skilldock(fx)), before, "~/.skilldock changed");
    assert_eq!(fx.read(&fx.claude()), claude, "a client file was written");
    // One commit, after the pre-migrate tag on the store as it was.
    assert_eq!(fx.commit_count(), commits_before + 1);
    let commit = applied.commit.clone().unwrap();
    let log = fx.log();
    assert_eq!(log[0].id, commit);
    assert_eq!(log[0].summary, "migrate: skilldock (7 servers, 4 skills)");
    let tag = store.tag(&applied.tag).unwrap().unwrap();
    assert!(
        applied.tag.starts_with("auto/pre-migrate/"),
        "{}",
        applied.tag
    );
    assert_eq!(tag.kind, TagKind::Auto);
    assert_eq!(tag.target, head_before);
    let post = store
        .tag(applied.post_tag.as_deref().unwrap())
        .unwrap()
        .unwrap();
    assert!(post.name.starts_with("auto/post-migrate/"), "{}", post.name);
    assert_eq!(post.target, commit);
    assert_eq!(
        applied.report.servers,
        [
            "context7",
            "fetch",
            "remote-docs",
            "notes",
            "time",
            "docs-search",
            "linear"
        ]
    );
    assert_eq!(
        applied.report.skills,
        [
            "gh-tree-skill",
            "market-helper",
            "repo-notes",
            "team-review"
        ]
    );

    // The golden store: servers, skills without `.git`, metadata, settings.
    let tree = store_tree(fx, &[(&s.team_review_head, "<team-review-head>")]);
    assert!(
        !tree.contains("== skills/team-review/.git"),
        "nested .git copied"
    );
    for value in PLAINTEXT {
        assert!(!tree.contains(value), "{value} reached the store");
    }
    assert!(
        !tree.contains("FAKE0000"),
        "the leaky skill reached the store"
    );
    assert!(
        tree.contains("commit = \"<team-review-head>\""),
        "no source commit"
    );
    insta::assert_snapshot!("golden_store", tree);

    // The backup repository, bare-cloned with its history.
    assert_eq!(
        applied.backup_import.as_deref(),
        Some("imports/skilldock-backup.git")
    );
    let bare =
        git2::Repository::open_bare(fx.home.imports_dir().join("skilldock-backup.git")).unwrap();
    assert!(bare.is_bare());
    assert_eq!(
        bare.head()
            .unwrap()
            .peel_to_commit()
            .unwrap()
            .id()
            .to_string(),
        s.backup_head
    );

    // The link into SkillDock's library is owned now, and the next skills
    // sync re-points it to the store copy (an update).
    let link_path = fx
        .th
        .home()
        .join(".claude")
        .join("skills")
        .join("repo-notes");
    let ledger = SkillLedger::load(&fx.fs, &fx.home.state_dir()).unwrap();
    let owned = ledger.get(&link_path).expect("the link is owned");
    assert_eq!(owned.skill_id, "repo-notes");
    let sx = SkillsEnv {
        env: &fx.env,
        fs: &fx.fs,
        home: &fx.home,
        registry: &NO_REGISTRY,
        runner: &RUNNER,
        link_kind: LinkKind::Junction,
    };
    let report = link::sync(&store, &sx).unwrap();
    let result = report
        .results
        .iter()
        .find(|r| r.path == link_path)
        .unwrap_or_else(|| panic!("{report:#?}"));
    assert_eq!(result.status, LinkStatus::Updated);
    let target = std::fs::canonicalize(&link_path).unwrap();
    assert_eq!(
        target,
        std::fs::canonicalize(fx.home.store_dir().join("skills").join("repo-notes")).unwrap()
    );
    // The link not named like the skill was neither owned nor moved.
    let old = fx
        .th
        .home()
        .join(".claude")
        .join("skills")
        .join("old-review");
    assert!(
        SkillLedger::load(&fx.fs, &fx.home.state_dir())
            .unwrap()
            .get(&old)
            .is_none()
    );
    assert_eq!(
        std::fs::canonicalize(&old).unwrap(),
        std::fs::canonicalize(skilldock(fx).join("skills").join("team-review")).unwrap()
    );
    assert_eq!(
        tree_hash(&skilldock(fx)),
        before,
        "the sync changed ~/.skilldock"
    );
}

#[test]
fn skilldock_wrappers_are_offered_for_replacement() {
    let s = setup();
    let fx = &s.fx;
    let store = fx.store();
    let applied = migrate::apply(&store, &fx.ax()).unwrap();
    let report = &applied.report;

    let context7 = item(report, ItemKind::Server, "context7");
    assert!(context7.detail.contains("tools denied: get-library-docs"));
    let remote = item(report, ItemKind::Server, "Remote-Docs");
    assert!(
        remote
            .detail
            .contains("unwrapped from SkillDock's mcp-remote wrapper")
    );
    // Codex has native tool filters: its wrapped entry collides with the
    // native definition and is offered for replacement.
    let wrapped = item(report, ItemKind::ClientEntry, "codex/context7");
    assert_eq!(wrapped.status, ItemStatus::NeedsReview);
    assert_eq!(wrapped.code, Some("collision"));
    assert!(
        wrapped.detail.contains("mcp-filter wrapper"),
        "{}",
        wrapped.detail
    );
    assert_eq!(
        wrapped.offers,
        [Offer::ReplaceWrapper {
            client: "codex".to_owned(),
            name: "context7".to_owned(),
            command: "surject adopt codex/context7".to_owned(),
        }]
    );
    // Claude Code has none: the wrapper is offered too, with why the
    // native definition cannot be written there yet.
    let blocked = item(report, ItemKind::ClientEntry, "claude-code/context7");
    assert_eq!(blocked.status, ItemStatus::NeedsReview);
    assert_eq!(
        blocked.code,
        Some("unsupported_field"),
        "{}",
        blocked.detail
    );
    assert!(
        blocked.detail.contains("mcp-filter wrapper"),
        "{}",
        blocked.detail
    );
    assert!(matches!(blocked.offers[..], [Offer::ReplaceWrapper { .. }]));
    // SkillDock managed `fetch` and it renders identically: adopted on the
    // first apply without a write. `time` was imported from Codex and is
    // identical there: the scan enabled it.
    let fetch = item(report, ItemKind::ClientEntry, "claude-code/fetch");
    assert_eq!(fetch.status, ItemStatus::Migrated, "{}", fetch.detail);
    let time = item(report, ItemKind::ClientEntry, "codex/time");
    assert_eq!(time.status, ItemStatus::Migrated, "{}", time.detail);
    assert!(
        fx.read(&fx.home.store_dir().join("servers").join("time.toml"))
            .contains("clients = [\"codex\"]")
    );

    // The first apply leaves the wrapper as a collision; replacing it
    // (`surject adopt codex/context7`) writes the native entry with
    // Codex's own tool filter.
    let codex = fx.th.home().join(".codex").join("config.toml");
    let plan = fx.plan();
    let entry = support::entry(&plan, &codex, "context7");
    assert_eq!(entry.state, EntryState::Collision);
    assert!(entry.unresolved);
    assert_eq!(
        support::entry(&plan, &fx.claude(), "fetch").action,
        Action::Adopt
    );
    let (report, _) = fx.apply_with(PlanOptions {
        decisions: vec![Decision {
            client: "codex".to_owned(),
            name: "context7".to_owned(),
            resolution: OnConflict::Overwrite,
        }],
        ..PlanOptions::default()
    });
    let entry = support::result_entry(&report, &codex, "context7");
    assert_eq!(entry.action, Action::AdoptOverwrite, "{entry:#?}");
    let text = fx.read(&codex);
    assert!(!text.contains("mcp-filter"), "{text}");
    assert!(
        text.contains("args = [\"-y\", \"@upstash/context7-mcp\"]"),
        "{text}"
    );
    assert!(text.contains("\"get-library-docs\""), "{text}");
}

#[test]
fn plaintext_values_go_to_the_extraction_wizard() {
    let s = setup();
    let fx = &s.fx;
    let store = fx.store();
    let applied = migrate::apply(&store, &fx.ax()).unwrap();
    let report = &applied.report;
    let fields: Vec<(&str, &str, &str)> = report
        .extractions
        .iter()
        .map(|e| (e.server.as_str(), e.field.as_str(), e.alias.as_str()))
        .collect();
    assert_eq!(
        fields,
        [
            (
                "remote-docs",
                "headers.Authorization",
                "REMOTE_DOCS_AUTHORIZATION"
            ),
            ("notes", "args[2]", "NOTES_TOKEN"),
            ("notes", "env.NOTES_API_KEY", "NOTES_NOTES_API_KEY"),
            ("linear", "headers.Authorization", "LINEAR_AUTHORIZATION"),
        ]
    );
    for extraction in &report.extractions {
        assert_eq!(
            extraction.suggested_ref,
            format!("keyring://surjection/{}", extraction.alias)
        );
    }
    let notes = item(report, ItemKind::Server, "notes");
    assert_eq!(notes.status, ItemStatus::NeedsReview);
    assert!(notes.offers.contains(&Offer::SetSecret {
        alias: "NOTES_NOTES_API_KEY".to_owned(),
        command: "surject secrets set NOTES_NOTES_API_KEY --keyring".to_owned(),
    }));
    // The store holds references, never the values; non-secrets stay.
    let text = fx.read(&fx.home.store_dir().join("servers").join("notes.toml"));
    assert!(
        text.contains("NOTES_API_KEY = \"${secret:NOTES_NOTES_API_KEY}\""),
        "{text}"
    );
    assert!(text.contains("\"${secret:NOTES_TOKEN}\""), "{text}");
    assert!(text.contains("LOG_LEVEL = \"info\""), "{text}");
    let remote = fx.read(&fx.home.store_dir().join("servers").join("remote-docs.toml"));
    assert!(
        remote.contains("Authorization = \"Bearer ${secret:REMOTE_DOCS_AUTHORIZATION}\""),
        "{remote}"
    );
    // mcp-remote with env: the env value reached the header, then became a
    // reference; the server has no env and no homepage.
    let linear = fx.read(&fx.home.store_dir().join("servers").join("linear.toml"));
    assert!(
        linear.contains("Authorization = \"Bearer ${secret:LINEAR_AUTHORIZATION}\""),
        "{linear}"
    );
    assert!(linear.contains("transport = \"sse\""), "{linear}");
    assert!(
        !linear.contains("[env]") && !linear.contains("homepage"),
        "{linear}"
    );
    // No secret was stored anywhere (catalog or keyring): the alias is
    // missing until `secrets set`, so the entry is blocked, not written.
    assert!(fx.read_opt_catalog().is_none());
    assert!(
        fx.keyring
            .peek("surjection", "NOTES_NOTES_API_KEY")
            .is_none()
    );
    let blocked = item(report, ItemKind::ClientEntry, "claude-code/notes");
    assert_eq!(blocked.status, ItemStatus::NeedsReview);
    assert_eq!(blocked.code, Some("missing_secret"), "{}", blocked.detail);
    // The history holds none of the values either.
    let all = store_tree(fx, &[]);
    for value in PLAINTEXT {
        assert!(!all.contains(value));
    }
}

#[test]
fn a_second_migration_changes_nothing() {
    let s = setup();
    let fx = &s.fx;
    let store = fx.store();
    migrate::apply(&store, &fx.ax()).unwrap();
    let commits = fx.commit_count();
    let again = migrate::apply(&store, &fx.ax()).unwrap();
    assert_eq!(again.commit, None);
    assert_eq!(fx.commit_count(), commits);
    assert!(again.report.servers.is_empty() && again.report.skills.is_empty());
    let context7 = item(&again.report, ItemKind::Server, "context7");
    assert_eq!(context7.status, ItemStatus::Skipped);
    assert_eq!(context7.code, Some("already_exists"));
    let backup = item(&again.report, ItemKind::Backup, "~/.skilldock/backup/repo");
    assert_eq!(backup.status, ItemStatus::Skipped);
    assert_eq!(again.backup_import, None);
}

/// A migration whose commit landed but whose link recording did not (the
/// lock timed out, the ledger did not save): running it again records the
/// links of the skills already in the store.
#[test]
fn a_second_run_repairs_links_lost_after_the_commit() {
    let s = setup();
    let fx = &s.fx;
    let store = fx.store();
    migrate::apply(&store, &fx.ax()).unwrap();
    let link_path = fx
        .th
        .home()
        .join(".claude")
        .join("skills")
        .join("repo-notes");
    let state = fx.home.state_dir();
    let mut ledger = SkillLedger::load(&fx.fs, &state).unwrap();
    assert!(ledger.forget(&link_path));
    ledger.save(&fx.fs, &state).unwrap();

    let again = migrate::apply(&store, &fx.ax()).unwrap();
    assert_eq!(again.commit, None);
    let skill = item(&again.report, ItemKind::Skill, "repo-notes");
    assert_eq!(skill.status, ItemStatus::Skipped);
    assert!(skill.detail.contains("1 link recorded"), "{}", skill.detail);
    let link = item(&again.report, ItemKind::SkillLink, "claude-code/repo-notes");
    assert_eq!(link.status, ItemStatus::Migrated);
    let ledger = SkillLedger::load(&fx.fs, &state).unwrap();
    assert_eq!(ledger.get(&link_path).unwrap().skill_id, "repo-notes");
    // A third run finds it owned and records nothing more.
    let third = migrate::apply(&store, &fx.ax()).unwrap();
    assert!(
        !third
            .report
            .items
            .iter()
            .any(|i| i.kind == ItemKind::SkillLink && i.name == "claude-code/repo-notes")
    );
}

/// SkillDock omits `agentSkillsCompatibilityEnabled` when unset and treats
/// the `agent-skills` library provider as compatibility on.
#[test]
fn the_agent_skills_provider_turns_compatibility_on() {
    let s = setup();
    let fx = &s.fx;
    let settings = skilldock(fx).join("config").join("settings.json");
    std::fs::write(
        &settings,
        "{\n  \"skillLibraryProvider\": \"agent-skills\",\n  \"theme\": \"light\"\n}\n",
    )
    .unwrap();
    let migration = migrate::plan(None, &fx.ax()).unwrap();
    let provider = item(&migration.report, ItemKind::Setting, "skillLibraryProvider");
    assert_eq!(provider.status, ItemStatus::Migrated, "{}", provider.detail);
    assert_eq!(provider.detail, "agents_cli_compat = true");
    let store = fx.store();
    migrate::apply(&store, &fx.ax()).unwrap();
    let text = fx.read(&fx.home.store_dir().join("settings.toml"));
    assert!(text.contains("agents_cli_compat = true"), "{text}");
}

#[test]
fn no_skilldock_data_is_not_found() {
    let fx = Fx::new();
    let err = migrate::plan(None, &fx.ax()).unwrap_err();
    assert_eq!(err.code().as_str(), "not_found");
}

trait CatalogRead {
    fn read_opt_catalog(&self) -> Option<String>;
}

impl CatalogRead for Fx {
    fn read_opt_catalog(&self) -> Option<String> {
        std::fs::read_to_string(self.home.store_dir().join("secrets.toml")).ok()
    }
}