luaskills 0.2.3

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

use semver::Version;
use serde::{Deserialize, Serialize};

use crate::download::archive::extract_skill_package_zip;
use crate::download::manager::{DownloadManager, DownloadManagerConfig};
use crate::host::options::RuntimeSkillRoot;
use crate::lua_skill::{SkillMeta, validate_luaskills_identifier, validate_luaskills_version};
use crate::skill::source::{
    InstalledSkillRecord, InstalledSkillSourceRecord, SkillInstallSourceType,
};

/// Lifecycle operations that the LuaSkills manager layer exposes for one skill.
/// LuaSkills 管理层为单个技能公开的生命周期操作类型。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum SkillLifecycleAction {
    Install,
    Update,
    Reload,
    Uninstall,
    Enable,
    Disable,
}

/// Logical operation plane used to distinguish host system controls from ordinary skill controls.
/// 用于区分宿主系统控制面与普通技能控制面的逻辑操作平面。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum SkillOperationPlane {
    Skills,
    System,
}

/// Authority level supplied by the host for system skill-management entrypoints.
/// 宿主为系统级技能管理入口注入的权限等级。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SkillManagementAuthority {
    /// Full host-system authority that may write the ROOT skill layer.
    /// 可写入 ROOT 技能层的完整宿主系统权限。
    System,
    /// Delegated tool authority that must follow ordinary PROJECT/USER boundaries.
    /// 必须遵守普通 PROJECT/USER 边界的委托工具权限。
    DelegatedTool,
}

/// High-level manager configuration that defines where installed skills and their state are stored.
/// 定义已安装技能及其状态存放位置的高层管理配置。
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SkillManagerConfig {
    /// Named skill root whose lifecycle state is managed by the current manager instance.
    /// 当前管理器实例所管理的命名技能根。
    pub skill_root: RuntimeSkillRoot,
    /// Root directory where lifecycle sidecar state of the current named skill root is persisted.
    /// 当前命名技能根生命周期旁路状态的持久化根目录。
    pub lifecycle_root: PathBuf,
    /// Root directory used to cache downloaded skill packages and remote manifests.
    /// 用于缓存下载技能包与远程清单的根目录。
    pub download_cache_root: PathBuf,
    /// Whether managed skill install/update flows may access the network.
    /// 受管技能安装/更新流程是否允许访问网络。
    pub allow_network_download: bool,
    /// Optional GitHub site base URL override used by managed GitHub installs.
    /// 受管 GitHub 安装使用的可选 GitHub 站点基址覆盖。
    #[serde(default)]
    pub github_base_url: Option<String>,
    /// Optional GitHub API base URL override used by managed GitHub installs.
    /// 受管 GitHub 安装使用的可选 GitHub API 基址覆盖。
    #[serde(default)]
    pub github_api_base_url: Option<String>,
}

/// One install request accepted by the future LuaSkills manager entrypoints.
/// 未来 LuaSkills 管理入口接受的单次安装请求定义。
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SkillInstallRequest {
    /// Optional skill id used for install-by-name flows.
    /// 供按名称安装流程使用的可选 skill id。
    pub skill_id: Option<String>,
    /// Optional raw source string such as URL or local directory.
    /// 例如 URL 或本地目录一类的可选原始来源字符串。
    pub source: Option<String>,
    /// Source type used to interpret the source locator. Defaults to GitHub.
    /// 用于解释来源定位值的来源类型,默认使用 GitHub。
    #[serde(default)]
    pub source_type: SkillInstallSourceType,
}

/// One install or update result returned by the skill manager.
/// 由技能管理器返回的单次安装或更新结果。
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SkillApplyResult {
    /// Stable skill identifier targeted by the current operation.
    /// 当前操作目标的稳定技能标识符。
    pub skill_id: String,
    /// High-level result status such as blocked, already_installed, or not_implemented.
    /// 高层结果状态,例如 blocked、already_installed 或 not_implemented。
    pub status: String,
    /// Human-readable explanation of the current result.
    /// 当前结果的人类可读解释文本。
    pub message: String,
    /// Optional semantic version involved in the current install/update result.
    /// 当前安装/更新结果涉及的可选语义化版本。
    #[serde(default)]
    pub version: Option<String>,
    /// Optional managed install source type involved in the current result.
    /// 当前结果涉及的可选受管安装来源类型。
    #[serde(default)]
    pub source_type: Option<SkillInstallSourceType>,
    /// Optional stable source locator involved in the current result.
    /// 当前结果涉及的可选稳定来源定位值。
    #[serde(default)]
    pub source_locator: Option<String>,
}

/// One staged install/update mutation that is not committed until runtime reload succeeds.
/// 单个尚未提交的安装/更新变更,只有运行时重载成功后才会最终提交。
#[derive(Debug, Clone)]
pub enum PreparedSkillApply {
    /// One immediate result that does not mutate disk state.
    /// 一个不会修改磁盘状态的即时结果。
    Immediate(SkillApplyResult),
    /// One staged install mutation waiting for commit or rollback.
    /// 一个等待提交或回滚的已暂存安装变更。
    Install(PreparedSkillInstall),
    /// One staged update mutation waiting for commit or rollback.
    /// 一个等待提交或回滚的已暂存更新变更。
    Update(PreparedSkillUpdate),
}

/// One staged install mutation prepared before the runtime reload is attempted.
/// 在尝试运行时重载之前准备好的单次安装暂存变更。
#[derive(Debug, Clone)]
pub struct PreparedSkillInstall {
    /// Structured install result returned after the staged install succeeds.
    /// 暂存安装成功后返回的结构化安装结果。
    pub result: SkillApplyResult,
    /// Final target directory where the installed skill has been staged.
    /// 已暂存安装技能的最终目标目录。
    pub target_dir: PathBuf,
    /// Install record that should be persisted only after runtime reload succeeds.
    /// 只有运行时重载成功后才应持久化的安装记录。
    pub install_record: InstalledSkillRecord,
}

/// One staged update mutation prepared before the runtime reload is attempted.
/// 在尝试运行时重载之前准备好的单次更新暂存变更。
#[derive(Debug, Clone)]
pub struct PreparedSkillUpdate {
    /// Structured update result returned after the staged update succeeds.
    /// 暂存更新成功后返回的结构化更新结果。
    pub result: SkillApplyResult,
    /// Final target directory currently holding the staged new skill package.
    /// 当前持有已暂存新技能包的最终目标目录。
    pub target_dir: PathBuf,
    /// Backup directory that still contains the previous skill package until commit completes.
    /// 在提交完成前仍保存旧技能包的备份目录。
    pub backup_dir: PathBuf,
    /// Updated install record that should be persisted only after runtime reload succeeds.
    /// 只有运行时重载成功后才应持久化的更新后安装记录。
    pub install_record: InstalledSkillRecord,
    /// Previous install record that should be restored if the update commit partially fails.
    /// 如果更新提交发生部分失败则需要恢复的旧安装记录。
    pub previous_install_record: InstalledSkillRecord,
}

/// One staged uninstall mutation prepared before the runtime reload is attempted.
/// 在尝试运行时重载之前准备好的单次卸载暂存变更。
#[derive(Debug, Clone)]
pub struct PreparedSkillUninstall {
    /// Structured uninstall result returned after the staged uninstall succeeds.
    /// 暂存卸载成功后返回的结构化卸载结果。
    pub result: SkillUninstallResult,
    /// Final target directory currently reserved for the installed skill.
    /// 当前为已安装技能保留的最终目标目录。
    pub target_dir: PathBuf,
    /// Backup directory that still contains the previous skill package until commit completes.
    /// 在提交完成前仍保存旧技能包的备份目录。
    pub backup_dir: Option<PathBuf>,
    /// Previous disabled-state record that should be restored if uninstall rollback is needed.
    /// 如果需要回滚卸载则应恢复的旧停用状态记录。
    pub previous_disabled_record: Option<DisabledSkillRecord>,
    /// Previous managed install record that should be restored if uninstall rollback is needed.
    /// 如果需要回滚卸载则应恢复的旧受管安装记录。
    pub previous_install_record: Option<InstalledSkillRecord>,
}

/// Optional database cleanup switches accepted by skill uninstall operations.
/// 技能卸载操作接受的可选数据库清理开关集合。
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct SkillUninstallOptions {
    /// Remove the SQLite database directory owned by the target skill when true.
    /// 为 true 时删除目标技能拥有的 SQLite 数据目录。
    #[serde(default)]
    pub remove_sqlite: bool,
    /// Remove the LanceDB database directory owned by the target skill when true.
    /// 为 true 时删除目标技能拥有的 LanceDB 数据目录。
    #[serde(default)]
    pub remove_lancedb: bool,
}

/// Structured uninstall result that reports whether code and databases were removed or retained.
/// 结构化卸载结果,用于报告代码与数据库是被删除还是被保留。
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SkillUninstallResult {
    /// Stable skill identifier targeted by the current uninstall action.
    /// 当前卸载动作目标的稳定技能标识符。
    pub skill_id: String,
    /// Whether the skill package directory itself was removed.
    /// skill 包目录本身是否已经被删除。
    pub skill_removed: bool,
    /// Whether the SQLite database directory was removed explicitly.
    /// SQLite 数据目录是否已被显式删除。
    pub sqlite_removed: bool,
    /// Whether the LanceDB database directory was removed explicitly.
    /// LanceDB 数据目录是否已被显式删除。
    pub lancedb_removed: bool,
    /// Whether the SQLite database directory was intentionally retained.
    /// SQLite 数据目录是否被有意保留。
    pub sqlite_retained: bool,
    /// Whether the LanceDB database directory was intentionally retained.
    /// LanceDB 数据目录是否被有意保留。
    pub lancedb_retained: bool,
    /// Human-readable explanation of the uninstall result.
    /// 当前卸载结果的人类可读说明文本。
    pub message: String,
}

/// One resolved effective skill instance after applying root precedence rules.
/// 应用根目录优先级规则后得到的单个生效技能实例。
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ResolvedSkillInstance {
    /// Stable skill identifier resolved from the directory name.
    /// 从目录名称解析出的稳定技能标识符。
    pub skill_id: String,
    /// Named skill root that currently owns the effective skill instance.
    /// 当前生效技能实例所属的命名技能根。
    pub root_name: String,
    /// Physical skills root directory that currently owns the effective skill instance.
    /// 当前生效技能实例所属的物理 skills 根目录。
    pub skills_root: PathBuf,
    /// Physical skill directory that is currently effective for the resolved skill id.
    /// 当前针对该技能标识符实际生效的物理技能目录。
    pub actual_dir: PathBuf,
}

/// Persistent record written when one skill is explicitly disabled.
/// 显式停用某个技能时写入的持久化记录。
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DisabledSkillRecord {
    /// Stable skill identifier bound to this state record.
    /// 与当前状态记录绑定的稳定 skill 标识符。
    pub skill_id: String,
    /// Optional human-readable disable reason.
    /// 可选的人类可读停用原因。
    pub reason: Option<String>,
    /// Unix timestamp in milliseconds when the skill was disabled.
    /// 当前技能被停用时的 Unix 毫秒时间戳。
    pub disabled_at_unix_ms: u128,
}

/// Skill manager that owns persisted skill enabled/disabled state.
/// 持有技能启用/停用持久状态的技能管理器。
pub struct SkillManager {
    config: SkillManagerConfig,
}

/// Drop guard that removes one staging directory unless the caller explicitly disarms it.
/// 除非调用方显式解除,否则在析构时删除单个暂存目录的清理守卫。
struct TempDirGuard {
    /// Physical staging directory that should be removed on drop.
    /// 析构时应被移除的物理暂存目录。
    path: PathBuf,
    /// Whether automatic cleanup has been disabled explicitly.
    /// 是否已经被显式关闭自动清理。
    disarmed: bool,
}

impl TempDirGuard {
    /// Create one cleanup guard bound to one staging directory.
    /// 创建一个绑定到指定暂存目录的清理守卫。
    fn new(path: PathBuf) -> Self {
        Self {
            path,
            disarmed: false,
        }
    }

    /// Disable automatic cleanup for the current staging directory.
    /// 为当前暂存目录关闭自动清理。
    fn disarm(&mut self) {
        self.disarmed = true;
    }
}

impl Drop for TempDirGuard {
    /// Remove the staging directory best-effort when the guard is still armed.
    /// 当守卫仍处于激活状态时,尽力移除暂存目录。
    fn drop(&mut self) {
        if !self.disarmed && self.path.exists() {
            let _ = fs::remove_dir_all(&self.path);
        }
    }
}

impl SkillManager {
    /// Create one skill manager from a shared configuration object.
    /// 基于共享配置对象创建一个技能管理器实例。
    pub fn new(config: SkillManagerConfig) -> Self {
        Self { config }
    }

    /// Ensure the skill-state root and its child directories exist.
    /// 确保技能状态根目录及其子目录已经存在。
    pub fn ensure_state_layout(&self) -> Result<(), String> {
        fs::create_dir_all(self.disabled_root()).map_err(|error| {
            format!(
                "Failed to create disabled root {}: {}",
                self.disabled_root().display(),
                error
            )
        })?;
        fs::create_dir_all(self.install_record_root()).map_err(|error| {
            format!(
                "Failed to create install-record root {}: {}",
                self.install_record_root().display(),
                error
            )
        })
    }

    /// Validate one skill id and enforce the root-plane protection boundary.
    /// 校验单个 skill id 并执行根层级平面保护边界。
    pub fn guard_operation(
        &self,
        plane: SkillOperationPlane,
        action: SkillLifecycleAction,
        skill_id: &str,
    ) -> Result<(), String> {
        validate_luaskills_identifier(skill_id, "skill_id")?;
        if plane == SkillOperationPlane::Skills && is_root_skill_layer(&self.config.skill_root) {
            return Err(format!(
                "ROOT skill root is system-controlled and cannot be processed through the skills plane for action {:?}",
                action
            ));
        }
        Ok(())
    }

    /// Return whether one skill is currently enabled.
    /// 返回单个技能当前是否处于启用状态。
    pub fn is_skill_enabled(&self, skill_id: &str) -> Result<bool, String> {
        self.ensure_state_layout()?;
        Ok(!self.disabled_record_path(skill_id).exists())
    }

    /// Persist one disabled-state marker for the specified skill.
    /// 为指定技能持久化一份停用状态标记。
    pub fn disable_skill(&self, skill_id: &str, reason: Option<&str>) -> Result<(), String> {
        self.disable_skill_in_plane(SkillOperationPlane::Skills, skill_id, reason)
    }

    /// Persist one disabled-state marker for the specified skill in the requested operation plane.
    /// 在指定操作平面为目标技能持久化一份停用状态标记。
    pub fn disable_skill_in_plane(
        &self,
        plane: SkillOperationPlane,
        skill_id: &str,
        reason: Option<&str>,
    ) -> Result<(), String> {
        self.guard_operation(plane, SkillLifecycleAction::Disable, skill_id)?;
        self.ensure_state_layout()?;
        let record = DisabledSkillRecord {
            skill_id: skill_id.to_string(),
            reason: reason
                .map(|value| value.trim().to_string())
                .filter(|value| !value.is_empty()),
            disabled_at_unix_ms: SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap_or_default()
                .as_millis(),
        };
        let path = self.disabled_record_path(skill_id);
        let content = serde_json::to_string_pretty(&record)
            .map_err(|error| format!("Failed to serialize disabled record: {}", error))?;
        fs::write(&path, content)
            .map_err(|error| format!("Failed to write {}: {}", path.display(), error))
    }

    /// Remove the disabled-state marker for one skill.
    /// 删除单个技能的停用状态标记。
    pub fn enable_skill(&self, skill_id: &str) -> Result<(), String> {
        self.enable_skill_in_plane(SkillOperationPlane::Skills, skill_id)
    }

    /// Remove the disabled-state marker for one skill in the requested operation plane.
    /// 在指定操作平面移除单个技能的停用状态标记。
    pub fn enable_skill_in_plane(
        &self,
        plane: SkillOperationPlane,
        skill_id: &str,
    ) -> Result<(), String> {
        self.guard_operation(plane, SkillLifecycleAction::Enable, skill_id)?;
        self.ensure_state_layout()?;
        let path = self.disabled_record_path(skill_id);
        if path.exists() {
            fs::remove_file(&path)
                .map_err(|error| format!("Failed to remove {}: {}", path.display(), error))?;
        }
        Ok(())
    }

    /// Read the disabled-state record for one skill when it exists.
    /// 在停用状态记录存在时读取单个技能的停用状态记录。
    pub fn disabled_record(&self, skill_id: &str) -> Result<Option<DisabledSkillRecord>, String> {
        let path = self.disabled_record_path(skill_id);
        if !path.exists() {
            return Ok(None);
        }
        let content = fs::read_to_string(&path)
            .map_err(|error| format!("Failed to read {}: {}", path.display(), error))?;
        let record = serde_json::from_str::<DisabledSkillRecord>(&content)
            .map_err(|error| format!("Failed to parse {}: {}", path.display(), error))?;
        Ok(Some(record))
    }

    /// Remove one installed skill directory and clear its disabled marker.
    /// 删除单个已安装 skill 目录,并清理其停用标记。
    pub fn uninstall_skill(&self, skill_id: &str) -> Result<SkillUninstallResult, String> {
        self.uninstall_skill_in_plane(SkillOperationPlane::Skills, skill_id)
    }

    /// Remove one installed skill directory and clear its disabled marker in the requested operation plane.
    /// 在指定操作平面删除单个已安装技能目录,并清理其停用标记。
    pub fn uninstall_skill_in_plane(
        &self,
        plane: SkillOperationPlane,
        skill_id: &str,
    ) -> Result<SkillUninstallResult, String> {
        let skill_dir = self.config.skill_root.skills_dir.join(skill_id);
        let prepared =
            self.prepare_uninstall_skill_at_path_in_plane(plane, skill_id, &skill_dir)?;
        self.commit_prepared_skill_uninstall(&prepared)
            .map_err(|error| {
                let rollback_error = self.rollback_prepared_skill_uninstall(&prepared);
                let rollback_message = rollback_error
                    .err()
                    .map(|rollback| format!(" rollback failed: {}", rollback))
                    .unwrap_or_default();
                format!(
                    "Failed to finalize uninstall: {}.{}",
                    error, rollback_message
                )
            })
    }

    /// Remove one installed skill directory at an explicitly resolved path and clear its disabled marker.
    /// 删除单个已解析物理路径上的技能目录,并清理其停用标记。
    pub fn uninstall_skill_at_path_in_plane(
        &self,
        plane: SkillOperationPlane,
        skill_id: &str,
        skill_dir: &Path,
    ) -> Result<SkillUninstallResult, String> {
        let prepared = self.prepare_uninstall_skill_at_path_in_plane(plane, skill_id, skill_dir)?;
        self.commit_prepared_skill_uninstall(&prepared)
            .map_err(|error| {
                let rollback_error = self.rollback_prepared_skill_uninstall(&prepared);
                let rollback_message = rollback_error
                    .err()
                    .map(|rollback| format!(" rollback failed: {}", rollback))
                    .unwrap_or_default();
                format!(
                    "Failed to finalize uninstall: {}.{}",
                    error, rollback_message
                )
            })
    }

    /// Prepare one uninstall request and stage filesystem changes without committing state deletions yet.
    /// 预处理单个卸载请求并暂存文件系统变更,但暂不提交状态删除。
    pub fn prepare_uninstall_skill_at_path_in_plane(
        &self,
        plane: SkillOperationPlane,
        skill_id: &str,
        skill_dir: &Path,
    ) -> Result<PreparedSkillUninstall, String> {
        self.guard_operation(plane, SkillLifecycleAction::Uninstall, skill_id)?;
        self.ensure_state_layout()?;
        let previous_disabled_record = self.disabled_record(skill_id)?;
        let previous_install_record = self.install_record(skill_id)?;
        let (skill_removed, backup_dir) = if skill_dir.exists() {
            let backup_dir = self
                .config
                .lifecycle_root
                .join("uninstall_backup")
                .join(format!("{}-{}", skill_id, current_unix_millis()));
            if let Some(parent) = backup_dir.parent() {
                fs::create_dir_all(parent)
                    .map_err(|error| format!("Failed to create {}: {}", parent.display(), error))?;
            }
            fs::rename(skill_dir, &backup_dir).map_err(|error| {
                format!(
                    "Failed to move current skill {} into uninstall backup {}: {}",
                    skill_dir.display(),
                    backup_dir.display(),
                    error
                )
            })?;
            (true, Some(backup_dir))
        } else {
            (false, None)
        };
        Ok(PreparedSkillUninstall {
            result: SkillUninstallResult {
                skill_id: skill_id.to_string(),
                skill_removed,
                sqlite_removed: false,
                lancedb_removed: false,
                sqlite_retained: false,
                lancedb_retained: false,
                message: if skill_removed {
                    "skill package removed".to_string()
                } else {
                    "skill package directory not found".to_string()
                },
            },
            target_dir: skill_dir.to_path_buf(),
            backup_dir,
            previous_disabled_record,
            previous_install_record,
        })
    }

    /// Prepare one install request and stage filesystem changes without committing the install record yet.
    /// 预处理单个安装请求并暂存文件系统变更,但暂不提交安装记录。
    pub fn prepare_install_skill(
        &self,
        plane: SkillOperationPlane,
        skill_roots: &[RuntimeSkillRoot],
        request: &SkillInstallRequest,
    ) -> Result<PreparedSkillApply, String> {
        let skill_id = resolve_requested_skill_id(request)?;
        self.guard_operation(plane, SkillLifecycleAction::Install, &skill_id)?;
        if resolve_declared_skill_instance_from_roots(skill_roots, &skill_id)?.is_some() {
            return Ok(PreparedSkillApply::Immediate(SkillApplyResult {
                skill_id,
                status: "already_installed".to_string(),
                message: "skill already exists; use update to evaluate upgrade behavior"
                    .to_string(),
                version: None,
                source_type: None,
                source_locator: None,
            }));
        }
        match request.source_type {
            SkillInstallSourceType::Github => self.prepare_install_skill_from_github(&skill_id, request),
            SkillInstallSourceType::Url => Err(
                "managed URL install is not implemented yet; GitHub install is currently the only supported install source"
                    .to_string(),
            ),
        }
    }

    /// Prepare one update request and stage filesystem changes without committing the new install record yet.
    /// 预处理单个更新请求并暂存文件系统变更,但暂不提交新的安装记录。
    pub fn prepare_update_skill(
        &self,
        plane: SkillOperationPlane,
        skill_roots: &[RuntimeSkillRoot],
        request: &SkillInstallRequest,
    ) -> Result<PreparedSkillApply, String> {
        let skill_id = resolve_requested_skill_id(request)?;
        self.guard_operation(plane, SkillLifecycleAction::Update, &skill_id)?;
        if resolve_declared_skill_instance_from_roots(skill_roots, &skill_id)?.is_none() {
            return Ok(PreparedSkillApply::Immediate(SkillApplyResult {
                skill_id,
                status: "missing_skill".to_string(),
                message: "skill is not installed; use install first".to_string(),
                version: None,
                source_type: None,
                source_locator: None,
            }));
        }
        self.prepare_github_managed_skill_update(&skill_id)
    }

    /// Stage one skill package install from the latest GitHub release of the declared repository.
    /// 从声明仓库的最新 GitHub release 暂存单个技能包安装。
    fn prepare_install_skill_from_github(
        &self,
        skill_id: &str,
        request: &SkillInstallRequest,
    ) -> Result<PreparedSkillApply, String> {
        let repo = normalize_github_repo_locator(
            request
                .source
                .as_deref()
                .ok_or_else(|| "github install requires source repository".to_string())?,
        )?;
        let repo_skill_id = github_repo_skill_id(&repo)?;
        if repo_skill_id != skill_id {
            return Err(format!(
                "github repository '{}' resolves to skill_id '{}' but the request targets '{}'",
                repo, repo_skill_id, skill_id
            ));
        }

        let downloader = self.downloader();
        let asset = downloader.resolve_github_managed_skill_release_asset(
            &crate::skill::dependencies::GithubReleaseSourceSpec {
                repo: repo.clone(),
                tag_api: None,
            },
            skill_id,
            None,
        )?;
        let archive_path = downloader.download_with_sha256(
            &crate::download::manager::DownloadRequest {
                source_type: crate::dependency::types::DependencySourceType::GithubRelease,
                source_locator: asset.download_url.clone(),
                cache_key: managed_skill_cache_key(skill_id, asset.version.as_str()),
            },
            asset.sha256.as_deref().ok_or_else(|| {
                format!(
                    "GitHub release '{}' does not expose one SHA-256 checksum for '{}'",
                    asset.tag_name, asset.asset_name
                )
            })?,
        )?;

        let install_temp_root = self.config.lifecycle_root.join("install_tmp").join(format!(
            "{}-{}",
            skill_id,
            current_unix_millis()
        ));
        if install_temp_root.exists() {
            fs::remove_dir_all(&install_temp_root).map_err(|error| {
                format!(
                    "Failed to remove stale temp install root {}: {}",
                    install_temp_root.display(),
                    error
                )
            })?;
        }
        fs::create_dir_all(&install_temp_root).map_err(|error| {
            format!(
                "Failed to create temp install root {}: {}",
                install_temp_root.display(),
                error
            )
        })?;
        let mut install_temp_guard = TempDirGuard::new(install_temp_root.clone());

        let extracted_skill_dir =
            extract_skill_package_zip(&archive_path, &install_temp_root, skill_id)?;
        let installed_meta = read_skill_manifest_from_directory(&extracted_skill_dir)?;
        if installed_meta.effective_skill_id() != skill_id {
            return Err(format!(
                "downloaded skill package resolves to skill_id '{}' instead of '{}'",
                installed_meta.effective_skill_id(),
                skill_id
            ));
        }
        if installed_meta.version() != asset.version {
            return Err(format!(
                "downloaded skill package version '{}' does not match release version '{}'",
                installed_meta.version(),
                asset.version
            ));
        }

        let target_dir = self.skill_root().join(skill_id);
        if target_dir.exists() {
            return Err(format!(
                "target skill directory {} already exists",
                target_dir.display()
            ));
        }
        fs::rename(&extracted_skill_dir, &target_dir).map_err(|error| {
            format!(
                "Failed to move extracted skill {} into {}: {}",
                extracted_skill_dir.display(),
                target_dir.display(),
                error
            )
        })?;
        install_temp_guard.disarm();
        let _ = fs::remove_dir_all(&install_temp_root);

        let record = InstalledSkillRecord {
            skill_id: skill_id.to_string(),
            version: asset.version.clone(),
            managed: true,
            source: InstalledSkillSourceRecord {
                source_type: SkillInstallSourceType::Github,
                locator: repo.clone(),
                tag: Some(asset.tag_name.clone()),
            },
            installed_at_unix_ms: current_unix_millis(),
        };
        Ok(PreparedSkillApply::Install(PreparedSkillInstall {
            result: SkillApplyResult {
                skill_id: skill_id.to_string(),
                status: "installed".to_string(),
                message: format!(
                    "skill '{}' version {} was installed from GitHub repository '{}'",
                    skill_id, asset.version, repo
                ),
                version: Some(asset.version),
                source_type: Some(SkillInstallSourceType::Github),
                source_locator: Some(repo),
            },
            target_dir,
            install_record: record,
        }))
    }

    /// Stage one managed GitHub-installed skill update by comparing the latest release tag with the current installed version.
    /// 通过比较最新 release 标签与当前已安装版本来暂存单个 GitHub 受管技能更新。
    fn prepare_github_managed_skill_update(
        &self,
        skill_id: &str,
    ) -> Result<PreparedSkillApply, String> {
        let record = self
            .install_record(skill_id)?
            .ok_or_else(|| {
                format!(
                    "skill '{}' is not managed by the install workflow; automatic update is unavailable",
                    skill_id
                )
            })?;
        if !record.managed {
            return Err(format!(
                "skill '{}' is not managed by the install workflow; automatic update is unavailable",
                skill_id
            ));
        }
        if record.source.source_type != SkillInstallSourceType::Github {
            return Err(format!(
                "skill '{}' uses source type '{:?}', but update currently supports only github",
                skill_id, record.source.source_type
            ));
        }

        let current_version = Version::parse(record.version.as_str()).map_err(|error| {
            format!(
                "installed version '{}' of skill '{}' is invalid: {}",
                record.version, skill_id, error
            )
        })?;
        let downloader = self.downloader();
        let asset = downloader.resolve_github_managed_skill_release_asset(
            &crate::skill::dependencies::GithubReleaseSourceSpec {
                repo: record.source.locator.clone(),
                tag_api: None,
            },
            skill_id,
            None,
        )?;
        let latest_version = Version::parse(asset.version.as_str()).map_err(|error| {
            format!(
                "latest GitHub release version '{}' of skill '{}' is invalid: {}",
                asset.version, skill_id, error
            )
        })?;
        if latest_version <= current_version {
            return Ok(PreparedSkillApply::Immediate(SkillApplyResult {
                skill_id: skill_id.to_string(),
                status: "up_to_date".to_string(),
                message: format!(
                    "skill '{}' is already on version {}",
                    skill_id, record.version
                ),
                version: Some(record.version),
                source_type: Some(SkillInstallSourceType::Github),
                source_locator: Some(record.source.locator),
            }));
        }

        let archive_path = downloader.download_with_sha256(
            &crate::download::manager::DownloadRequest {
                source_type: crate::dependency::types::DependencySourceType::GithubRelease,
                source_locator: asset.download_url.clone(),
                cache_key: managed_skill_cache_key(skill_id, asset.version.as_str()),
            },
            asset.sha256.as_deref().ok_or_else(|| {
                format!(
                    "GitHub release '{}' does not expose one SHA-256 checksum for '{}'",
                    asset.tag_name, asset.asset_name
                )
            })?,
        )?;
        let temp_root = self.config.lifecycle_root.join("update_tmp").join(format!(
            "{}-{}",
            skill_id,
            current_unix_millis()
        ));
        if temp_root.exists() {
            fs::remove_dir_all(&temp_root).map_err(|error| {
                format!(
                    "Failed to remove stale temp update root {}: {}",
                    temp_root.display(),
                    error
                )
            })?;
        }
        fs::create_dir_all(&temp_root).map_err(|error| {
            format!(
                "Failed to create temp update root {}: {}",
                temp_root.display(),
                error
            )
        })?;
        let mut update_temp_guard = TempDirGuard::new(temp_root.clone());
        let extracted_skill_dir = extract_skill_package_zip(&archive_path, &temp_root, skill_id)?;
        let updated_meta = read_skill_manifest_from_directory(&extracted_skill_dir)?;
        if updated_meta.version() != asset.version {
            return Err(format!(
                "downloaded update package version '{}' does not match release version '{}'",
                updated_meta.version(),
                asset.version
            ));
        }

        let target_dir = self.skill_root().join(skill_id);
        if !target_dir.exists() {
            return Err(format!(
                "installed skill directory {} does not exist",
                target_dir.display()
            ));
        }
        let backup_dir = self
            .config
            .lifecycle_root
            .join("update_backup")
            .join(format!("{}-{}", skill_id, current_unix_millis()));
        if let Some(parent) = backup_dir.parent() {
            fs::create_dir_all(parent)
                .map_err(|error| format!("Failed to create {}: {}", parent.display(), error))?;
        }
        fs::rename(&target_dir, &backup_dir).map_err(|error| {
            format!(
                "Failed to move current skill {} into backup {}: {}",
                target_dir.display(),
                backup_dir.display(),
                error
            )
        })?;
        if let Err(error) = fs::rename(&extracted_skill_dir, &target_dir) {
            let _ = fs::rename(&backup_dir, &target_dir);
            return Err(format!(
                "Failed to move updated skill {} into {}: {}",
                extracted_skill_dir.display(),
                target_dir.display(),
                error
            ));
        }
        update_temp_guard.disarm();
        let _ = fs::remove_dir_all(&temp_root);

        let updated_record = InstalledSkillRecord {
            skill_id: skill_id.to_string(),
            version: asset.version.clone(),
            managed: true,
            source: InstalledSkillSourceRecord {
                source_type: SkillInstallSourceType::Github,
                locator: record.source.locator.clone(),
                tag: Some(asset.tag_name.clone()),
            },
            installed_at_unix_ms: current_unix_millis(),
        };
        Ok(PreparedSkillApply::Update(PreparedSkillUpdate {
            result: SkillApplyResult {
                skill_id: skill_id.to_string(),
                status: "updated".to_string(),
                message: format!(
                    "skill '{}' was updated from version {} to {}",
                    skill_id, record.version, asset.version
                ),
                version: Some(asset.version),
                source_type: Some(SkillInstallSourceType::Github),
                source_locator: Some(record.source.locator.clone()),
            },
            target_dir,
            backup_dir,
            install_record: updated_record,
            previous_install_record: record,
        }))
    }

    /// Return the configured installed skill root.
    /// 返回当前配置中的已安装技能根目录。
    pub fn skill_root(&self) -> &Path {
        &self.config.skill_root.skills_dir
    }

    /// Return the configured skill-state root.
    /// 返回当前配置中的技能状态根目录。
    pub fn state_root(&self) -> &Path {
        self.config.lifecycle_root.as_path()
    }

    /// Return the root directory used to store managed install records.
    /// 返回用于存放受管安装记录的根目录。
    fn install_record_root(&self) -> PathBuf {
        self.config.lifecycle_root.join("installs")
    }

    /// Return the root directory used to store disabled-state markers.
    /// 返回用于存放停用状态标记的根目录。
    fn disabled_root(&self) -> PathBuf {
        self.config.lifecycle_root.join("skills").join("disabled")
    }

    /// Return the JSON state file path used by one disabled skill.
    /// 返回单个已停用技能对应的 JSON 状态文件路径。
    fn disabled_record_path(&self, skill_id: &str) -> PathBuf {
        self.disabled_root().join(format!("{}.json", skill_id))
    }

    /// Return the YAML install-record path used by one managed skill.
    /// 返回单个受管技能使用的 YAML 安装记录路径。
    fn install_record_path(&self, skill_id: &str) -> PathBuf {
        self.install_record_root()
            .join(format!("{}.yaml", skill_id))
    }

    /// Read one managed install record from disk when it exists.
    /// 在受管安装记录存在时从磁盘读取该记录。
    pub fn install_record(&self, skill_id: &str) -> Result<Option<InstalledSkillRecord>, String> {
        validate_luaskills_identifier(skill_id, "skill_id")?;
        let path = self.install_record_path(skill_id);
        if !path.exists() {
            return Ok(None);
        }
        let yaml = fs::read_to_string(&path)
            .map_err(|error| format!("Failed to read {}: {}", path.display(), error))?;
        let record: InstalledSkillRecord = serde_yaml::from_str(&yaml)
            .map_err(|error| format!("Failed to parse {}: {}", path.display(), error))?;
        Ok(Some(record))
    }

    /// Persist one managed install record to disk.
    /// 将单个受管安装记录持久化到磁盘。
    fn persist_install_record(&self, record: &InstalledSkillRecord) -> Result<(), String> {
        self.ensure_state_layout()?;
        let path = self.install_record_path(&record.skill_id);
        let yaml = serde_yaml::to_string(record)
            .map_err(|error| format!("Failed to serialize install record: {}", error))?;
        fs::write(&path, yaml)
            .map_err(|error| format!("Failed to write {}: {}", path.display(), error))
    }

    /// Remove one managed install record from disk and report whether it existed.
    /// 从磁盘删除单个受管安装记录,并返回它是否存在。
    fn remove_install_record(&self, skill_id: &str) -> Result<bool, String> {
        validate_luaskills_identifier(skill_id, "skill_id")?;
        let path = self.install_record_path(skill_id);
        if !path.exists() {
            return Ok(false);
        }
        fs::remove_file(&path)
            .map_err(|error| format!("Failed to remove {}: {}", path.display(), error))?;
        Ok(true)
    }

    /// Persist one disabled-state record exactly as captured before a staged mutation.
    /// 按暂存变更前捕获的原样持久化单个停用状态记录。
    fn persist_disabled_record(&self, record: &DisabledSkillRecord) -> Result<(), String> {
        self.ensure_state_layout()?;
        let path = self.disabled_record_path(&record.skill_id);
        let content = serde_json::to_string_pretty(record)
            .map_err(|error| format!("Failed to serialize disabled record: {}", error))?;
        fs::write(&path, content)
            .map_err(|error| format!("Failed to write {}: {}", path.display(), error))
    }

    /// Remove one disabled-state record from disk and report whether it existed.
    /// 从磁盘删除单个停用状态记录,并返回它是否存在。
    fn remove_disabled_record(&self, skill_id: &str) -> Result<bool, String> {
        validate_luaskills_identifier(skill_id, "skill_id")?;
        self.ensure_state_layout()?;
        let path = self.disabled_record_path(skill_id);
        if !path.exists() {
            return Ok(false);
        }
        fs::remove_file(&path)
            .map_err(|error| format!("Failed to remove {}: {}", path.display(), error))?;
        Ok(true)
    }

    /// Restore one previous disabled-state snapshot or remove the current record when no snapshot existed.
    /// 恢复单个旧停用状态快照,若原先不存在快照则删除当前记录。
    fn restore_disabled_record(
        &self,
        skill_id: &str,
        record: Option<&DisabledSkillRecord>,
    ) -> Result<(), String> {
        match record {
            Some(record) => self.persist_disabled_record(record),
            None => {
                self.remove_disabled_record(skill_id)?;
                Ok(())
            }
        }
    }

    /// Restore one previous install-record snapshot or remove the current record when no snapshot existed.
    /// 恢复单个旧安装记录快照,若原先不存在快照则删除当前记录。
    fn restore_install_record(
        &self,
        skill_id: &str,
        record: Option<&InstalledSkillRecord>,
    ) -> Result<(), String> {
        match record {
            Some(record) => self.persist_install_record(record),
            None => {
                self.remove_install_record(skill_id)?;
                Ok(())
            }
        }
    }

    /// Persist the final install record and remove transitional backup data after runtime reload succeeds.
    /// 在运行时重载成功后持久化最终安装记录,并移除过渡备份数据。
    pub fn commit_prepared_skill_apply(
        &self,
        prepared: &PreparedSkillApply,
    ) -> Result<SkillApplyResult, String> {
        match prepared {
            PreparedSkillApply::Immediate(result) => Ok(result.clone()),
            PreparedSkillApply::Install(prepared_install) => {
                self.persist_install_record(&prepared_install.install_record)?;
                Ok(prepared_install.result.clone())
            }
            PreparedSkillApply::Update(prepared_update) => {
                self.persist_install_record(&prepared_update.install_record)?;
                if prepared_update.backup_dir.exists() {
                    fs::remove_dir_all(&prepared_update.backup_dir).map_err(|error| {
                        let restore_error =
                            self.persist_install_record(&prepared_update.previous_install_record);
                        match restore_error {
                            Ok(()) => format!(
                                "Failed to remove update backup {}: previous install record was restored: {}",
                                prepared_update.backup_dir.display(),
                                error
                            ),
                            Err(restore_error) => format!(
                                "Failed to remove update backup {}: {}. Failed to restore previous install record: {}",
                                prepared_update.backup_dir.display(),
                                error,
                                restore_error
                            ),
                        }
                    })?;
                }
                Ok(prepared_update.result.clone())
            }
        }
    }

    /// Roll back one staged install/update mutation after reload or commit fails.
    /// 在重载或提交失败后回滚一次已暂存的安装或更新变更。
    pub fn rollback_prepared_skill_apply(
        &self,
        prepared: &PreparedSkillApply,
    ) -> Result<(), String> {
        match prepared {
            PreparedSkillApply::Immediate(_) => Ok(()),
            PreparedSkillApply::Install(prepared_install) => {
                if prepared_install.target_dir.exists() {
                    fs::remove_dir_all(&prepared_install.target_dir).map_err(|error| {
                        format!(
                            "Failed to roll back installed skill directory {}: {}",
                            prepared_install.target_dir.display(),
                            error
                        )
                    })?;
                }
                Ok(())
            }
            PreparedSkillApply::Update(prepared_update) => {
                if prepared_update.target_dir.exists() {
                    fs::remove_dir_all(&prepared_update.target_dir).map_err(|error| {
                        format!(
                            "Failed to remove staged updated skill directory {}: {}",
                            prepared_update.target_dir.display(),
                            error
                        )
                    })?;
                }
                if prepared_update.backup_dir.exists() {
                    fs::rename(&prepared_update.backup_dir, &prepared_update.target_dir).map_err(
                        |error| {
                            format!(
                                "Failed to restore backup {} into {}: {}",
                                prepared_update.backup_dir.display(),
                                prepared_update.target_dir.display(),
                                error
                            )
                        },
                    )?;
                }
                Ok(())
            }
        }
    }

    /// Persist the final uninstall state and remove transitional backup data after runtime reload succeeds.
    /// 在运行时重载成功后持久化最终卸载状态,并移除过渡备份数据。
    pub fn commit_prepared_skill_uninstall(
        &self,
        prepared: &PreparedSkillUninstall,
    ) -> Result<SkillUninstallResult, String> {
        if prepared.previous_disabled_record.is_some() {
            self.remove_disabled_record(&prepared.result.skill_id)?;
        }
        if prepared.previous_install_record.is_some() {
            self.remove_install_record(&prepared.result.skill_id)?;
        }
        if let Some(backup_dir) = &prepared.backup_dir {
            fs::remove_dir_all(backup_dir).map_err(|error| {
                let disabled_restore_error = self.restore_disabled_record(
                    &prepared.result.skill_id,
                    prepared.previous_disabled_record.as_ref(),
                );
                let install_restore_error = self.restore_install_record(
                    &prepared.result.skill_id,
                    prepared.previous_install_record.as_ref(),
                );
                let mut message = format!(
                    "Failed to remove uninstall backup {}: {}",
                    backup_dir.display(),
                    error
                );
                if let Err(restore_error) = disabled_restore_error {
                    message.push_str(&format!(
                        ". Failed to restore previous disabled record: {}",
                        restore_error
                    ));
                }
                if let Err(restore_error) = install_restore_error {
                    message.push_str(&format!(
                        ". Failed to restore previous install record: {}",
                        restore_error
                    ));
                }
                message
            })?;
        }
        Ok(prepared.result.clone())
    }

    /// Roll back one staged uninstall mutation after reload or commit fails.
    /// 在重载或提交失败后回滚一次已暂存的卸载变更。
    pub fn rollback_prepared_skill_uninstall(
        &self,
        prepared: &PreparedSkillUninstall,
    ) -> Result<(), String> {
        if let Some(backup_dir) = &prepared.backup_dir {
            if prepared.target_dir.exists() {
                fs::remove_dir_all(&prepared.target_dir).map_err(|error| {
                    format!(
                        "Failed to remove staged uninstall target directory {}: {}",
                        prepared.target_dir.display(),
                        error
                    )
                })?;
            }
            if backup_dir.exists() {
                fs::rename(backup_dir, &prepared.target_dir).map_err(|error| {
                    format!(
                        "Failed to restore uninstall backup {} into {}: {}",
                        backup_dir.display(),
                        prepared.target_dir.display(),
                        error
                    )
                })?;
            }
        }
        self.restore_disabled_record(
            &prepared.result.skill_id,
            prepared.previous_disabled_record.as_ref(),
        )?;
        self.restore_install_record(
            &prepared.result.skill_id,
            prepared.previous_install_record.as_ref(),
        )?;
        Ok(())
    }

    /// Build one downloader configured for managed install and update flows.
    /// 为受管安装与更新流程构造单个下载器。
    fn downloader(&self) -> DownloadManager {
        DownloadManager::new(DownloadManagerConfig {
            cache_root: self.config.download_cache_root.clone(),
            allow_network_download: self.config.allow_network_download,
            github_base_url: self.config.github_base_url.clone(),
            github_api_base_url: self.config.github_api_base_url.clone(),
        })
    }
}

/// Return whether one runtime skill root represents the system-controlled ROOT layer.
/// 返回单个运行时技能根是否代表系统控制的 ROOT 层。
fn is_root_skill_layer(root: &RuntimeSkillRoot) -> bool {
    root.name.trim().eq_ignore_ascii_case("ROOT")
}

/// Resolve the effective request skill id, deriving it from the source locator when needed.
/// 解析当前请求的生效技能标识符,并在需要时从来源定位值派生。
pub(crate) fn resolve_requested_skill_id(request: &SkillInstallRequest) -> Result<String, String> {
    let explicit_skill_id = request
        .skill_id
        .as_deref()
        .map(str::trim)
        .filter(|value| !value.is_empty())
        .map(ToOwned::to_owned);
    let derived_skill_id = match request.source_type {
        SkillInstallSourceType::Github => request
            .source
            .as_deref()
            .map(normalize_github_repo_locator)
            .transpose()?
            .map(|repo| github_repo_skill_id(&repo))
            .transpose()?,
        SkillInstallSourceType::Url => None,
    };
    let skill_id = explicit_skill_id.or(derived_skill_id).ok_or_else(|| {
        "install/update request requires skill_id or one source that can derive it".to_string()
    })?;
    validate_luaskills_identifier(&skill_id, "skill_id")?;
    Ok(skill_id)
}

/// Normalize one GitHub repository locator into `owner/repo` form.
/// 将单个 GitHub 仓库定位值规范化为 `owner/repo` 形式。
fn normalize_github_repo_locator(source: &str) -> Result<String, String> {
    let normalized = source
        .trim()
        .trim_start_matches("https://github.com/")
        .trim_start_matches("http://github.com/")
        .trim_matches('/')
        .to_string();
    let mut segments = normalized.split('/');
    let owner = segments.next().unwrap_or_default().trim();
    let repo = segments.next().unwrap_or_default().trim();
    if owner.is_empty() || repo.is_empty() || segments.next().is_some() {
        return Err(format!(
            "github source '{}' must be one repository locator in owner/repo form",
            source
        ));
    }
    Ok(format!("{}/{}", owner, repo))
}

/// Derive one skill id from the repository segment of a GitHub locator.
/// 从 GitHub 定位值的仓库段派生单个技能标识符。
fn github_repo_skill_id(repo: &str) -> Result<String, String> {
    let skill_id = repo
        .rsplit('/')
        .next()
        .unwrap_or_default()
        .trim()
        .to_string();
    validate_luaskills_identifier(&skill_id, "derived github skill_id")?;
    Ok(skill_id)
}

/// Build one stable download-cache key for a managed skill package.
/// 为受管技能包构造单个稳定的下载缓存键。
fn managed_skill_cache_key(skill_id: &str, version: &str) -> String {
    format!("skill-{}-{}", skill_id, version)
}

/// Return the current Unix timestamp in milliseconds.
/// 返回当前 Unix 毫秒时间戳。
fn current_unix_millis() -> u128 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_millis()
}

/// Read one extracted skill manifest from disk and bind the directory-derived skill id.
/// 从磁盘读取单个已解包技能清单,并绑定从目录派生的技能标识符。
fn read_skill_manifest_from_directory(skill_dir: &Path) -> Result<SkillMeta, String> {
    let skill_id = skill_dir
        .file_name()
        .and_then(|value| value.to_str())
        .ok_or_else(|| {
            format!(
                "Failed to resolve skill id from directory {}",
                skill_dir.display()
            )
        })?
        .trim()
        .to_string();
    validate_luaskills_identifier(&skill_id, "skill_id")?;
    let skill_yaml_path = skill_dir.join("skill.yaml");
    let yaml_text = fs::read_to_string(&skill_yaml_path)
        .map_err(|error| format!("Failed to read {}: {}", skill_yaml_path.display(), error))?;
    let yaml_value: serde_yaml::Value = serde_yaml::from_str(&yaml_text)
        .map_err(|error| format!("Failed to parse {}: {}", skill_yaml_path.display(), error))?;
    if yaml_value
        .as_mapping()
        .and_then(|mapping| mapping.get(serde_yaml::Value::String("skill_id".to_string())))
        .is_some()
    {
        return Err(format!(
            "skill {} must not declare skill_id in skill.yaml; directory name is the only skill_id",
            skill_dir.display()
        ));
    }
    let mut meta: SkillMeta = serde_yaml::from_value(yaml_value)
        .map_err(|error| format!("Failed to decode {}: {}", skill_yaml_path.display(), error))?;
    meta.bind_directory_skill_id(skill_id.clone());
    validate_luaskills_version(meta.version(), "skill.yaml version")?;
    if meta.effective_skill_id() != skill_id {
        return Err(format!(
            "skill manifest in {} resolved to skill_id '{}' instead of '{}'",
            skill_yaml_path.display(),
            meta.effective_skill_id(),
            skill_id
        ));
    }
    Ok(meta)
}

/// Resolve the currently effective skill directories after applying override precedence and empty-directory disable semantics.
/// 在应用 override 优先级与空目录禁用语义后解析当前实际生效的技能目录集合。
pub fn collect_effective_skill_instances(
    base_dir: &Path,
    override_dir: Option<&Path>,
) -> Result<Vec<ResolvedSkillInstance>, String> {
    let mut roots = vec![RuntimeSkillRoot {
        name: "ROOT".to_string(),
        skills_dir: base_dir.to_path_buf(),
    }];
    if let Some(override_dir) = override_dir {
        roots.push(RuntimeSkillRoot {
            name: "PROJECT".to_string(),
            skills_dir: override_dir.to_path_buf(),
        });
    }
    collect_effective_skill_instances_from_roots(&roots)
}

/// Resolve the currently effective skill directories after applying ordered root precedence rules.
/// 在应用有序根目录优先级规则后解析当前实际生效的技能目录集合。
pub fn collect_effective_skill_instances_from_roots(
    roots: &[RuntimeSkillRoot],
) -> Result<Vec<ResolvedSkillInstance>, String> {
    let mut all_skill_ids = BTreeSet::new();
    let mut root_maps = Vec::new();
    for root in roots {
        let root_map = collect_named_skill_dirs(&root.skills_dir)?;
        all_skill_ids.extend(root_map.keys().cloned());
        root_maps.push((root.clone(), root_map));
    }

    let mut resolved = Vec::new();
    for skill_id in all_skill_ids {
        for (root, root_map) in &root_maps {
            let Some(skill_dir) = root_map.get(&skill_id) else {
                continue;
            };
            if is_effective_disable_override(skill_dir)? {
                break;
            }
            if !is_skill_manifest_enabled(skill_dir)? {
                break;
            }
            resolved.push(ResolvedSkillInstance {
                skill_id: skill_id.clone(),
                root_name: root.name.clone(),
                skills_root: root.skills_dir.clone(),
                actual_dir: skill_dir.clone(),
            });
            break;
        }
    }
    Ok(resolved)
}

/// Resolve one effective skill instance by skill id after applying root precedence.
/// 在应用根目录优先级后按技能标识符解析单个生效技能实例。
pub fn resolve_effective_skill_instance(
    base_dir: &Path,
    override_dir: Option<&Path>,
    skill_id: &str,
) -> Result<Option<ResolvedSkillInstance>, String> {
    validate_luaskills_identifier(skill_id, "skill_id")?;
    Ok(collect_effective_skill_instances(base_dir, override_dir)?
        .into_iter()
        .find(|instance| instance.skill_id == skill_id))
}

/// Resolve one effective skill instance by skill id from an ordered root chain.
/// 从有序根目录覆盖链中按技能标识符解析单个生效技能实例。
pub fn resolve_effective_skill_instance_from_roots(
    roots: &[RuntimeSkillRoot],
    skill_id: &str,
) -> Result<Option<ResolvedSkillInstance>, String> {
    validate_luaskills_identifier(skill_id, "skill_id")?;
    Ok(collect_effective_skill_instances_from_roots(roots)?
        .into_iter()
        .find(|instance| instance.skill_id == skill_id))
}

/// Resolve the highest-priority declared skill directory by skill id without applying enable-state filtering.
/// 在不应用启用状态过滤的前提下,按技能标识符解析最高优先级的已声明技能目录。
pub fn resolve_declared_skill_instance_from_roots(
    roots: &[RuntimeSkillRoot],
    skill_id: &str,
) -> Result<Option<ResolvedSkillInstance>, String> {
    validate_luaskills_identifier(skill_id, "skill_id")?;
    for root in roots {
        let root_map = collect_named_skill_dirs(&root.skills_dir)?;
        if let Some(actual_dir) = root_map.get(skill_id) {
            return Ok(Some(ResolvedSkillInstance {
                skill_id: skill_id.to_string(),
                root_name: root.name.clone(),
                skills_root: root.skills_dir.clone(),
                actual_dir: actual_dir.clone(),
            }));
        }
    }
    Ok(None)
}

/// Read one root directory into a validated skill-id -> path map.
/// 把单个根目录读取为经过校验的 skill-id -> 路径映射。
fn collect_named_skill_dirs(
    root: &Path,
) -> Result<std::collections::BTreeMap<String, PathBuf>, String> {
    let mut output = std::collections::BTreeMap::new();
    if !root.exists() {
        return Ok(output);
    }
    for entry in fs::read_dir(root)
        .map_err(|error| format!("Failed to read {}: {}", root.display(), error))?
    {
        let entry = entry.map_err(|error| format!("Failed to read skill entry: {}", error))?;
        let file_type = entry
            .file_type()
            .map_err(|error| format!("Failed to inspect skill entry type: {}", error))?;
        if !file_type.is_dir() {
            continue;
        }
        let skill_id = match entry.file_name().to_str() {
            Some(value) => value.to_string(),
            None => continue,
        };
        if validate_luaskills_identifier(&skill_id, "skill_id").is_err() {
            continue;
        }
        output.insert(skill_id, entry.path());
    }
    Ok(output)
}

/// Return whether one override skill directory should disable lower-priority instances because it is intentionally empty.
/// 返回单个 override 技能目录是否因为有意留空而应禁用更低优先级实例。
fn is_effective_disable_override(skill_dir: &Path) -> Result<bool, String> {
    Ok(fs::read_dir(skill_dir)
        .map_err(|error| {
            format!(
                "Failed to read override dir {}: {}",
                skill_dir.display(),
                error
            )
        })?
        .next()
        .is_none())
}

/// Return whether one resolved skill directory is enabled by its manifest.
/// 返回单个已解析技能目录是否在其清单中启用。
fn is_skill_manifest_enabled(skill_dir: &Path) -> Result<bool, String> {
    let skill_yaml = skill_dir.join("skill.yaml");
    if !skill_yaml.exists() {
        return Ok(true);
    }
    let yaml_text = fs::read_to_string(&skill_yaml)
        .map_err(|error| format!("Failed to read {}: {}", skill_yaml.display(), error))?;
    let yaml_value: serde_yaml::Value = serde_yaml::from_str(&yaml_text)
        .map_err(|error| format!("Failed to parse {}: {}", skill_yaml.display(), error))?;
    if yaml_value.as_mapping().is_some_and(|mapping| {
        mapping.contains_key(serde_yaml::Value::String("skill_id".to_string()))
    }) {
        return Err(format!(
            "skill manifest {} must not declare skill_id; directory name is the only skill_id",
            skill_yaml.display()
        ));
    }
    #[derive(Debug, Deserialize)]
    struct SkillEnableProbe {
        /// When omitted the skill is treated as enabled.
        /// 省略时表示技能默认启用。
        #[serde(default = "default_skill_enable")]
        enable: bool,
    }
    /// Return the default enable flag used by lightweight manifest probes.
    /// 返回轻量清单探针使用的默认启用标记。
    fn default_skill_enable() -> bool {
        true
    }
    let probe: SkillEnableProbe = serde_yaml::from_value(yaml_value)
        .map_err(|error| format!("Failed to parse {}: {}", skill_yaml.display(), error))?;
    Ok(probe.enable)
}

#[cfg(test)]
mod tests {
    use super::{
        SkillInstallRequest, SkillInstallSourceType, SkillManager, SkillManagerConfig,
        SkillOperationPlane, TempDirGuard, collect_effective_skill_instances,
        resolve_effective_skill_instance,
    };
    use crate::runtime_options::RuntimeSkillRoot;

    /// Build one test skill-manager configuration rooted under the provided temporary directory.
    /// 基于给定临时目录构造单个测试用技能管理器配置。
    fn test_manager_config(
        temp_root: &std::path::Path,
        skill_root: RuntimeSkillRoot,
    ) -> SkillManagerConfig {
        SkillManagerConfig {
            skill_root,
            lifecycle_root: temp_root.join("state"),
            download_cache_root: temp_root.join("downloads"),
            allow_network_download: false,
            github_base_url: None,
            github_api_base_url: None,
        }
    }

    /// Verify that the staging-directory guard cleans temp roots on drop.
    /// 验证暂存目录守卫会在析构时清理临时根目录。
    #[test]
    fn temp_dir_guard_removes_staging_root_on_drop() {
        let temp_root =
            std::env::temp_dir().join(format!("luaskills_temp_guard_test_{}", std::process::id()));
        if temp_root.exists() {
            let _ = std::fs::remove_dir_all(&temp_root);
        }
        std::fs::create_dir_all(&temp_root).expect("temp root should be created");
        {
            let _guard = TempDirGuard::new(temp_root.clone());
            std::fs::write(temp_root.join("staged.txt"), "staged")
                .expect("staged marker should be written");
        }
        assert!(!temp_root.exists());
    }

    /// Verify that disable/enable operations persist and clear state markers correctly.
    /// 验证停用/启用操作会正确持久化并清理状态标记。
    #[test]
    fn skill_manager_persists_disabled_state() {
        let temp_root = std::env::temp_dir().join(format!(
            "luaskills_skill_manager_test_{}",
            std::process::id()
        ));
        if temp_root.exists() {
            let _ = std::fs::remove_dir_all(&temp_root);
        }
        let skill_root = temp_root.join("skills");
        let manager = SkillManager::new(SkillManagerConfig {
            ..test_manager_config(
                &temp_root,
                RuntimeSkillRoot {
                    name: "USER".to_string(),
                    skills_dir: skill_root,
                },
            )
        });

        assert!(manager.is_skill_enabled("vulcan-codekit").unwrap());
        manager
            .disable_skill("vulcan-codekit", Some("manual test"))
            .expect("disable should succeed");
        assert!(!manager.is_skill_enabled("vulcan-codekit").unwrap());
        assert_eq!(
            manager
                .disabled_record("vulcan-codekit")
                .unwrap()
                .expect("record should exist")
                .reason
                .as_deref(),
            Some("manual test")
        );

        manager
            .enable_skill("vulcan-codekit")
            .expect("enable should succeed");
        assert!(manager.is_skill_enabled("vulcan-codekit").unwrap());

        let _ = std::fs::remove_dir_all(&temp_root);
    }

    /// Verify that install/update entrypoints return strict structured states before networking succeeds.
    /// 验证 install/update 入口在真正下载前会返回严格的结构化状态。
    #[test]
    fn install_update_entrypoints_return_strict_structured_results() {
        let temp_root = std::env::temp_dir().join(format!(
            "luaskills_install_update_test_{}",
            std::process::id()
        ));
        let skill_root = temp_root.join("skills");
        let skill_roots = vec![RuntimeSkillRoot {
            name: "USER".to_string(),
            skills_dir: skill_root.clone(),
        }];
        let _ = std::fs::create_dir_all(&skill_root);
        let manager = SkillManager::new(test_manager_config(&temp_root, skill_roots[0].clone()));

        let install_result = manager
            .prepare_install_skill(
                SkillOperationPlane::Skills,
                &skill_roots,
                &SkillInstallRequest {
                    skill_id: Some("vulcan-codekit".to_string()),
                    source: None,
                    source_type: SkillInstallSourceType::Github,
                },
            )
            .expect_err("install without source should fail strictly");
        assert!(install_result.contains("github install requires source repository"));

        let _ = std::fs::create_dir_all(skill_root.join("vulcan-codekit"));
        let update_result = manager
            .prepare_update_skill(
                SkillOperationPlane::Skills,
                &skill_roots,
                &SkillInstallRequest {
                    skill_id: Some("vulcan-codekit".to_string()),
                    source: None,
                    source_type: SkillInstallSourceType::Github,
                },
            )
            .expect_err("update without install record should fail strictly");
        assert!(update_result.contains("is not managed by the install workflow"));

        let _ = std::fs::remove_dir_all(&temp_root);
    }

    /// Verify that uninstall removes the skill directory but keeps database flags unset by default.
    /// 验证卸载会删除技能目录,同时默认不声明数据库已删除。
    #[test]
    fn uninstall_returns_safe_default_database_flags() {
        let temp_root = std::env::temp_dir().join(format!(
            "luaskills_uninstall_result_test_{}",
            std::process::id()
        ));
        if temp_root.exists() {
            let _ = std::fs::remove_dir_all(&temp_root);
        }
        let skill_root = temp_root.join("skills");
        let manager = SkillManager::new(test_manager_config(
            &temp_root,
            RuntimeSkillRoot {
                name: "USER".to_string(),
                skills_dir: skill_root.clone(),
            },
        ));
        let _ = std::fs::create_dir_all(skill_root.join("vulcan-codekit"));

        let result = manager
            .uninstall_skill("vulcan-codekit")
            .expect("uninstall should succeed");
        assert!(result.skill_removed);
        assert!(!result.sqlite_removed);
        assert!(!result.lancedb_removed);
        assert!(!skill_root.join("vulcan-codekit").exists());

        let _ = std::fs::remove_dir_all(&temp_root);
    }

    /// Verify that PROJECT roots can contribute standalone skills without shadowing ROOT skills.
    /// 验证 PROJECT 根目录可以独立提供技能,但不能覆盖 ROOT 技能。
    #[test]
    fn collect_effective_skill_instances_keeps_root_priority_over_project() {
        let temp_root = std::env::temp_dir().join(format!(
            "luaskills_collect_effective_instances_test_{}",
            std::process::id()
        ));
        if temp_root.exists() {
            let _ = std::fs::remove_dir_all(&temp_root);
        }
        let base_dir = temp_root.join("base");
        let override_dir = temp_root.join("override");
        let _ = std::fs::create_dir_all(base_dir.join("vulcan-codekit"));
        let _ = std::fs::create_dir_all(override_dir.join("vulcan-codekit"));
        let _ = std::fs::create_dir_all(override_dir.join("vulcan-runtime"));
        let _ = std::fs::write(
            base_dir.join("vulcan-codekit").join("skill.yaml"),
            "name: vulcan-codekit\nversion: 0.1.0\n",
        );
        let _ = std::fs::write(
            override_dir.join("vulcan-codekit").join("skill.yaml"),
            "name: vulcan-codekit\nversion: 0.2.0\n",
        );
        let _ = std::fs::write(
            override_dir.join("vulcan-runtime").join("skill.yaml"),
            "name: vulcan-runtime\nversion: 0.1.0\n",
        );

        let resolved = collect_effective_skill_instances(&base_dir, Some(&override_dir))
            .expect("effective skill collection should succeed");
        assert_eq!(resolved.len(), 2);
        let codekit = resolved
            .iter()
            .find(|value| value.skill_id == "vulcan-codekit")
            .expect("vulcan-codekit should exist");
        assert!(codekit.actual_dir.starts_with(&base_dir));
        let runtime = resolved
            .iter()
            .find(|value| value.skill_id == "vulcan-runtime")
            .expect("project-only vulcan-runtime should exist");
        assert!(runtime.actual_dir.starts_with(&override_dir));

        let _ = std::fs::remove_dir_all(&temp_root);
    }

    /// Verify that resolving one effective skill instance keeps ROOT ahead of PROJECT.
    /// 验证解析单个生效技能实例时会保持 ROOT 高于 PROJECT。
    #[test]
    fn resolve_effective_skill_instance_prefers_root_directory() {
        let temp_root = std::env::temp_dir().join(format!(
            "luaskills_resolve_effective_instance_test_{}",
            std::process::id()
        ));
        if temp_root.exists() {
            let _ = std::fs::remove_dir_all(&temp_root);
        }
        let base_dir = temp_root.join("base");
        let override_dir = temp_root.join("override");
        let _ = std::fs::create_dir_all(base_dir.join("vulcan-codekit"));
        let _ = std::fs::create_dir_all(override_dir.join("vulcan-codekit"));
        let _ = std::fs::write(
            base_dir.join("vulcan-codekit").join("skill.yaml"),
            "name: vulcan-codekit\nversion: 0.1.0\n",
        );
        let _ = std::fs::write(
            override_dir.join("vulcan-codekit").join("skill.yaml"),
            "name: vulcan-codekit\nversion: 0.2.0\n",
        );

        let resolved =
            resolve_effective_skill_instance(&base_dir, Some(&override_dir), "vulcan-codekit")
                .expect("resolution should succeed")
                .expect("instance should exist");
        assert!(resolved.actual_dir.starts_with(&base_dir));

        let _ = std::fs::remove_dir_all(&temp_root);
    }
}