agent-hub-runtime 0.6.0

AgentHub desktop and companion CLI runtime for Tauri applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
pub(crate) use super::skill_deployment::detach_source_refs_from_adoption_target;
pub use super::skill_deployment::{sync_single_skill_to_tool, DeployIntent};

use serde::Serialize;
use std::collections::{HashMap, HashSet};
use std::fmt;
use std::path::{Path, PathBuf};
use std::time::Instant;

use super::{
    error::{AppError, TargetConflictDetail},
    skill_metadata,
    skill_store::{ScenarioRecord, SkillStore, SkillTargetRecord},
    sync_engine, tool_adapters, tool_service,
};

#[derive(Debug, Clone)]
pub struct ScenarioSyncTarget {
    pub skill_id: String,
    pub skill_name: String,
    pub tool: String,
    pub source: PathBuf,
    pub target: PathBuf,
    pub mode: sync_engine::SyncMode,
    /// Current content hash of the central skill source, copied from
    /// `SkillRecord.content_hash`. Compared against the previously
    /// synced `SkillTargetRecord.source_hash` to skip redundant
    /// Copy-mode resyncs at startup (issue #153).
    pub source_hash: Option<String>,
}

#[derive(Debug, Clone, Serialize)]
pub struct SyncPreviewTarget {
    pub skill_id: String,
    pub skill_name: String,
    pub tool: String,
    pub target_path: String,
    pub mode: String,
}

pub fn ensure_scenario_exists(store: &SkillStore, scenario_id: &str) -> Result<(), AppError> {
    let exists = store
        .get_all_scenarios()
        .map_err(AppError::db)?
        .iter()
        .any(|s| s.id == scenario_id);
    if !exists {
        return Err(AppError::not_found("Scenario not found"));
    }
    Ok(())
}

pub fn enabled_deployable_adapters_for_scenario_skill(
    store: &SkillStore,
    scenario_id: &str,
    skill_id: &str,
) -> Result<Vec<tool_adapters::ToolAdapter>, AppError> {
    let adapters = tool_adapters::enabled_deployable_adapters(store);
    let adapter_keys: Vec<String> = adapters.iter().map(|a| a.key.clone()).collect();

    store
        .ensure_scenario_skill_tool_defaults(scenario_id, skill_id, &adapter_keys)
        .map_err(AppError::db)?;

    let enabled = store
        .get_enabled_tools_for_scenario_skill(scenario_id, skill_id)
        .map_err(AppError::db)?;
    let enabled_set: HashSet<String> = enabled.into_iter().collect();

    Ok(adapters
        .into_iter()
        .filter(|adapter| enabled_set.contains(&adapter.key))
        .collect())
}

pub fn collect_scenario_sync_targets(
    store: &SkillStore,
    scenario_id: &str,
) -> Result<Vec<ScenarioSyncTarget>, AppError> {
    let skills = store
        .get_skills_for_scenario(scenario_id)
        .map_err(AppError::db)?;
    let preference = crate::core::deployment_preferences::Preference::load(
        store,
        crate::core::deployment_preferences::Scope::Global,
    )?;
    let existing_targets = store.get_all_targets().map_err(AppError::db)?;
    let mut targets = Vec::new();

    for skill in &skills {
        let source = PathBuf::from(&skill.central_path);
        let target_name = sync_engine::target_dir_name(&source, &skill.name);
        let adapters =
            enabled_deployable_adapters_for_scenario_skill(store, scenario_id, &skill.id)?;
        for adapter in &adapters {
            let target = deployment_target(adapter, &target_name, &skill.id, &existing_targets);
            let recorded = existing_targets.iter().find(|existing| {
                existing.skill_id == skill.id
                    && existing.tool == adapter.key
                    && Path::new(&existing.target_path) == target
            });
            let mode = preference.for_target(recorded.map(|existing| existing.mode.as_str()));
            targets.push(ScenarioSyncTarget {
                skill_id: skill.id.clone(),
                skill_name: skill.name.clone(),
                tool: adapter.key.clone(),
                source: source.clone(),
                target,
                mode,
                source_hash: skill.content_hash.clone(),
            });
        }
    }

    Ok(targets)
}

pub(crate) fn deployment_target(
    adapter: &tool_adapters::ToolAdapter,
    target_name: &str,
    skill_id: &str,
    existing_targets: &[SkillTargetRecord],
) -> PathBuf {
    let root = adapter.skills_dir();
    existing_targets
        .iter()
        .find(|target| target.skill_id == skill_id && target.tool == adapter.key)
        .map(|target| PathBuf::from(&target.target_path))
        .filter(|path| is_skill_path_within_root(path, &root))
        .unwrap_or_else(|| root.join(target_name))
}

pub(crate) fn is_skill_path_within_root(path: &Path, root: &Path) -> bool {
    path.strip_prefix(root).is_ok_and(|relative| {
        !relative.as_os_str().is_empty()
            && relative
                .components()
                .all(|component| matches!(component, std::path::Component::Normal(_)))
    })
}

pub fn preview_scenario_sync(
    store: &SkillStore,
    scenario_id: &str,
) -> Result<Vec<SyncPreviewTarget>, AppError> {
    collect_scenario_sync_targets(store, scenario_id).map(|targets| {
        targets
            .into_iter()
            .map(|target| SyncPreviewTarget {
                skill_id: target.skill_id,
                skill_name: target.skill_name,
                tool: target.tool,
                target_path: target.target.to_string_lossy().to_string(),
                mode: target.mode.as_str().to_string(),
            })
            .collect()
    })
}

/// Decide which `SyncMode` `is_target_current` should compare against, or
/// `None` if the existing target's mode is incompatible with the desired
/// mode and the skip path must be refused.
///
/// Returns `Some(existing)` when both modes match exactly. Also returns
/// `Some(Copy)` when the existing record is `"copy"` but the desired
/// mode is `Symlink` — this is the Windows fallback case (issue #153):
/// `symlink_dir()` failed on a prior run and we landed in copy mode, so
/// every subsequent startup would re-attempt symlink, fail again, and
/// trigger a full recursive copy. Treating the existing copy as
/// compatible lets the hash gate skip when the source hasn't changed.
///
/// The reverse direction (existing `"symlink"`, desired `Copy`) returns
/// `None` because the user actively changed the `sync_mode` setting and
/// the on-disk symlink doesn't reflect that intent.
fn skip_check_mode(
    existing_mode: &str,
    desired: sync_engine::SyncMode,
) -> Option<sync_engine::SyncMode> {
    match (existing_mode, desired) {
        ("symlink", sync_engine::SyncMode::Symlink) => Some(sync_engine::SyncMode::Symlink),
        ("copy", sync_engine::SyncMode::Copy) => Some(sync_engine::SyncMode::Copy),
        ("copy", sync_engine::SyncMode::Symlink) => Some(sync_engine::SyncMode::Copy),
        _ => None,
    }
}

/// Remove a recorded deployment, keeping (and reporting) anything that no
/// longer matches the record. Every row-driven removal in this module goes
/// through here so none of them can fall back to "delete whatever is there".
fn remove_recorded_or_warn(path: &Path, recorded_mode: &str) -> bool {
    match sync_engine::remove_recorded_target(path, recorded_mode) {
        Ok(removed) => {
            if !removed {
                log::warn!(
                    "Preserving {}: no longer matches its recorded {recorded_mode} deployment; \
                     removing the record only",
                    path.display()
                );
            }
            removed
        }
        Err(e) => {
            log::warn!("Failed to remove sync target {}: {e}", path.display());
            false
        }
    }
}

/// A key identifying the *directory entry* a target path names, used to spot
/// two rows that claim one object under different spellings.
///
/// The parent is canonicalized (resolving `..` and symlinked ancestors) and the
/// final component re-attached verbatim — deliberately NOT `canonicalize()` on
/// the whole path, which follows the final symlink and would collapse every
/// agent's link into the one library directory they all point at, making
/// distinct deployments look like the same object.
///
/// Known gap: on a case-insensitive filesystem two spellings of the final
/// component still key differently. That is the same lexical assumption the
/// rest of this module makes about `target_path`, and erring here only costs a
/// refusal, never a deletion.
fn ownership_key(path: &Path, memo: &mut HashMap<PathBuf, PathBuf>) -> PathBuf {
    let (Some(parent), Some(name)) = (path.parent(), path.file_name()) else {
        return path.to_path_buf();
    };
    // Rows share a handful of skills directories, so memoizing the parent keeps
    // this to a few syscalls no matter how large the library is.
    let canonical_parent = match memo.get(parent) {
        Some(cached) => cached.clone(),
        None => {
            let resolved = parent
                .canonicalize()
                .unwrap_or_else(|_| parent.to_path_buf());
            memo.insert(parent.to_path_buf(), resolved.clone());
            resolved
        }
    };
    canonical_parent.join(name)
}

/// Authorization for a deployment write: a `skill_targets` row claiming this
/// exact path lets us replace what it recorded, otherwise we may only write
/// where nothing of the user's would be destroyed (#363).
pub(crate) fn replace_policy(
    recorded_mode: Option<&str>,
    force: bool,
) -> sync_engine::ReplacePolicy<'_> {
    match recorded_mode {
        Some(mode) => sync_engine::ReplacePolicy::Recorded { mode },
        None if force => sync_engine::ReplacePolicy::UserConfirmed,
        None => sync_engine::ReplacePolicy::NoClobber,
    }
}

/// One target a sync refused to write because it is not ours to replace.
///
/// Kept structured all the way to the caller: an agent driving the CLI has to
/// tell the user *which* path is in the way and what to do about it, and a
/// pre-rendered English sentence cannot be branched on (#363).
#[derive(Debug, Clone, Serialize)]
pub struct TargetConflict {
    pub target: PathBuf,
    pub reason: String,
}

impl fmt::Display for TargetConflict {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&sync_engine::refusal_message(&self.target, &self.reason))
    }
}

/// Sync every desired target, returning the ownership refusals rather than
/// failing on them.
///
/// Refusals are *reported*, not thrown, because whether one should abort the
/// operation depends entirely on the caller: a user typing `skills sync` needs
/// an error, while app startup must not be prevented from launching by a
/// name collision in an agent directory. Returning the list lets each caller
/// state that policy; an early `Err` here made startup panic (#363).
pub fn sync_desired_targets(
    store: &SkillStore,
    desired_targets: &[ScenarioSyncTarget],
    force: bool,
) -> Result<Vec<TargetConflict>, AppError> {
    let batch_start = Instant::now();
    let existing_targets: HashMap<(String, String), SkillTargetRecord> = store
        .get_all_targets()
        .map_err(AppError::db)?
        .into_iter()
        .map(|target| ((target.skill_id.clone(), target.tool.clone()), target))
        .collect();

    let mut synced_count = 0usize;
    let mut skipped_count = 0usize;
    let mut failed_count = 0usize;
    let mut refusals: Vec<TargetConflict> = Vec::new();

    for desired in desired_targets {
        let target_start = Instant::now();
        let key = (desired.skill_id.clone(), desired.tool.clone());
        // A row claiming exactly this path is what lets us replace a copy-mode
        // directory; anything else must be left alone (#363).
        let recorded_mode = existing_targets
            .get(&key)
            .filter(|existing| std::path::Path::new(&existing.target_path) == desired.target)
            .map(|existing| existing.mode.clone());
        if let Some(existing) = existing_targets.get(&key) {
            let target_path = PathBuf::from(&existing.target_path);
            if target_path != desired.target {
                // Adapters can share a skills directory: amp and replit both
                // deploy to ~/.config/agents/skills, and kimi did too until it
                // moved to ~/.kimi-code/skills (#270). When one of them is
                // retargeted, the old path is not this tool's leftover — it is
                // still another tool's live deployment. Drop the stale record,
                // but leave the directory to whoever is still deployed there.
                let claimed_by_another_tool = desired_targets.iter().any(|other| {
                    other.tool != desired.tool
                        && other.skill_id == desired.skill_id
                        && other.target == target_path
                });
                if claimed_by_another_tool {
                    log::info!(
                        "Keeping {}: still the deployment target of another tool; \
                         dropping {}'s stale record only",
                        target_path.display(),
                        desired.tool
                    );
                } else {
                    match sync_engine::remove_recorded_target(&target_path, &existing.mode) {
                        Ok(true) => {}
                        Ok(false) => log::warn!(
                            "Keeping {}: no longer matches its recorded {} deployment; \
                             dropping the stale record only",
                            target_path.display(),
                            existing.mode
                        ),
                        Err(e) => log::warn!(
                            "Failed to remove stale target {}: {e}",
                            target_path.display()
                        ),
                    }
                }
                if let Err(e) = store.delete_target(&desired.skill_id, &desired.tool) {
                    log::warn!(
                        "Failed to delete stale target record for skill {}, tool {}: {e}",
                        desired.skill_id,
                        desired.tool
                    );
                }
            } else if existing.status == "ok" {
                if let Some(check_mode) = skip_check_mode(&existing.mode, desired.mode) {
                    if sync_engine::is_target_current(
                        &desired.source,
                        &desired.target,
                        check_mode,
                        existing.source_hash.as_deref(),
                        desired.source_hash.as_deref(),
                    ) {
                        // Surface the Windows fallback case in logs so operators
                        // can tell when a target is permanently on Copy because
                        // an earlier symlink_dir() failed (issue #153). Helpful
                        // when a user later enables Developer Mode and wonders
                        // why Symlink isn't being re-attempted.
                        if existing.mode == "copy"
                            && matches!(desired.mode, sync_engine::SyncMode::Symlink)
                        {
                            log::debug!(
                                "sync_desired_targets: skill {} ({}) staying on copy fallback for {} (content unchanged); trigger a manual resync to retry symlink",
                                desired.skill_id,
                                desired.skill_name,
                                desired.tool
                            );
                        }
                        skipped_count += 1;
                        continue;
                    }
                }
            }
        }

        match sync_engine::sync_skill(
            &desired.source,
            &desired.target,
            desired.mode,
            replace_policy(recorded_mode.as_deref(), force),
        ) {
            Ok(actual_mode) => {
                let now = chrono::Utc::now().timestamp_millis();
                let target_record = SkillTargetRecord {
                    id: uuid::Uuid::new_v4().to_string(),
                    skill_id: desired.skill_id.clone(),
                    tool: desired.tool.clone(),
                    target_path: desired.target.to_string_lossy().to_string(),
                    mode: actual_mode.as_str().to_string(),
                    status: "ok".to_string(),
                    synced_at: Some(now),
                    last_error: None,
                    // Record the hash that was just synced so the next
                    // run of this loop can short-circuit when the central
                    // skill content has not changed (issue #153).
                    source_hash: desired.source_hash.clone(),
                };
                if let Err(e) = store.insert_target(&target_record) {
                    log::warn!(
                        "Failed to insert sync target for skill {}: {e}",
                        desired.skill_id
                    );
                }
                synced_count += 1;
                let elapsed = target_start.elapsed().as_millis();
                if elapsed >= 200 {
                    log::warn!(
                        "sync_desired_targets: slow sync ({elapsed} ms, mode={}) for skill {} ({}) -> {}",
                        actual_mode.as_str(),
                        desired.skill_id,
                        desired.skill_name,
                        desired.target.display()
                    );
                }
            }
            Err(e) => {
                failed_count += 1;
                // An ownership refusal is not a transient failure to log and
                // move past: the user's content is intact but the skill they
                // asked for is not deployed, and saying "ok" to that is the
                // half of #363 that made the data loss invisible.
                if let Some(refused) = e.downcast_ref::<sync_engine::ReplaceRefused>() {
                    refusals.push(TargetConflict {
                        target: refused.target.clone(),
                        reason: refused.reason.to_string(),
                    });
                }
                log::warn!(
                    "Failed to sync skill {} ({}) to {} after {} ms: {e}",
                    desired.skill_id,
                    desired.skill_name,
                    desired.target.display(),
                    target_start.elapsed().as_millis()
                );
            }
        }
    }

    log::info!(
        "sync_desired_targets: {} targets in {} ms (synced={synced_count}, skipped={skipped_count}, failed={failed_count})",
        desired_targets.len(),
        batch_start.elapsed().as_millis()
    );

    // Everything that could be synced has been; hand back what was not.
    // Ordinary IO failures stay logged-and-tolerated, as before.
    Ok(refusals)
}

/// Preview the ownership decisions made by `sync_desired_targets` without changing targets.
pub fn preflight_scenario_sync_targets(
    store: &SkillStore,
    desired_targets: &[ScenarioSyncTarget],
    force: bool,
) -> Result<(), AppError> {
    let existing_targets = store.get_all_targets().map_err(AppError::db)?;
    let mut conflicts = Vec::new();
    for desired in desired_targets {
        let recorded_mode = existing_targets
            .iter()
            .find(|existing| {
                existing.skill_id == desired.skill_id
                    && existing.tool == desired.tool
                    && std::path::Path::new(&existing.target_path) == desired.target
            })
            .map(|existing| existing.mode.as_str());
        if let Err(error) = sync_engine::preflight_replace(
            &desired.source,
            &desired.target,
            desired.mode,
            replace_policy(recorded_mode, force),
        ) {
            if let Some(refused) = error.downcast_ref::<sync_engine::ReplaceRefused>() {
                conflicts.push(TargetConflictDetail {
                    path: refused.target.display().to_string(),
                    reason: refused.reason.to_string(),
                    is_skill: skill_metadata::is_valid_skill_dir(&refused.target),
                });
            } else {
                return Err(AppError::io(error));
            }
        }
    }
    if conflicts.is_empty() {
        Ok(())
    } else {
        Err(AppError::target_conflict(
            format!(
                "拒绝同步:{} 个目标路径已有内容且不由 AgentHub 管理,未做任何修改。",
                conflicts.len()
            ),
            conflicts,
        ))
    }
}

/// Turn reported refusals into the error a user-initiated command should show.
/// Deliberately says only that these targets were skipped — everything else in
/// the operation did apply, so claiming "nothing happened" would be false.
pub fn refusals_to_error(refusals: Vec<TargetConflict>) -> Result<(), AppError> {
    if refusals.is_empty() {
        return Ok(());
    }
    let summary = format!(
        "已跳过 {} 个技能——目标路径已有内容且不由 AgentHub 管理(这些路径未被删除,其余技能已正常部署)。{}",
        refusals.len(),
        refusals
            .iter()
            .map(|c| c.to_string())
            .collect::<Vec<_>>()
            .join(";")
    );
    Err(AppError::target_conflict(
        summary,
        refusals
            .into_iter()
            .map(|c| TargetConflictDetail {
                path: c.target.display().to_string(),
                reason: c.reason,
                is_skill: skill_metadata::is_valid_skill_dir(&c.target),
            })
            .collect(),
    ))
}

pub fn unsync_obsolete_scenario_targets(
    store: &SkillStore,
    old_scenario_id: &str,
    desired_targets: &[ScenarioSyncTarget],
) -> Result<(), AppError> {
    let desired_paths: HashMap<(String, String), PathBuf> = desired_targets
        .iter()
        .map(|target| {
            (
                (target.skill_id.clone(), target.tool.clone()),
                target.target.clone(),
            )
        })
        .collect();

    let old_skill_ids = store
        .get_skill_ids_for_scenario(old_scenario_id)
        .map_err(AppError::db)?;
    for skill_id in &old_skill_ids {
        let targets = store.get_targets_for_skill(skill_id).unwrap_or_default();
        for target in &targets {
            let path = PathBuf::from(&target.target_path);
            let key = (skill_id.clone(), target.tool.clone());
            if desired_paths.get(&key) == Some(&path) {
                continue;
            }

            remove_recorded_or_warn(&path, &target.mode);
            if let Err(e) = store.delete_target(skill_id, &target.tool) {
                log::warn!(
                    "Failed to delete target record for skill {skill_id}, tool {}: {e}",
                    target.tool
                );
            }
        }
    }

    Ok(())
}

pub fn unsync_scenario_skills(store: &SkillStore, scenario_id: &str) -> Result<(), AppError> {
    let skill_ids = store
        .get_skill_ids_for_scenario(scenario_id)
        .map_err(AppError::db)?;

    for skill_id in &skill_ids {
        let targets = store.get_targets_for_skill(skill_id).unwrap_or_default();
        for target in &targets {
            let path = PathBuf::from(&target.target_path);
            remove_recorded_or_warn(&path, &target.mode);
            if let Err(e) = store.delete_target(skill_id, &target.tool) {
                log::warn!(
                    "Failed to delete target record for skill {skill_id}, tool {}: {e}",
                    target.tool
                );
            }
        }
    }

    Ok(())
}

pub fn sync_scenario_skills(
    store: &SkillStore,
    scenario_id: &str,
    force: bool,
) -> Result<Vec<TargetConflict>, AppError> {
    let desired_targets = collect_scenario_sync_targets(store, scenario_id)?;
    sync_desired_targets(store, &desired_targets, force)
}

pub fn apply_scenario_to_default(
    store: &SkillStore,
    scenario_id: &str,
    force: bool,
) -> Result<Vec<TargetConflict>, AppError> {
    ensure_scenario_exists(store, scenario_id)?;
    let desired_targets = collect_scenario_sync_targets(store, scenario_id)?;

    if let Ok(Some(old_id)) = store.get_active_scenario_id() {
        if old_id != scenario_id {
            unsync_obsolete_scenario_targets(store, &old_id, &desired_targets)?;
        }
    }

    store
        .set_active_scenario(scenario_id)
        .map_err(AppError::db)?;
    sync_desired_targets(store, &desired_targets, force)
}

pub fn sync_skill_to_active_scenario(
    store: &SkillStore,
    scenario_id: &str,
    skill_id: &str,
) -> Result<(), AppError> {
    if let Ok(Some(active_id)) = store.get_active_scenario_id() {
        if active_id == scenario_id {
            let adapters =
                enabled_deployable_adapters_for_scenario_skill(store, scenario_id, skill_id)?;
            let preference = crate::core::deployment_preferences::Preference::load(
                store,
                crate::core::deployment_preferences::Scope::Global,
            )?;
            let Ok(Some(skill)) = store.get_skill_by_id(skill_id) else {
                return Ok(());
            };
            let source = PathBuf::from(&skill.central_path);
            let target_name = sync_engine::target_dir_name(&source, &skill.name);
            let old_targets = store.get_targets_for_skill(skill_id).unwrap_or_default();
            for adapter in &adapters {
                let target = deployment_target(adapter, &target_name, skill_id, &old_targets);
                let mut recorded_mode: Option<String> = None;
                if let Some(old) = old_targets.iter().find(|t| t.tool == adapter.key) {
                    let old_path = PathBuf::from(&old.target_path);
                    if old_path != target {
                        match sync_engine::remove_recorded_target(&old_path, &old.mode) {
                            Ok(true) => {}
                            Ok(false) => log::warn!(
                                "Keeping {}: no longer matches its recorded {} deployment; \
                                 dropping the stale record only",
                                old_path.display(),
                                old.mode
                            ),
                            Err(e) => log::warn!(
                                "Failed to remove stale target {}: {e}",
                                old_path.display()
                            ),
                        }
                        let _ = store.delete_target(skill_id, &adapter.key);
                    } else {
                        recorded_mode = Some(old.mode.clone());
                    }
                }

                let mode = preference.for_target(recorded_mode.as_deref());
                match sync_engine::sync_skill(
                    &source,
                    &target,
                    mode,
                    replace_policy(recorded_mode.as_deref(), false),
                ) {
                    Ok(actual_mode) => {
                        let now = chrono::Utc::now().timestamp_millis();
                        let target_record = super::skill_store::SkillTargetRecord {
                            id: uuid::Uuid::new_v4().to_string(),
                            skill_id: skill_id.to_string(),
                            tool: adapter.key.clone(),
                            target_path: target.to_string_lossy().to_string(),
                            mode: actual_mode.as_str().to_string(),
                            status: "ok".to_string(),
                            synced_at: Some(now),
                            last_error: None,
                            source_hash: skill.content_hash.clone(),
                        };
                        if let Err(e) = store.insert_target(&target_record) {
                            log::warn!("Failed to insert sync target for skill {skill_id}: {e}");
                        }
                    }
                    Err(e) => {
                        log::warn!(
                            "Failed to sync skill {skill_id} to {}: {e}",
                            target.display()
                        );
                    }
                }
            }
        }
    }
    Ok(())
}

pub fn ensure_default_startup_scenario(store: &SkillStore) -> Result<(), AppError> {
    let mut scenarios = store.get_all_scenarios().map_err(AppError::db)?;
    if scenarios.is_empty() {
        let now = chrono::Utc::now().timestamp_millis();
        let default_scenario = ScenarioRecord {
            id: uuid::Uuid::new_v4().to_string(),
            name: "Default".to_string(),
            description: Some("Default startup scenario".to_string()),
            icon: None,
            sort_order: 0,
            created_at: now,
            updated_at: now,
        };
        store
            .insert_scenario(&default_scenario)
            .map_err(AppError::db)?;
        scenarios.push(default_scenario);
    }

    // Startup restores whatever skill group was last active; there is no separate
    // "default startup skill group" setting to override it.
    let current_active = store.get_active_scenario_id().map_err(AppError::db)?;

    let desired_active = current_active
        .clone()
        .filter(|id| scenarios.iter().any(|scenario| scenario.id == *id))
        .unwrap_or_else(|| scenarios[0].id.clone());

    if current_active.as_deref() != Some(desired_active.as_str()) {
        if let Some(old_active) = current_active.as_deref() {
            unsync_scenario_skills(store, old_active)?;
        }
        store
            .set_active_scenario(&desired_active)
            .map_err(AppError::db)?;
    }

    // Startup policy: a collision must never stop the app from launching. The
    // colliding skill simply is not deployed, its content is untouched, and the
    // workspace view shows it as not synced.
    let refusals = sync_scenario_skills(store, &desired_active, false)?;
    for refusal in &refusals {
        log::warn!("startup sync skipped a target: {refusal}");
    }
    Ok(())
}

pub fn ensure_cli_scenario_state(store: &SkillStore) -> Result<(), AppError> {
    let mut scenarios = store.get_all_scenarios().map_err(AppError::db)?;
    if scenarios.is_empty() {
        let now = chrono::Utc::now().timestamp_millis();
        let default_scenario = ScenarioRecord {
            id: uuid::Uuid::new_v4().to_string(),
            name: "Default".to_string(),
            description: Some("Default startup scenario".to_string()),
            icon: None,
            sort_order: 0,
            created_at: now,
            updated_at: now,
        };
        store
            .insert_scenario(&default_scenario)
            .map_err(AppError::db)?;
        scenarios.push(default_scenario);
    }

    let current_active = store.get_active_scenario_id().map_err(AppError::db)?;
    if current_active
        .as_deref()
        .is_some_and(|id| scenarios.iter().any(|scenario| scenario.id == id))
    {
        return Ok(());
    }

    store
        .set_active_scenario(&scenarios[0].id)
        .map_err(AppError::db)
}

pub fn restore_all_skills_sync_included(store: &SkillStore) -> Result<bool, AppError> {
    let mut changed = false;
    for skill in store.get_all_skills().map_err(AppError::db)? {
        if !skill.enabled {
            store
                .update_skill_enabled(&skill.id, true)
                .map_err(AppError::db)?;
            changed = true;
        }
    }
    Ok(changed)
}

pub fn sync_active_scenario_to_tool(store: &SkillStore, tool_key: &str) {
    if let Ok(Some(active_id)) = store.get_active_scenario_id() {
        let Ok(skill_ids) = store.get_skill_ids_for_scenario(&active_id) else {
            return;
        };
        for skill_id in skill_ids {
            if let Ok(adapters) =
                enabled_deployable_adapters_for_scenario_skill(store, &active_id, &skill_id)
            {
                if adapters.iter().any(|adapter| adapter.key == tool_key) {
                    let _ = sync_skill_to_active_scenario(store, &active_id, &skill_id);
                }
            }
        }
    }
}

#[derive(Debug, Clone, Copy)]
pub enum BatchApplyMode {
    Add,
    Remove,
}

/// Apply a batch of `(skill_id × tool_key)` pairs in either Add or Remove mode
/// without touching `active_scenario_id` or `scenario_skill_tools` toggles.
///
/// This is the tray-side skill group apply primitive. Unlike [`sync_single_skill_to_tool`]
/// (which is wrapped by the `sync_skill_to_tool` Tauri command and carries the
/// implicit active-skill-group toggle side-effect), this batch is a pure
/// "write/remove files + maintain `skill_targets` rows" operation.
///
/// Remove mode handles shared physical paths: a `target_path` may be referenced
/// by multiple `(skill_id, tool)` records when several tools resolve to the same
/// skills directory. The filesystem path is only removed when no remaining
/// `skill_targets` row references it after the batch deletions, so removing one
/// skill group's tools never wipes another tool's still-active files.
pub fn apply_skills_to_tools(
    store: &SkillStore,
    skill_ids: &[String],
    tool_keys: &[String],
    mode: BatchApplyMode,
    force: bool,
) -> Result<(), AppError> {
    if skill_ids.is_empty() || tool_keys.is_empty() {
        return Ok(());
    }

    match mode {
        BatchApplyMode::Add => apply_add(store, skill_ids, tool_keys, false, force),
        BatchApplyMode::Remove => apply_remove(store, skill_ids, tool_keys),
    }
}

/// Check the same targets and ownership rules as batch deployment without writing.
pub fn preflight_add_skills_to_tools(
    store: &SkillStore,
    skill_ids: &[String],
    tool_keys: &[String],
) -> Result<(), AppError> {
    if skill_ids.is_empty() || tool_keys.is_empty() {
        return Ok(());
    }
    apply_add(store, skill_ids, tool_keys, true, false)
}

fn apply_add(
    store: &SkillStore,
    skill_ids: &[String],
    tool_keys: &[String],
    preflight_only: bool,
    force: bool,
) -> Result<(), AppError> {
    let preference = crate::core::deployment_preferences::Preference::load(
        store,
        crate::core::deployment_preferences::Scope::Global,
    )?;
    let disabled = tool_service::get_disabled_tools(store);

    let mut adapters: HashMap<String, tool_adapters::ToolAdapter> = HashMap::new();
    for key in tool_keys {
        if disabled.contains(key) {
            log::debug!("apply_skills_to_tools: skipping disabled tool {key}");
            continue;
        }
        let Some(adapter) = tool_adapters::find_adapter_with_store(store, key) else {
            log::warn!("apply_skills_to_tools: unknown tool {key}");
            continue;
        };
        if !adapter.can_deploy() {
            log::debug!(
                "apply_skills_to_tools: skipping uninstalled tool {} ({key})",
                adapter.display_name
            );
            continue;
        }
        adapters.insert(key.clone(), adapter);
    }

    // Plan every pair up front, then refuse the whole batch if any one of them
    // would destroy something (#363, expectation 4). Not a rollback — a
    // finished copy cannot be undone — but nothing is written until every pair
    // has been judged.
    struct PlannedPair {
        skill: crate::core::skill_store::SkillRecord,
        tool_key: String,
        source: PathBuf,
        target: PathBuf,
        mode: sync_engine::SyncMode,
    }

    let existing_targets = store.get_all_targets().map_err(AppError::db)?;
    let mut plan: Vec<PlannedPair> = Vec::new();
    for skill_id in skill_ids {
        let Ok(Some(skill)) = store.get_skill_by_id(skill_id) else {
            log::warn!("apply_skills_to_tools: skill {skill_id} not found");
            continue;
        };
        let source = PathBuf::from(&skill.central_path);
        let target_name = sync_engine::target_dir_name(&source, &skill.name);
        for (tool_key, adapter) in &adapters {
            plan.push(PlannedPair {
                skill: skill.clone(),
                tool_key: tool_key.clone(),
                mode: preference.for_target(
                    existing_targets
                        .iter()
                        .find(|existing| {
                            existing.skill_id == *skill_id
                                && existing.tool == *tool_key
                                && Path::new(&existing.target_path)
                                    == deployment_target(
                                        adapter,
                                        &target_name,
                                        skill_id,
                                        &existing_targets,
                                    )
                        })
                        .map(|existing| existing.mode.as_str()),
                ),
                source: source.clone(),
                target: deployment_target(adapter, &target_name, skill_id, &existing_targets),
            });
        }
    }

    // Two skills whose central directories share a basename resolve to the
    // same deployment path (`target_dir_name` uses the basename only), so the
    // second would silently overwrite the first. Neither is the user's data,
    // but the result is a target whose contents don't match its record.
    // Two library skills planning onto one path is a naming problem, not a
    // user's directory being in the way — kept apart so the refusal that does
    // mean the latter is the only thing tagged as a target conflict.
    let mut duplicate_targets: Vec<String> = Vec::new();
    let mut conflicts: Vec<TargetConflictDetail> = Vec::new();
    let mut probe_errors: Vec<String> = Vec::new();
    // Keyed on skill id, not name: names are not unique, and two distinct
    // skills that happen to share one would otherwise slip through as "the
    // same skill" and silently overwrite each other.
    let mut planned_paths: HashMap<&Path, (&str, &str)> = HashMap::new();
    for pair in &plan {
        let entry = (pair.skill.id.as_str(), pair.skill.name.as_str());
        if let Some((first_id, first_name)) = planned_paths.insert(pair.target.as_path(), entry) {
            if first_id != pair.skill.id {
                duplicate_targets.push(format!(
                    "{} — skills \"{}\" and \"{}\" both deploy here",
                    pair.target.display(),
                    first_name,
                    pair.skill.name
                ));
            }
        }
    }
    if !duplicate_targets.is_empty() {
        return Err(AppError::invalid_input(format!(
            "拒绝部署:{} 个目标路径被多个技能同时占用,未做任何修改。{}",
            duplicate_targets.len(),
            duplicate_targets.join(";")
        )));
    }

    // Ownership belongs to the path, not to the (skill, tool) pair. When two
    // agents share a skills directory, a row for either one vouches for the
    // object there, so evidence is pooled per path before judging — otherwise
    // the pair without its own row would refuse a target we demonstrably own.
    // Pool the distinct recorded modes per path, then keep the evidence only
    // when they agree. Contradictory rows must refuse, exactly as in the
    // removal path — taking whichever one came first would let a stale `copy`
    // row authorize deleting a real directory, and HashMap order is not even
    // deterministic about which one that is.
    // Pooled from every existing row that lands on a planned path, not just
    // from the pairs in this batch: `skill_targets` is unique on
    // `(skill_id, tool)`, not on `target_path`, so a row we did not select can
    // still be a claim on the same object — and a contradictory one.
    // Keyed by directory entry rather than by path string, so a row spelled
    // differently (symlinked ancestor, `..`) but naming the same object still
    // counts as evidence about it.
    let mut key_memo: HashMap<PathBuf, PathBuf> = HashMap::new();
    let planned_keys: HashSet<PathBuf> = plan
        .iter()
        .map(|pair| ownership_key(&pair.target, &mut key_memo))
        .collect();
    let mut modes_by_key: HashMap<PathBuf, HashSet<&str>> = HashMap::new();
    for row in &existing_targets {
        let key = ownership_key(Path::new(row.target_path.as_str()), &mut key_memo);
        if planned_keys.contains(&key) {
            modes_by_key
                .entry(key)
                .or_default()
                .insert(row.mode.as_str());
        }
    }
    let evidence_by_key: HashMap<&PathBuf, &str> = modes_by_key
        .iter()
        .filter_map(|(key, modes)| {
            let mut it = modes.iter();
            match (it.next(), it.next()) {
                (Some(only), None) => Some((key, *only)),
                _ => None,
            }
        })
        .collect();
    let evidence_for = |target: &Path, memo: &mut HashMap<PathBuf, PathBuf>| -> Option<&str> {
        let key = ownership_key(target, memo);
        evidence_by_key.get(&key).copied()
    };
    let mut preflighted: HashSet<&Path> = HashSet::new();
    for pair in &plan {
        if !preflighted.insert(pair.target.as_path()) {
            continue;
        }
        if let Err(e) = sync_engine::preflight_replace(
            &pair.source,
            &pair.target,
            pair.mode,
            replace_policy(evidence_for(&pair.target, &mut key_memo), force),
        ) {
            // Keep the refusal's own path and reason: the caller may be an
            // agent that has to name the directory in the way and offer the
            // way out, which a flattened sentence cannot support.
            match e.downcast_ref::<sync_engine::ReplaceRefused>() {
                Some(refused) => conflicts.push(TargetConflictDetail {
                    path: refused.target.display().to_string(),
                    reason: refused.reason.to_string(),
                    is_skill: skill_metadata::is_valid_skill_dir(&refused.target),
                }),
                // Failing to even inspect the target (permissions, a broken
                // mount) is an IO problem. Reporting it as a conflict would
                // tell the caller to adopt or move content that may not exist.
                None => probe_errors.push(format!("{}: {e}", pair.target.display())),
            }
        }
    }
    if !probe_errors.is_empty() {
        return Err(AppError::io(format!(
            "拒绝部署:{} 个目标路径无法检查,未做任何修改。{}",
            probe_errors.len(),
            probe_errors.join(";")
        )));
    }
    if !conflicts.is_empty() {
        let summary = format!(
            "拒绝部署:{}/{} 个目标路径已有内容且不由 AgentHub 管理,未做任何修改。{}",
            conflicts.len(),
            plan.len(),
            conflicts
                .iter()
                .map(|c| sync_engine::refusal_message(Path::new(&c.path), &c.reason))
                .collect::<Vec<_>>()
                .join(";")
        );
        return Err(AppError::target_conflict(summary, conflicts));
    }
    if preflight_only {
        return Ok(());
    }

    let mut synced = 0usize;
    let mut failed = 0usize;
    // Several tools can resolve to one skills directory, so two pairs of this
    // batch may write the same path. The second one has no row of its own yet,
    // and without this it would refuse the directory the first one just created
    // (only visible in copy mode — a symlink already points at the source).
    let mut written_in_batch: HashMap<&Path, String> = HashMap::new();
    for pair in &plan {
        let PlannedPair {
            skill,
            tool_key,
            source,
            target,
            mode,
        } = pair;
        let skill_id = &skill.id;
        // What this batch just wrote outranks the row: the row describes the
        // previous deployment, the batch describes what is on disk right now.
        // Preferring the row would make the second pair on a shared path refuse
        // the directory the first pair created after a mode change.
        // Same precedence the preflight used, and deliberately NOT falling back
        // to this pair's own `recorded_mode`: that would reinstate a row the
        // conflict rule above just rejected as ambiguous.
        let effective_mode = written_in_batch
            .get(target.as_path())
            .map(String::as_str)
            .or_else(|| evidence_for(target, &mut key_memo));
        match sync_engine::sync_skill(source, target, *mode, replace_policy(effective_mode, force))
        {
            Ok(actual_mode) => {
                written_in_batch.insert(target.as_path(), actual_mode.as_str().to_string());
                let now = chrono::Utc::now().timestamp_millis();
                let target_record = SkillTargetRecord {
                    id: uuid::Uuid::new_v4().to_string(),
                    skill_id: skill_id.clone(),
                    tool: tool_key.clone(),
                    target_path: target.to_string_lossy().to_string(),
                    mode: actual_mode.as_str().to_string(),
                    status: "ok".to_string(),
                    synced_at: Some(now),
                    last_error: None,
                    source_hash: skill.content_hash.clone(),
                };
                if let Err(e) = store.insert_target(&target_record) {
                    log::warn!(
                        "apply_skills_to_tools: failed to insert target for skill {skill_id} / {tool_key}: {e}"
                    );
                    failed += 1;
                } else {
                    synced += 1;
                }
            }
            Err(e) => {
                failed += 1;
                log::warn!(
                    "apply_skills_to_tools: failed to sync skill {skill_id} ({}) to {}: {e}",
                    skill.name,
                    target.display()
                );
            }
        }
    }

    log::info!(
        "apply_skills_to_tools(Add): skills={} tools={} synced={synced} failed={failed}",
        skill_ids.len(),
        adapters.len(),
    );
    Ok(())
}

fn apply_remove(
    store: &SkillStore,
    skill_ids: &[String],
    tool_keys: &[String],
) -> Result<(), AppError> {
    let tool_set: HashSet<&String> = tool_keys.iter().collect();

    // Keep each row's recorded mode: it is the only evidence of what we put at
    // that path, and it has to survive until after the filesystem is inspected
    // (#363, expectation 5).
    let mut to_delete: Vec<(String, String, PathBuf, String)> = Vec::new();
    for skill_id in skill_ids {
        let targets = store.get_targets_for_skill(skill_id).unwrap_or_default();
        for target in targets {
            if tool_set.contains(&target.tool) {
                to_delete.push((
                    skill_id.clone(),
                    target.tool.clone(),
                    PathBuf::from(&target.target_path),
                    target.mode.clone(),
                ));
            }
        }
    }

    if to_delete.is_empty() {
        return Ok(());
    }

    // Rows go first, exactly as before: the recorded modes this batch needs are
    // already captured above, so deleting now costs no evidence, and re-reading
    // afterwards keeps the survivor set honest if any delete failed. Reading
    // must not fail open — treating a DB error as "nothing survives" would
    // authorize removing a path another tool is still using.
    for (skill_id, tool, _, _) in &to_delete {
        if let Err(e) = store.delete_target(skill_id, tool) {
            log::warn!(
                "apply_skills_to_tools(Remove): failed to delete target record for skill {skill_id} / {tool}: {e}"
            );
        }
    }

    // Must not fail open: treating a read error as "nothing survives" would
    // authorize deleting a path another tool still uses. It also must not fail
    // with an error, because the rows above are already gone — returning Err
    // here would leave callers thinking nothing happened. So on a read error,
    // keep every path and stop.
    let still_referenced: HashSet<PathBuf> = match store.get_all_targets() {
        Ok(rows) => rows
            .into_iter()
            .map(|t| PathBuf::from(&t.target_path))
            .collect(),
        Err(e) => {
            log::warn!(
                "apply_skills_to_tools(Remove): cannot verify remaining references ({e}); \
                 leaving every affected path on disk"
            );
            return Ok(());
        }
    };

    // One path may be claimed by several doomed rows. Their modes must agree
    // before anything is deleted: disagreement means we do not actually know
    // what we put there, and for a fix whose whole purpose is preservation,
    // ambiguous evidence has to preserve. (Taking whichever mode happens to
    // match would let a stale `copy` row authorize deleting a user directory
    // that replaced our symlink.)
    let mut candidates: Vec<(&PathBuf, Vec<&String>)> = Vec::new();
    let mut seen: HashMap<&PathBuf, usize> = HashMap::new();
    for (_, _, path, mode) in &to_delete {
        match seen.get(path) {
            Some(index) => candidates[*index].1.push(mode),
            None => {
                seen.insert(path, candidates.len());
                candidates.push((path, vec![mode]));
            }
        }
    }

    let mut removed = 0usize;
    let mut preserved = 0usize;
    for (path, recorded_modes) in candidates {
        if still_referenced.contains(path) {
            log::debug!(
                "apply_skills_to_tools(Remove): keeping {} (still referenced by another target)",
                path.display()
            );
            continue;
        }
        let mut modes: Vec<&str> = recorded_modes.iter().map(|m| m.as_str()).collect();
        modes.sort_unstable();
        modes.dedup();
        let outcome = match modes.as_slice() {
            [single] => sync_engine::remove_recorded_target(path, single),
            // Contradictory records: keep the object, drop the rows.
            _ => {
                log::warn!(
                    "apply_skills_to_tools(Remove): {} has conflicting records ({}); \
                     preserving it and removing the records only",
                    path.display(),
                    modes.join("/")
                );
                Ok(false)
            }
        };
        match outcome {
            Ok(true) => removed += 1,
            // Someone replaced our deployment with content of their own. The
            // record goes; the content stays.
            Ok(false) => {
                preserved += 1;
                log::warn!(
                    "apply_skills_to_tools(Remove): preserving {} — no longer matches its \
                     recorded deployment ({}); removing the record only",
                    path.display(),
                    recorded_modes
                        .iter()
                        .map(|m| m.as_str())
                        .collect::<Vec<_>>()
                        .join("/")
                );
            }
            Err(e) => {
                log::warn!(
                    "apply_skills_to_tools(Remove): failed to remove {}: {e}",
                    path.display()
                );
            }
        }
    }

    log::info!(
        "apply_skills_to_tools(Remove): pairs={} fs_removed={removed} preserved={preserved}",
        to_delete.len(),
    );
    Ok(())
}

#[cfg(test)]
mod sync_desired_targets_tests;

#[cfg(test)]
mod skip_check_mode_tests;