tuffcli 0.10.2

Capability lifecycle manager for coding agents.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
use std::collections::BTreeMap;
use std::fs;
use std::io::IsTerminal;
use std::path::Path;

use crate::adapter::{
    self, AdapterKind, AgentAdapter, CapabilityKind, HookDefinition, HookRenderContext,
    NativeHookConfig, resolve_capability,
};
use crate::error::{Result, TuffError};
use crate::git;
use crate::lockfile::{self, TargetLockEntry};
use crate::manifest::{self, CapabilityType, load_manifest};
use crate::release;
use crate::resolver::{self, Scope};

use super::{capability_index, home_dir, infer_from_path, resolve_agent_selection};

pub fn cmd_add(
    repo_root: &Path,
    source: Option<&Path>,
    name: Option<&str>,
    capability_type: Option<&str>,
    target_ids: &[String],
    global: bool,
    hook_file: Option<&Path>,
) -> Result<()> {
    let source = source.ok_or_else(|| TuffError::usage("source path or URL is required"))?;
    let (scope, install_root) = if global {
        let home = home_dir()?;
        let lock_path = crate::paths::global_lockfile(&home);
        lockfile::init_lockfile_at(&lock_path)?;
        (Scope::Global, home)
    } else {
        (Scope::Project, repo_root.to_path_buf())
    };
    let target_ids = resolve_agent_selection(&install_root, target_ids, global)?;

    if git::is_git_url(&source.to_string_lossy()) {
        return cmd_add_git(
            &install_root,
            scope,
            &source.to_string_lossy(),
            &target_ids,
            name,
            capability_type,
            repo_root,
            hook_file,
        );
    }
    if let Some(name) = name
        && name.contains('@')
    {
        return Err(TuffError::usage(format!(
            "'{name}' carries a version requirement, which applies to git sources only"
        ))
        .with_hint("a local directory has no release tags; pass the name without '@'"));
    }
    cmd_add_local(
        &install_root,
        scope,
        source,
        &target_ids,
        repo_root,
        capability_type,
        name,
        hook_file,
    )
}

/// `tuff add mcp <source>...` — each source is a built-in catalog id, a
/// local directory holding a `tuff.toml`, or a git URL. Paths and URLs go
/// through the normal typed-add route; catalog ids are synthesized in
/// memory and installed through the same `install_capability` so every
/// lifecycle verb sees an ordinary capability.
pub fn cmd_add_mcp(
    repo_root: &Path,
    sources: &[String],
    target_ids: &[String],
    global: bool,
    yes: bool,
    registry_url: &str,
) -> Result<()> {
    if sources.is_empty() {
        return Err(TuffError::usage(
            "at least one catalog id, path, or git URL is required",
        ));
    }

    for source in sources {
        let as_path = Path::new(source);
        if git::is_git_url(source) || as_path.exists() {
            cmd_add(
                repo_root,
                Some(as_path),
                None,
                Some("mcp-server"),
                target_ids,
                global,
                None,
            )?;
            continue;
        }

        if let Some(mut manifest) = crate::catalog::lookup(source)? {
            prompt_env_overrides(&mut manifest, yes);
            add_catalog_server(repo_root, &manifest, source, None, target_ids, global)?;
            continue;
        }

        // Not a path, a git URL, or a built-in id: ask the registry. A name
        // is matched exactly, so a search hit never installs by surprise.
        let registry = registry_url;
        let Some(server) = super::block_on_oci(crate::registry::fetch(registry, source))? else {
            return Err(TuffError::not_found(format!(
                "'{source}' is not a path, a git URL, a built-in catalog id, or a server in the MCP registry"
            ))
            .with_hint(format!(
                "run 'tuff mcp search {source}' to find its full registry name, or 'tuff add mcp --help' for the built-in ids"
            )));
        };
        let id = crate::registry::default_capability_id(&server.name);
        let mut manifest = crate::registry::to_manifest(&server, &id)?;
        prompt_env_overrides(&mut manifest, yes);
        add_catalog_server(
            repo_root,
            &manifest,
            &server.name,
            Some(registry),
            target_ids,
            global,
        )?;
        // Left out of the manifest because the server does not require
        // them; said out loud so the omission is a choice the user can see
        // and reverse, not a silent one.
        let skipped = crate::registry::skipped_optional_headers(&server);
        if !skipped.is_empty() {
            eprintln!(
                "note: '{}' also documents the optional {} {}; add {} to [server.headers] by hand if you need {}",
                id,
                if skipped.len() == 1 {
                    "header"
                } else {
                    "headers"
                },
                skipped.join(", "),
                if skipped.len() == 1 { "it" } else { "them" },
                if skipped.len() == 1 { "it" } else { "them" },
            );
        }
    }
    Ok(())
}

/// Ask, per variable a server declaration reads, whether to use a different
/// name than the catalog's default — never the secret's value, only which
/// variable holds it, matching the "secrets are references, never values"
/// rule. Header references (RFC-106 D1) join this one flow rather than
/// introducing a second. Only meaningful for catalog installs (a local/git
/// manifest is already fully under the user's own control). Skipped —
/// silently keeping the catalog defaults — with `--yes` or when stdin isn't
/// a real terminal, so this never hangs a script or CI run.
fn prompt_env_overrides(manifest: &mut manifest::CapabilityManifest, yes: bool) {
    if yes || !std::io::stdin().is_terminal() {
        return;
    }
    let Some(server) = manifest.server.as_mut() else {
        return;
    };
    for default in referenced_variables(server) {
        eprint!(
            "{}: reads {default} from your environment. Press enter to keep it, or type a different variable name: ",
            manifest.id
        );
        let _ = std::io::Write::flush(&mut std::io::stderr());
        let mut line = String::new();
        if std::io::stdin().read_line(&mut line).is_err() {
            return;
        }
        if let Some(new_name) = resolve_prompt_answer(&default, &line) {
            rename_env_var(server, &default, &new_name);
        }
    }
}

/// `None` means keep the default (blank input, or input matching the
/// default verbatim); `Some(name)` means use this variable name instead.
fn resolve_prompt_answer(default: &str, line: &str) -> Option<String> {
    let trimmed = line.trim();
    if trimmed.is_empty() || trimmed == default {
        None
    } else {
        Some(trimmed.to_string())
    }
}

/// Every variable the server reads, `[server.env]` first and then
/// `[server.headers]`, each name asked about once however many places
/// reference it.
fn referenced_variables(server: &manifest::McpServerConfig) -> Vec<String> {
    let mut names: Vec<String> = Vec::new();
    let referenced = server
        .env
        .values()
        .map(|reference| reference.from_env.clone())
        .chain(
            server
                .headers
                .values()
                .map(|reference| reference.from_env.clone()),
        );
    for name in referenced {
        if !names.contains(&name) {
            names.push(name);
        }
    }
    names
}

/// In `[server.env]` the map key and `from_env` value are always identical
/// today (an entry only ever declares a variable by name, with no separate
/// purpose label), so renaming replaces both. A header is keyed by the
/// header name instead, so only its reference moves, and its `format` is
/// carried across untouched.
fn rename_env_var(server: &mut manifest::McpServerConfig, old_name: &str, new_name: &str) {
    if server.env.remove(old_name).is_some() {
        server.env.insert(
            new_name.to_string(),
            manifest::EnvRef {
                from_env: new_name.to_string(),
            },
        );
    }
    for reference in server.headers.values_mut() {
        if reference.from_env == old_name {
            reference.from_env = new_name.to_string();
        }
    }
}

/// Install one MCP server resolved from a catalog: the one compiled into
/// the binary when `registry` is `None`, otherwise the named MCP registry.
fn add_catalog_server(
    repo_root: &Path,
    manifest: &manifest::CapabilityManifest,
    catalog_id: &str,
    registry: Option<&str>,
    target_ids: &[String],
    global: bool,
) -> Result<()> {
    let (scope, install_root) = if global {
        let home = home_dir()?;
        let lock_path = crate::paths::global_lockfile(&home);
        lockfile::init_lockfile_at(&lock_path)?;
        (Scope::Global, home)
    } else {
        (Scope::Project, repo_root.to_path_buf())
    };
    let target_ids = resolve_agent_selection(&install_root, target_ids, global)?;
    let capability = resolve_capability(manifest)?;

    if scope == Scope::Project
        && let Some(warning) = resolver::check_collision(
            &capability.id,
            repo_root,
            Some(resolver::CATALOG_SOURCE_IDENTITY),
        )?
    {
        eprintln!("{warning}");
    }

    install_capability(
        &install_root,
        scope,
        &capability,
        manifest,
        &target_ids,
        Some(lockfile::CapabilitySource::Catalog(
            lockfile::CatalogSource {
                id: catalog_id.to_string(),
                version: manifest.version.clone(),
                registry: registry.map(str::to_string),
            },
        )),
        true,
    )?;
    match registry {
        Some(registry) => println!(
            "installed {} from {registry} ({} {})",
            capability.id, catalog_id, manifest.version
        ),
        None => println!(
            "installed {} from the built-in catalog (catalog {})",
            capability.id, manifest.version
        ),
    }
    Ok(())
}

/// Whether the lockfile already records `id` for `target` — the one case in
/// which overwriting an existing `mcpServers.<id>` entry is a re-install of
/// our own work rather than clobbering something a person wrote by hand.
pub(crate) fn mcp_entry_tracked(lockfile: &lockfile::Lockfile, id: &str, target: &str) -> bool {
    lockfile
        .capabilities
        .get(id)
        .is_some_and(|entry| entry.targets.contains_key(target))
}

#[expect(
    clippy::too_many_arguments,
    reason = "CLI dispatch passes source and install context"
)]
fn cmd_add_git(
    install_root: &Path,
    scope: Scope,
    url: &str,
    target_ids: &[String],
    name: Option<&str>,
    capability_type: Option<&str>,
    project_root: &Path,
    hook_file: Option<&Path>,
) -> Result<()> {
    // `<name>@<requirement>` asks for a release (RFC-101). The tags are
    // listed before anything is cloned, so a request nothing satisfies
    // costs one round trip and names what was available.
    let (name, request) = match name {
        Some(spec) => {
            let (name, request) = release::split_version_request(spec)?;
            (
                Some(name),
                request.map(release::VersionRequest::parse).transpose()?,
            )
        }
        None => (None, None),
    };
    let source_path = git::source_subdirectory(url);
    let release_name = name.or_else(|| {
        source_path
            .as_deref()
            .and_then(|path| path.rsplit('/').next())
    });
    let release = match &request {
        Some(request) => {
            let release_name = release_name.ok_or_else(|| {
                TuffError::usage(
                    "a version requirement needs a capability name to match release tags against",
                )
                .with_hint(
                    "write <name>@<version>, or use a URL that names the capability's directory",
                )
            })?;
            Some(super::resolve_git_release(url, release_name, request)?)
        }
        None => None,
    };
    let (source_guard, cache_dir, clean_url) = match &release {
        Some(release) => git::clone_tag_to_temp(url, &release.tag)?,
        None => git::clone_to_temp(url, None)?,
    };
    let commit_sha = git::resolve_ref(&cache_dir)?;
    if let (Some(release), Some(request), Some(release_name)) = (&release, &request, release_name) {
        println!(
            "resolved {release_name}@{request} to {} ({})",
            release.tag,
            super::short_sha(&commit_sha)
        );
    }
    let cap_type = capability_type
        .and_then(CapabilityType::parse)
        .unwrap_or(CapabilityType::Skill);
    let skill_dir = if let Some(path) = source_path.as_deref() {
        crate::tool::check_path_traversal(path)?;
        let path = cache_dir.join(path);
        if !path.is_dir() {
            return Err(TuffError::not_found(format!(
                "capability directory not found in repository: {}",
                path.display()
            )));
        }
        path
    } else if cap_type == CapabilityType::McpServer {
        // No SKILL.md-style discovery exists for servers; the URL must name
        // the directory holding the tuff.toml.
        return Err(TuffError::usage(
            "installing an mcp-server from git requires a subdirectory in the URL (e.g. <repo>//mcp-servers/github)",
        ));
    } else {
        let name = name.ok_or_else(|| {
            TuffError::usage(
                "--name is required when installing from a git URL without a subdirectory",
            )
        })?;
        git::discover_capability(&cache_dir, name, cap_type)?
    };

    // The lockfile pins the commit either way. The entry's version is the
    // release when a tag chose it, else what the source declares for itself
    // (RFC-101 tier 2), else the commit SHA, and the scheme says which.
    let installed_version = git_installed_version(&skill_dir, release.as_ref(), &commit_sha);

    let native_hook = cap_type == CapabilityType::Hook && hook_file.is_some();
    let manifest = if native_hook {
        synthetic_local_manifest(&skill_dir, Some(cap_type))?
    } else {
        git_manifest(&skill_dir, name, &installed_version)?
    };
    let name: &str = name.unwrap_or(&manifest.id);
    let source_skill = source_path.as_deref().unwrap_or(name);

    let capability = if native_hook {
        resolve_native_hook_capability(&skill_dir, Some(name), &installed_version, hook_file)?
    } else {
        resolve_capability(&manifest)?
    };

    if scope == Scope::Project
        && let Some(warning) = resolver::check_collision(name, project_root, Some(&clean_url))?
    {
        eprintln!("{warning}");
    }

    let result = install_capability(
        install_root,
        scope,
        &capability,
        &manifest,
        target_ids,
        Some(lockfile::CapabilitySource::Git(lockfile::GitSource {
            url: clean_url,
            path: source_skill.to_string(),
            git_ref: commit_sha,
            tag: release.map(|release| release.tag),
            requested: request.map(|request| request.to_string()),
        })),
        true,
    );
    drop(source_guard);
    result
}

/// The version a git install records: the release when a tag chose it,
/// else the version the source declares for itself, else the commit.
pub(super) fn git_installed_version(
    skill_dir: &Path,
    release: Option<&release::ReleaseTag>,
    commit_sha: &str,
) -> String {
    match release {
        Some(release) => release.version.to_string(),
        None => manifest::declared_version(skill_dir).unwrap_or_else(|| commit_sha.to_string()),
    }
}

/// The manifest for a capability checked out of git: the real one when the
/// directory has a `tuff.toml`, honouring its type and sections, else one
/// synthesized from the skill directory. `name` overrides the id; the
/// version is always the one the install records.
pub(super) fn git_manifest(
    skill_dir: &Path,
    name: Option<&str>,
    version: &str,
) -> Result<manifest::CapabilityManifest> {
    if skill_dir.join("tuff.toml").is_file() {
        let mut manifest = load_manifest(skill_dir)?;
        if let Some(name) = name {
            manifest::validate_capability_id(name)?;
            manifest.id = name.to_string();
        }
        manifest.version = version.to_string();
        return Ok(manifest);
    }
    let name = name.ok_or_else(|| {
        TuffError::usage("--name is required when the git source has no tuff.toml")
    })?;
    manifest::synthetic_manifest(skill_dir, name, version)
}

/// Adopt or install one local capability directory, the way `tuff add
/// <path>` would.
///
/// `tuff scan --adopt` calls this rather than writing lockfile rows of its
/// own, so there is one implementation of what happens to a local path: the
/// collision warning, the baseline hash, the cache population, and the
/// `Imported` ownership that stops `delete` from removing files Tuff never
/// wrote. Discovery is the only thing scan adds.
pub(crate) fn cmd_add_local_path(
    repo_root: &Path,
    capability_dir: &Path,
    target_id: &str,
    capability_type: CapabilityType,
) -> Result<()> {
    cmd_add_local(
        repo_root,
        Scope::Project,
        capability_dir,
        &[target_id.to_string()],
        repo_root,
        Some(capability_type.as_str()),
        None,
        None,
    )
}

#[expect(
    clippy::too_many_arguments,
    reason = "CLI dispatch passes source and install context"
)]
fn cmd_add_local(
    install_root: &Path,
    scope: Scope,
    capability_path: &Path,
    target_ids: &[String],
    project_root: &Path,
    capability_type: Option<&str>,
    name: Option<&str>,
    hook_file: Option<&Path>,
) -> Result<()> {
    let capability_dir = lockfile::absolutize(install_root, capability_path);
    let parsed_type = capability_type.and_then(CapabilityType::parse);
    let inferred = infer_from_path(&capability_dir);
    let resolved_type = parsed_type.or(Some(inferred.0));
    let mut manifest = load_or_synthetic_manifest(&capability_dir, resolved_type)?;
    if let Some(name) = name {
        manifest::validate_capability_id(name)?;
        manifest.id = name.to_string();
    }
    let resolved = if resolved_type == Some(CapabilityType::Hook) && hook_file.is_some() {
        resolve_native_hook_capability(&capability_dir, name, "0.1.0", hook_file)?
    } else {
        resolve_capability(&manifest)?
    };

    if scope == Scope::Project
        && let Some(warning) = resolver::check_collision(&resolved.id, project_root, None)?
    {
        eprintln!("{warning}");
    }

    if is_target_layout_path(install_root, &capability_dir) {
        // A capability that already lives in a harness layout and is already
        // tracked can still be wanted by a second harness. Emitting it there is
        // an addition to the recorded targets, not a re-adoption, so it does not
        // go through the in-place path and does not disturb the recorded source.
        let tracked = lockfile::require_scoped_lockfile(install_root, scope)?
            .capabilities
            .contains_key(&resolved.id);
        if tracked {
            let added =
                add_missing_targets(install_root, scope, &manifest, &resolved, target_ids, true)?;
            if added == 0 {
                return Err(TuffError::refused(format!(
                    "capability '{}' is already tracked",
                    resolved.id
                ))
                .with_hint(format!(
                    "use 'tuff update {}' for tracked changes",
                    resolved.id
                )));
            }
            return Ok(());
        }
        return adopt_capability_in_place(
            install_root,
            scope,
            &capability_dir,
            &manifest,
            &resolved,
            &inferred.1,
            target_ids,
        );
    }

    install_capability(
        install_root,
        scope,
        &resolved,
        &manifest,
        target_ids,
        None,
        true,
    )
}

fn load_or_synthetic_manifest(
    capability_dir: &Path,
    inferred_type: Option<CapabilityType>,
) -> Result<manifest::CapabilityManifest> {
    if capability_dir.join("tuff.toml").exists() {
        load_manifest(capability_dir)
    } else {
        synthetic_local_manifest(capability_dir, inferred_type)
    }
}

fn synthetic_local_manifest(
    capability_dir: &Path,
    inferred_type: Option<CapabilityType>,
) -> Result<manifest::CapabilityManifest> {
    if !capability_dir.exists() || !capability_dir.is_dir() {
        return Err(TuffError::not_found(format!(
            "directory not found: {}",
            capability_dir.display()
        )));
    }

    let id = capability_dir
        .file_name()
        .ok_or_else(|| TuffError::usage("capability directory must have a name"))?
        .to_string_lossy()
        .to_string();
    let capability_type = inferred_type.unwrap_or(CapabilityType::Skill);

    let mut files = Vec::new();
    for entry in fs::read_dir(capability_dir)? {
        let entry = entry?;
        if !entry.file_type()?.is_file() {
            continue;
        }
        let name = entry.file_name().to_string_lossy().to_string();
        if name != "tuff.toml" {
            files.push(name);
        }
    }
    files.sort();
    if files.is_empty() {
        return Err(TuffError::usage(format!(
            "no source files found in {}",
            capability_dir.display()
        )));
    }

    Ok(manifest::CapabilityManifest {
        id,
        // What the frontmatter declares, if anything (RFC-101 tier 2).
        version: manifest::declared_version(capability_dir).unwrap_or_else(|| "0.1.0".into()),
        capability_type,
        description: "Added from existing agent assets.".into(),
        files,
        parameters: None,
        implementation: None,
        hook: None,
        workflow: None,
        server: None,
        policy: None,
        targets: vec![],
        root: capability_dir.to_path_buf(),
    })
}

fn resolve_native_hook_capability(
    capability_dir: &Path,
    name: Option<&str>,
    version: &str,
    hook_file: Option<&Path>,
) -> Result<adapter::ResolvedCapability> {
    let hook_file = hook_file.ok_or_else(|| TuffError::usage("--hook-file is required"))?;
    let id = name
        .map(str::to_string)
        .or_else(|| {
            capability_dir
                .file_name()
                .map(|name| name.to_string_lossy().to_string())
        })
        .ok_or_else(|| TuffError::usage("hook directory must have a name"))?;

    let hook_path = if hook_file.is_absolute() {
        hook_file.to_path_buf()
    } else {
        capability_dir.join(hook_file)
    };
    if !hook_path.is_file() {
        return Err(TuffError::not_found(format!(
            "hook fragment not found: {}",
            hook_path.display()
        )));
    }
    let hook_rel = hook_path
        .strip_prefix(capability_dir)
        .map_err(|_| TuffError::usage("--hook-file must be inside the hook source directory"))?
        .to_string_lossy()
        .replace('\\', "/");
    crate::tool::check_path_traversal(&hook_rel)?;

    let fragment: serde_json::Value = serde_json::from_str(&fs::read_to_string(&hook_path)?)?;
    let source_files = collect_native_hook_source_files(capability_dir, &hook_path, &id)?;

    Ok(adapter::ResolvedCapability {
        id,
        capability_type: CapabilityType::Hook,
        version: version.to_string(),
        description: "Added from native hook fragment.".into(),
        source_files: source_files.clone(),
        source_dir: capability_dir.to_path_buf(),
        kind: CapabilityKind::Hook {
            hook: HookDefinition::Native(NativeHookConfig {
                fragment,
                source_files,
            }),
        },
    })
}

fn collect_native_hook_source_files(
    capability_dir: &Path,
    hook_path: &Path,
    capability_id: &str,
) -> Result<Vec<(String, Vec<u8>)>> {
    let mut files = Vec::new();
    collect_native_hook_source_files_inner(
        capability_dir,
        capability_dir,
        hook_path,
        capability_id,
        &mut files,
    )?;
    files.sort_by(|left, right| left.0.cmp(&right.0));
    if files.is_empty() {
        eprintln!(
            "note: hook source has no runtime files; only the native hook fragment will be merged"
        );
    }
    Ok(files)
}

fn collect_native_hook_source_files_inner(
    root: &Path,
    current: &Path,
    hook_path: &Path,
    capability_id: &str,
    files: &mut Vec<(String, Vec<u8>)>,
) -> Result<()> {
    for entry in fs::read_dir(current)? {
        let entry = entry?;
        let path = entry.path();
        // `is_dir` and `is_file` follow links, so a link inside a hook
        // source would copy whatever it points at into the project, and a
        // link to an ancestor would recurse forever. Refused, as skill and
        // pack sources already refuse it.
        let metadata = fs::symlink_metadata(&path)?;
        if metadata.file_type().is_symlink() {
            return Err(TuffError::refused(format!(
                "symbolic links are not allowed in capability sources: {}",
                path.display()
            )));
        }
        if metadata.is_dir() {
            collect_native_hook_source_files_inner(root, &path, hook_path, capability_id, files)?;
            continue;
        }
        if !metadata.is_file() || same_file_path(&path, hook_path) {
            continue;
        }

        let rel = path
            .strip_prefix(root)
            .unwrap_or(&path)
            .to_string_lossy()
            .replace('\\', "/");
        if rel == "tuff.toml" {
            continue;
        }
        let Some(rel) = normalize_native_hook_path(&rel, capability_id) else {
            continue;
        };
        files.push((rel, fs::read(&path)?));
    }
    Ok(())
}

fn normalize_native_hook_path(path: &str, capability_id: &str) -> Option<String> {
    const SOURCE_HOOK_ROOTS: &[&str] = &[
        ".codex/hooks/",
        ".claude/hooks/",
        ".agents/hooks/",
        "hooks/",
    ];

    SOURCE_HOOK_ROOTS
        .iter()
        .find_map(|prefix| path.strip_prefix(prefix).map(str::to_string))
        .or_else(|| Some(path.to_string()))
        .map(|path| {
            path.strip_prefix(&format!("{capability_id}/"))
                .unwrap_or(&path)
                .to_string()
        })
        .filter(|path| !path.is_empty())
}

fn same_file_path(left: &Path, right: &Path) -> bool {
    let left = left.canonicalize().unwrap_or_else(|_| left.to_path_buf());
    let right = right.canonicalize().unwrap_or_else(|_| right.to_path_buf());
    left == right
}

fn is_target_layout_path(root: &Path, capability_dir: &Path) -> bool {
    let canonical_root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
    let canonical_dir = capability_dir
        .canonicalize()
        .unwrap_or_else(|_| capability_dir.to_path_buf());
    let rel = canonical_dir
        .strip_prefix(&canonical_root)
        .unwrap_or(canonical_dir.as_path());
    matches!(
        rel.components()
            .next()
            .and_then(|component| component.as_os_str().to_str()),
        Some(".agents" | ".claude" | ".cursor")
    )
}

fn relative_or_absolute_canonical(path: &Path, root: &Path) -> String {
    let canonical_root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
    let canonical_path = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
    canonical_path
        .strip_prefix(&canonical_root)
        .map(|relative| relative.to_string_lossy().replace('\\', "/"))
        .unwrap_or_else(|_| lockfile::relative_or_absolute_fs(path, root))
}

fn adopt_capability_in_place(
    install_root: &Path,
    scope: Scope,
    capability_dir: &Path,
    manifest: &manifest::CapabilityManifest,
    capability: &adapter::ResolvedCapability,
    inferred_target: &str,
    target_ids: &[String],
) -> Result<()> {
    for target_id in target_ids {
        if target_id != inferred_target {
            return Err(TuffError::usage(format!(
                "{} is already in the '{}' agent layout; use -a {}",
                lockfile::relative_or_absolute_fs(capability_dir, install_root),
                inferred_target,
                inferred_target
            )));
        }
    }

    let mut lockfile = lockfile::require_scoped_lockfile(install_root, scope)?;
    if lockfile.capabilities.contains_key(&capability.id) {
        return Err(TuffError::refused(format!(
            "capability '{}' is already tracked",
            capability.id
        ))
        .with_hint(format!(
            "use 'tuff update {}' for tracked changes",
            capability.id
        )));
    }

    let mut targets = BTreeMap::new();
    let installed_root = capability_dir.to_path_buf();
    let baseline_hash = crate::cache::hash_tree(&installed_root)?;
    crate::cache::populate(&super::home_dir()?, &baseline_hash, &installed_root)?;
    targets.insert(
        inferred_target.to_string(),
        lockfile::TargetLockEntry {
            managed_hooks: Vec::new(),
            managed_mcp_entry: None,
            managed_permissions: Vec::new(),
            ownership: lockfile::TargetOwnership::Imported,
            sha256: baseline_hash,
            installed_path: relative_or_absolute_canonical(capability_dir, install_root),
        },
    );

    lockfile.capabilities.insert(
        capability.id.clone(),
        lockfile::CapabilityLockEntry {
            capability_type: capability.capability_type,
            version: capability.version.clone(),
            version_scheme: lockfile::VersionScheme::Declared,
            description: capability.description.clone(),
            source: lockfile::CapabilitySource::local(relative_or_absolute_canonical(
                capability_dir,
                install_root,
            )),
            targets,
            implementation: manifest.implementation.clone(),
            parameters: manifest.parameters.clone(),
            workflow: manifest.workflow.clone(),
            server: manifest.server.clone(),
        },
    );
    lockfile::write_scoped_lockfile(install_root, scope, &lockfile)?;
    capability_index::regenerate_capability_index(install_root, scope)?;
    println!(
        "added {} ({}, {}) -> {}",
        capability.id,
        capability.capability_type,
        inferred_target,
        relative_or_absolute_canonical(capability_dir, install_root)
    );
    Ok(())
}

/// Write one planned file to disk and record it as an `EmittedFile`.
///
/// Shared by `install_capability`'s write phase and the generated
/// capability-index skill (`capability_index.rs`), which has no hooks or
/// reporting to layer on top — just files to write and hash.
pub(crate) fn write_planned_file(
    install_root: &Path,
    planned: &adapter::PlannedFile,
) -> Result<adapter::EmittedFile> {
    let target_path = install_root.join(contained_planned_path(&planned.path)?);
    if let Some(parent) = target_path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    std::fs::write(&target_path, &planned.content)?;

    Ok(adapter::EmittedFile {
        path: planned.path.clone(),
        hash: lockfile::hash_bytes(&planned.content),
        baseline_hash: lockfile::hash_bytes(&planned.content),
    })
}

/// Refuse to write a planned file anywhere but under the install root.
///
/// Planners build these paths from manifest content, so this is the last
/// line of defence if one of them ever lets `..` or an absolute path
/// through: nothing is written outside the project, whatever planned it.
pub(crate) fn contained_planned_path(path: &str) -> Result<std::path::PathBuf> {
    crate::pack::validate_relative_path(Path::new(path)).map_err(|_| {
        TuffError::refused(format!(
            "refusing to write outside the install directory: '{path}'"
        ))
    })
}

/// Emits an already-tracked capability into harnesses it is not yet recorded
/// for, and records those targets. Returns how many targets were added.
///
/// The recorded source, version, and description belong to the original
/// install, so they are restored afterwards: adding a harness says nothing new
/// about where the capability came from. A target that is already recorded is
/// skipped rather than re-emitted, which keeps the call idempotent.
pub(crate) fn add_missing_targets(
    install_root: &Path,
    scope: Scope,
    manifest: &manifest::CapabilityManifest,
    capability: &adapter::ResolvedCapability,
    target_ids: &[String],
    report: bool,
) -> Result<usize> {
    let lockfile = lockfile::require_scoped_lockfile(install_root, scope)?;
    let existing = lockfile
        .capabilities
        .get(&capability.id)
        .ok_or_else(|| {
            TuffError::not_found(format!("capability '{}' is not tracked", capability.id))
        })?
        .clone();

    let missing: Vec<String> = target_ids
        .iter()
        .filter(|target_id| !existing.targets.contains_key(*target_id))
        .cloned()
        .collect();
    if missing.is_empty() {
        return Ok(0);
    }

    install_capability(
        install_root,
        scope,
        capability,
        manifest,
        &missing,
        Some(existing.source.clone()),
        report,
    )?;

    let mut lockfile = lockfile::require_scoped_lockfile(install_root, scope)?;
    if let Some(entry) = lockfile.capabilities.get_mut(&capability.id) {
        entry.version = existing.version;
        entry.version_scheme = existing.version_scheme;
        entry.description = existing.description;
        entry.implementation = existing.implementation;
        entry.parameters = existing.parameters;
        entry.workflow = existing.workflow;
        entry.server = existing.server;
    }
    lockfile::write_scoped_lockfile(install_root, scope, &lockfile)?;

    Ok(missing.len())
}

/// Emits a tracked capability, read from the directory it is installed in, into
/// additional harnesses. Used by `tuff init` to give a detected harness the CLI
/// guide it would otherwise never see.
pub(crate) fn add_targets_from_installed_dir(
    install_root: &Path,
    scope: Scope,
    capability_dir: &Path,
    target_ids: &[String],
    report: bool,
) -> Result<usize> {
    let inferred = infer_from_path(capability_dir);
    let manifest = load_or_synthetic_manifest(capability_dir, Some(inferred.0))?;
    let resolved = resolve_capability(&manifest)?;
    add_missing_targets(
        install_root,
        scope,
        &manifest,
        &resolved,
        target_ids,
        report,
    )
}

/// A policy compiled for one agent, ready to write once nothing can refuse.
struct CompiledPolicy {
    settings_path: std::path::PathBuf,
    merged: Vec<u8>,
    managed: Vec<lockfile::ManagedPermission>,
}

/// Say, per agent, which rules are enforced only partially and why.
fn warn_partially_enforced_policy(
    policy: &tuff_core::policy::PolicyConfig,
    target_ids: &[String],
) -> Result<()> {
    for tid in target_ids {
        let Some(adapter) = AdapterKind::from_id(tid) else {
            continue;
        };
        for verdict in tuff_core::policy::verdicts(policy, &adapter.policy_compatibility())? {
            if verdict.entry.coverage == tuff_hooks_spec::CoverageLevel::Partial {
                let why = verdict
                    .entry
                    .caveat
                    .as_deref()
                    .unwrap_or("partial coverage");
                eprintln!(
                    "{}: rule {} ({}) is enforced partially: {why}",
                    adapter.display_name(),
                    verdict.index + 1,
                    verdict.rule.describe()
                );
            }
        }
    }
    Ok(())
}

/// Compile a policy into each agent's native permission rules and compute
/// the settings file each will hold, removing rules a previous install of
/// the same policy recorded and this one no longer has. Everything here can
/// refuse, a corrupt settings file included, and nothing here writes.
fn compile_policy(
    install_root: &Path,
    capability_id: &str,
    policy: &tuff_core::policy::PolicyConfig,
    adapters: &[AdapterKind],
    lockfile: &lockfile::Lockfile,
) -> Result<BTreeMap<String, CompiledPolicy>> {
    let mut compiled = BTreeMap::new();
    for adapter in adapters {
        let settings_relpath = adapter.permissions_settings_relpath().ok_or_else(|| {
            TuffError::unsupported(format!(
                "{} has no native permission rules for policy '{capability_id}'",
                adapter.display_name()
            ))
        })?;
        let mut managed: Vec<lockfile::ManagedPermission> = Vec::new();
        for rule in &policy.rules {
            let effect = rule.effect()?;
            let native = adapter.native_permission_rules(rule)?.ok_or_else(|| {
                TuffError::unsupported(format!(
                    "{} cannot compile policy rule ({}) natively",
                    adapter.display_name(),
                    rule.describe()
                ))
            })?;
            for native_rule in native {
                let permission = lockfile::ManagedPermission {
                    settings_path: settings_relpath.to_string(),
                    list: effect.as_str().to_string(),
                    rule: native_rule,
                };
                if !managed.contains(&permission) {
                    managed.push(permission);
                }
            }
        }
        let as_pairs = |permissions: &mut dyn Iterator<Item = &lockfile::ManagedPermission>| {
            permissions
                .filter_map(|permission| {
                    tuff_core::policy::PolicyEffect::parse(&permission.list)
                        .map(|effect| (effect, permission.rule.clone()))
                })
                .collect::<Vec<_>>()
        };
        let previous = lockfile
            .capabilities
            .get(capability_id)
            .and_then(|entry| entry.targets.get(adapter.id()))
            .map(|target| target.managed_permissions.clone())
            .unwrap_or_default();
        let stale = as_pairs(&mut previous.iter().filter(|permission| {
            permission.settings_path == settings_relpath && !managed.contains(permission)
        }));
        let additions = as_pairs(&mut managed.iter());
        let settings_path = install_root.join(settings_relpath);
        let existing = if settings_path.is_file() {
            Some(fs::read(&settings_path)?)
        } else {
            None
        };
        let merged = tuff_core::policy::merge_permissions(
            settings_relpath,
            existing.as_deref(),
            &stale,
            &additions,
        )?;
        compiled.insert(
            adapter.id().to_string(),
            CompiledPolicy {
                settings_path,
                merged,
                managed,
            },
        );
    }
    Ok(compiled)
}

/// Refuse a policy any rule of which a selected agent would not enforce.
///
/// A policy reported as installed where nothing enforces it is worse than
/// no policy, because it removes the reason to look. Every rule is checked
/// against every selected agent's matrix before anything is planned or
/// written, and each rule an agent would not enforce is named.
fn refuse_unenforced_policy(
    id: &str,
    policy: &tuff_core::policy::PolicyConfig,
    target_ids: &[String],
) -> Result<()> {
    let mut unenforced = Vec::new();
    for tid in target_ids {
        let adapter = AdapterKind::from_id(tid).ok_or_else(|| {
            TuffError::usage(format!("unknown agent '{tid}'"))
                .with_hint("run 'tuff agent list' to see available agents")
        })?;
        for verdict in tuff_core::policy::verdicts(policy, &adapter.policy_compatibility())? {
            if verdict.entry.coverage == tuff_hooks_spec::CoverageLevel::Unsupported {
                let why = verdict
                    .entry
                    .caveat
                    .as_deref()
                    .map(|caveat| format!(": {caveat}"))
                    .unwrap_or_default();
                unenforced.push(format!(
                    "  {}: rule {} ({}) is not enforced{why}",
                    adapter.display_name(),
                    verdict.index + 1,
                    verdict.rule.describe()
                ));
            }
        }
    }
    if unenforced.is_empty() {
        return Ok(());
    }
    Err(TuffError::unsupported(format!(
        "policy '{id}' would not be enforced as written, so it was not installed:\n{}",
        unenforced.join("\n")
    ))
    .with_hint("run 'tuff policy matrix' to see what each agent can enforce"))
}

pub(crate) fn install_capability(
    install_root: &Path,
    scope: Scope,
    capability: &adapter::ResolvedCapability,
    manifest: &manifest::CapabilityManifest,
    target_ids: &[String],
    source: Option<lockfile::CapabilitySource>,
    report: bool,
) -> Result<()> {
    if let CapabilityKind::Policy { ref policy } = capability.kind {
        refuse_unenforced_policy(&capability.id, policy, target_ids)?;
        if report {
            warn_partially_enforced_policy(policy, target_ids)?;
        }
    }
    let mut adapters = Vec::new();
    for tid in target_ids {
        let adapter = AdapterKind::from_id(tid).ok_or_else(|| {
            TuffError::usage(format!("unknown agent '{}'", tid,))
                .with_hint("run 'tuff agent list' to see available agents")
        })?;
        if !adapter.supports(capability.capability_type) {
            return Err(TuffError::unsupported(format!(
                "{} does not yet support {} capabilities",
                adapter.display_name(),
                capability.capability_type
            )));
        }
        if let CapabilityKind::Hook {
            hook: HookDefinition::Command(ref hook_cfg),
        } = capability.kind
        {
            adapter.native_hook_event(&hook_cfg.event)?;
        }
        adapters.push(adapter);
    }

    let mut plans: Vec<(AdapterKind, Vec<adapter::PlannedFile>)> = Vec::new();
    for adapter in &adapters {
        let planned = adapter.plan(capability, install_root)?;
        plans.push((*adapter, planned));
    }

    let lockfile = lockfile::require_scoped_lockfile(install_root, scope)?;
    for (adapter, planned_files) in &plans {
        let is_tracked = lockfile
            .capabilities
            .get(&capability.id)
            .and_then(|e| e.targets.get(adapter.id()))
            .is_some();
        if !is_tracked {
            for f in planned_files {
                if f.allow_existing {
                    continue;
                }
                let target_path = install_root.join(&f.path);
                if target_path.exists() {
                    return Err(TuffError::refused(format!(
                        "refusing to overwrite untracked file at {}",
                        lockfile::relative_or_absolute_fs(&target_path, install_root)
                    ))
                    .with_hint("remove it, or track it in Tuff first"));
                }
            }
        }
    }

    if matches!(
        capability.kind,
        CapabilityKind::Tool { .. } | CapabilityKind::McpServer { .. }
    ) {
        for adapter in &adapters {
            let mcp_path = install_root.join(adapter.mcp_config_relpath());
            tuff_core::mcp::validate_config(&mcp_path)?;

            // For an external server the JSON entry *is* the product, so an
            // entry Tuff never wrote is a collision — refuse here, before a
            // single file lands, rather than after `server.toml` is written.
            if matches!(capability.kind, CapabilityKind::McpServer { .. })
                && !mcp_entry_tracked(&lockfile, &capability.id, adapter.id())
                && tuff_core::mcp::has_server(&mcp_path, &capability.id)?
            {
                return Err(TuffError::refused(format!(
                    "refusing to overwrite untracked MCP server '{}' in {}",
                    capability.id,
                    lockfile::relative_or_absolute_fs(&mcp_path, install_root)
                ))
                .with_hint("remove it by hand, or choose a different capability id"));
            }
        }
    }

    let compiled_policies = match &capability.kind {
        CapabilityKind::Policy { policy } => {
            compile_policy(install_root, &capability.id, policy, &adapters, &lockfile)?
        }
        _ => BTreeMap::new(),
    };

    let mut new_targets: BTreeMap<String, TargetLockEntry> = BTreeMap::new();

    for (adapter, planned_files) in &plans {
        let mut managed_hooks = Vec::new();

        if let CapabilityKind::Hook { hook } = &capability.kind {
            let hook_root = install_root
                .join(adapter.dir_prefix())
                .join("hooks")
                .join(&capability.id);
            let hook_root_rel = lockfile::relative_or_absolute_fs(&hook_root, install_root);
            match hook {
                HookDefinition::Command(hook_cfg) => {
                    let render = adapter.render_standard_hook(HookRenderContext {
                        capability_id: &capability.id,
                        hook: hook_cfg,
                        source_files: &capability.source_files,
                        repo_root: install_root,
                        track_managed_hooks: true,
                    })?;
                    if report {
                        for diagnostic in render.diagnostics {
                            eprintln!("{}", diagnostic.message);
                        }
                    }
                    managed_hooks = render.managed_hooks;
                }
                HookDefinition::Native(native) => {
                    let fragment = adapter::replace_hook_dir_placeholder(
                        native.fragment.clone(),
                        &hook_root_rel,
                    );
                    let settings_path = adapter.hook_settings_relpath();
                    managed_hooks = lockfile::managed_hooks_from_fragment(
                        install_root,
                        settings_path,
                        &fragment,
                    )?;
                }
            }
        }

        for planned in planned_files {
            let target_path = install_root.join(&planned.path);
            write_planned_file(install_root, planned)?;

            if report && should_print_installed_file(capability, planned) {
                println!(
                    "installed {} ({}) -> {}",
                    capability.id,
                    adapter.id(),
                    lockfile::relative_or_absolute_fs(&target_path, install_root)
                );
            }
        }

        if let Some(compiled) = compiled_policies.get(adapter.id()) {
            if let Some(parent) = compiled.settings_path.parent() {
                fs::create_dir_all(parent)?;
            }
            fs::write(&compiled.settings_path, &compiled.merged)?;
            if report {
                println!(
                    "compiled {} permission rule(s) for {} ({}) -> {}",
                    compiled.managed.len(),
                    capability.id,
                    adapter.id(),
                    lockfile::relative_or_absolute_fs(&compiled.settings_path, install_root)
                );
            }
        }

        let installed_root = install_root
            .join(adapter.dir_prefix())
            .join(capability.capability_type.plural_dir())
            .join(&capability.id);
        let baseline_hash = crate::cache::hash_tree(&installed_root)?;
        crate::cache::populate(&super::home_dir()?, &baseline_hash, &installed_root)?;
        new_targets.insert(
            adapter.id().to_string(),
            TargetLockEntry {
                managed_hooks,
                managed_mcp_entry: None,
                managed_permissions: compiled_policies
                    .get(adapter.id())
                    .map(|compiled| compiled.managed.clone())
                    .unwrap_or_default(),
                ownership: target_ownership_for(capability, install_root, *adapter),
                sha256: baseline_hash,
                installed_path: lockfile::relative_or_absolute_fs(&installed_root, install_root),
            },
        );
    }

    if let CapabilityKind::Tool {
        implementation: ref impl_cfg,
        ..
    } = capability.kind
    {
        if impl_cfg.mcp {
            for adapter in &adapters {
                let mcp_path = install_root.join(adapter.mcp_config_relpath());

                let mcp_command = impl_cfg.language.clone();
                let entrypoint_path = format!(
                    "{}/tools/{}/{}",
                    adapter.dir_prefix(),
                    capability.id,
                    impl_cfg.entrypoint
                );
                let mcp_args = vec![entrypoint_path];

                crate::adapters::mcp_register_tool(
                    install_root,
                    &mcp_path,
                    &capability.id,
                    &mcp_command,
                    &mcp_args,
                )?;
                // MCP-native tools get the same per-entry baseline as
                // external servers: the entry shape below must match what
                // `mcp::register_tool` writes.
                let entry_value = serde_json::json!({"command": mcp_command, "args": mcp_args});
                if let Some(target) = new_targets.get_mut(adapter.id()) {
                    target.managed_mcp_entry = Some(lockfile::ManagedMcpEntry {
                        config_path: adapter.mcp_config_relpath().to_string(),
                        baseline_hash: lockfile::managed_mcp_entry_baseline(&entry_value)?,
                    });
                }
                if report {
                    println!(
                        "registered MCP server {} ({}) -> {}",
                        capability.id,
                        adapter.id(),
                        lockfile::relative_or_absolute_fs(&mcp_path, install_root)
                    );
                }
            }
        } else {
            for adapter in &adapters {
                let mcp_path = install_root.join(adapter.mcp_config_relpath());
                crate::adapters::mcp_remove_tool(install_root, &mcp_path, &capability.id)?;
            }
            if report {
                eprintln!(
                    "note: tool '{}' is not MCP-native; copied and tracked without MCP registration",
                    capability.id
                );
            }
        }
    }

    if let CapabilityKind::McpServer { ref server } = capability.kind {
        for adapter in &adapters {
            let mcp_path = install_root.join(adapter.mcp_config_relpath());
            let tracked = mcp_entry_tracked(&lockfile, &capability.id, adapter.id());
            let entry_value = adapter.mcp_server_entry(server);
            let baseline = lockfile::managed_mcp_entry_baseline(&entry_value)?;
            crate::adapters::mcp_register_server(
                install_root,
                &mcp_path,
                &capability.id,
                entry_value,
                tracked,
            )?;
            if let Some(target) = new_targets.get_mut(adapter.id()) {
                target.managed_mcp_entry = Some(lockfile::ManagedMcpEntry {
                    config_path: adapter.mcp_config_relpath().to_string(),
                    baseline_hash: baseline,
                });
            }
            if report {
                println!(
                    "registered MCP server {} ({}) -> {}",
                    capability.id,
                    adapter.id(),
                    lockfile::relative_or_absolute_fs(&mcp_path, install_root)
                );
            }
        }
        let required = crate::catalog::required_env(server);
        if report && !required.is_empty() {
            eprintln!(
                "note: '{}' reads {} from the environment; export {} before starting the harness",
                capability.id,
                if required.len() == 1 {
                    "a variable"
                } else {
                    "variables"
                },
                required.join(", ")
            );
        }
    }

    let mut lockfile = lockfile;
    let existing_targets = lockfile
        .capabilities
        .get(&capability.id)
        .map(|e| e.targets.clone())
        .unwrap_or_default();

    let mut merged_targets = existing_targets;
    for (k, v) in new_targets {
        merged_targets.insert(k, v);
    }

    let source = source.unwrap_or_else(|| {
        lockfile::CapabilitySource::local(lockfile::relative_or_absolute_fs(
            &manifest.root,
            install_root,
        ))
    });

    lockfile.capabilities.insert(
        capability.id.clone(),
        lockfile::CapabilityLockEntry {
            capability_type: capability.capability_type,
            version: capability.version.clone(),
            version_scheme: source.version_scheme_for(&capability.version),
            description: capability.description.clone(),
            source,
            targets: merged_targets,
            implementation: manifest.implementation.clone(),
            parameters: manifest.parameters.clone(),
            workflow: manifest.workflow.clone(),
            server: manifest.server.clone(),
        },
    );

    lockfile::write_scoped_lockfile(install_root, scope, &lockfile)?;
    capability_index::regenerate_capability_index(install_root, scope)?;
    Ok(())
}

fn should_print_installed_file(
    capability: &adapter::ResolvedCapability,
    planned: &adapter::PlannedFile,
) -> bool {
    if capability.capability_type != CapabilityType::Skill {
        return true;
    }
    Path::new(&planned.path).file_name() == Some(std::ffi::OsStr::new("SKILL.md"))
}

fn target_ownership_for(
    capability: &adapter::ResolvedCapability,
    install_root: &Path,
    adapter: AdapterKind,
) -> lockfile::TargetOwnership {
    if matches!(
        &capability.kind,
        CapabilityKind::Hook {
            hook: HookDefinition::Native(_)
        }
    ) && is_path_under(
        &capability.source_dir,
        &install_root.join(adapter.dir_prefix()),
    ) {
        lockfile::TargetOwnership::Imported
    } else {
        lockfile::TargetOwnership::Generated
    }
}

fn is_path_under(path: &Path, root: &Path) -> bool {
    let canonical_root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
    let canonical_path = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
    canonical_path.starts_with(canonical_root)
}

#[cfg(test)]
mod tests {
    use super::{normalize_native_hook_path, rename_env_var, resolve_prompt_answer};
    use crate::manifest::{EnvRef, McpServerConfig, McpTransport};

    #[test]
    fn resolve_prompt_answer_keeps_default_on_blank_or_matching_input() {
        assert_eq!(resolve_prompt_answer("GITHUB_TOKEN", "\n"), None);
        assert_eq!(resolve_prompt_answer("GITHUB_TOKEN", "   \n"), None);
        assert_eq!(
            resolve_prompt_answer("GITHUB_TOKEN", "GITHUB_TOKEN\n"),
            None
        );
    }

    #[test]
    fn resolve_prompt_answer_returns_a_trimmed_different_name() {
        assert_eq!(
            resolve_prompt_answer("GITHUB_TOKEN", "  GH_TOKEN  \n"),
            Some("GH_TOKEN".to_string())
        );
    }

    #[test]
    fn rename_env_var_replaces_both_the_key_and_the_reference() {
        let mut server = McpServerConfig {
            transport: McpTransport::Stdio,
            command: Some("npx".to_string()),
            args: Vec::new(),
            url: None,
            env: std::collections::BTreeMap::from([(
                "GITHUB_TOKEN".to_string(),
                EnvRef {
                    from_env: "GITHUB_TOKEN".to_string(),
                },
            )]),
            headers: std::collections::BTreeMap::new(),
            metadata: None,
        };
        rename_env_var(&mut server, "GITHUB_TOKEN", "GH_TOKEN");
        assert!(!server.env.contains_key("GITHUB_TOKEN"));
        assert_eq!(server.env["GH_TOKEN"].from_env, "GH_TOKEN");
    }

    #[test]
    fn rename_env_var_is_a_no_op_for_an_unknown_name() {
        let mut server = McpServerConfig {
            transport: McpTransport::Stdio,
            command: Some("npx".to_string()),
            args: Vec::new(),
            url: None,
            env: std::collections::BTreeMap::new(),
            headers: std::collections::BTreeMap::new(),
            metadata: None,
        };
        rename_env_var(&mut server, "NOT_PRESENT", "OTHER");
        assert!(server.env.is_empty());
    }

    #[test]
    fn native_hook_paths_strip_source_harness_roots() {
        assert_eq!(
            normalize_native_hook_path(".codex/hooks/change-logger/run.sh", "change-logger"),
            Some("run.sh".to_string())
        );
        assert_eq!(
            normalize_native_hook_path(".claude/hooks/run.sh", "change-logger"),
            Some("run.sh".to_string())
        );
        assert_eq!(
            normalize_native_hook_path("hooks/run.sh", "change-logger"),
            Some("run.sh".to_string())
        );
    }

    #[test]
    fn native_hook_paths_preserve_runtime_paths() {
        assert_eq!(
            normalize_native_hook_path("config/change-logger.json", "change-logger"),
            Some("config/change-logger.json".to_string())
        );
    }
}