-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathdefault_skill_seeder.cpp
More file actions
1517 lines (1391 loc) · 51 KB
/
Copy pathdefault_skill_seeder.cpp
File metadata and controls
1517 lines (1391 loc) · 51 KB
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
#include "default_skill_seeder.hpp"
#include "../utils/atomic_file.hpp"
#include "../utils/logger.hpp"
#include "../utils/sha256.hpp"
#include "../utils/utf8_path.hpp"
#include <nlohmann/json.hpp>
#include <algorithm>
#include <array>
#include <cerrno>
#include <charconv>
#include <cstdint>
#include <cstdlib>
#include <ctime>
#include <filesystem>
#include <fstream>
#include <iomanip>
#include <mutex>
#include <optional>
#include <sstream>
#include <stdexcept>
#include <string_view>
#include <system_error>
#include <unordered_map>
#include <utility>
#include <vector>
#ifdef _WIN32
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# endif
# include <windows.h>
#else
# include <fcntl.h>
# include <sys/file.h>
# include <sys/stat.h>
# include <unistd.h>
#endif
namespace fs = std::filesystem;
namespace acecode {
namespace {
constexpr const char* kSeedStateFile = ".seed_skills_state.json";
constexpr const char* kSeedVersionFile = "seed.version";
constexpr const char* kSeedUpdateLockFile = ".seed_skills_update.lock";
constexpr const char* kSeedStagingDir = ".seed_skills_staging";
constexpr const char* kSeedBackupDir = ".seed_skills_backup";
constexpr std::size_t kMaxSeedVersionBytes = 128;
struct ParsedSeedVersion {
std::string text;
std::string date;
std::uint64_t revision = 0;
};
struct PreviousSeedState {
std::string result;
std::string installed_tree_sha256;
std::string skill_md_hash;
bool acecode_owned = false;
};
struct PreviousSeedStates {
std::unordered_map<std::string, PreviousSeedState> skills;
std::unordered_map<std::string, PreviousSeedState> experts;
std::unordered_map<std::string, PreviousSeedState> hooks;
};
std::mutex g_seed_reconciliation_mutex;
void append_error(DefaultSkillSeedInstallResult& result,
const std::string& message) {
if (message.empty()) return;
if (!result.error.empty()) result.error += "; ";
result.error += message;
}
std::string trim_ascii(std::string value) {
auto is_space = [](unsigned char ch) {
return ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n';
};
while (!value.empty() &&
is_space(static_cast<unsigned char>(value.front()))) {
value.erase(value.begin());
}
while (!value.empty() &&
is_space(static_cast<unsigned char>(value.back()))) {
value.pop_back();
}
return value;
}
template <typename Integer>
bool parse_decimal(std::string_view text, Integer& value) {
if (text.empty()) return false;
for (char ch : text) {
if (ch < '0' || ch > '9') return false;
}
const char* begin = text.data();
const char* end = begin + text.size();
auto parsed = std::from_chars(begin, end, value);
return parsed.ec == std::errc{} && parsed.ptr == end;
}
bool is_leap_year(unsigned year) {
return year % 400u == 0u || (year % 4u == 0u && year % 100u != 0u);
}
std::optional<ParsedSeedVersion> parse_seed_version(std::string text) {
text = trim_ascii(std::move(text));
if (text.size() < 12 || text[4] != '-' || text[7] != '-' ||
text[10] != '.') {
return std::nullopt;
}
unsigned year = 0;
unsigned month = 0;
unsigned day = 0;
std::uint64_t revision = 0;
if (!parse_decimal<unsigned>(std::string_view(text).substr(0, 4), year) ||
!parse_decimal<unsigned>(std::string_view(text).substr(5, 2), month) ||
!parse_decimal<unsigned>(std::string_view(text).substr(8, 2), day) ||
!parse_decimal<std::uint64_t>(
std::string_view(text).substr(11), revision)) {
return std::nullopt;
}
static constexpr std::array<unsigned, 12> kDaysPerMonth = {
31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31,
};
if (month == 0 || month > kDaysPerMonth.size()) return std::nullopt;
unsigned max_day = kDaysPerMonth[month - 1];
if (month == 2 && is_leap_year(year)) max_day = 29;
if (day == 0 || day > max_day) return std::nullopt;
return ParsedSeedVersion{
text,
text.substr(0, 10),
revision,
};
}
int compare_seed_versions(const ParsedSeedVersion& lhs,
const ParsedSeedVersion& rhs) {
if (lhs.date < rhs.date) return -1;
if (lhs.date > rhs.date) return 1;
if (lhs.revision < rhs.revision) return -1;
if (lhs.revision > rhs.revision) return 1;
return 0;
}
std::optional<std::string> read_small_text_file(const fs::path& path,
std::string& error) {
std::ifstream ifs(path, std::ios::binary);
if (!ifs.is_open()) {
error = "failed to open " + path_to_utf8_generic(path);
return std::nullopt;
}
std::array<char, kMaxSeedVersionBytes + 1> buffer{};
ifs.read(buffer.data(), static_cast<std::streamsize>(buffer.size()));
const std::streamsize count = ifs.gcount();
if (count > static_cast<std::streamsize>(kMaxSeedVersionBytes)) {
error = "file is too large: " + path_to_utf8_generic(path);
return std::nullopt;
}
if (ifs.bad()) {
error = "failed to read " + path_to_utf8_generic(path);
return std::nullopt;
}
return std::string(buffer.data(), static_cast<std::size_t>(count));
}
std::optional<ParsedSeedVersion> read_seed_version(const fs::path& path,
std::string& error) {
auto text = read_small_text_file(path, error);
if (!text) return std::nullopt;
auto parsed = parse_seed_version(std::move(*text));
if (!parsed) {
error = "invalid seed version in " + path_to_utf8_generic(path);
}
return parsed;
}
bool seed_dir_has_all_resources(const fs::path& skills_dir) {
std::error_code ec;
if (!fs::is_directory(skills_dir, ec)) return false;
for (const auto& seed : default_skill_seeds()) {
if (!fs::is_regular_file(
skills_dir / seed.relative_path / "SKILL.md", ec)) {
return false;
}
}
const fs::path experts_dir = skills_dir.parent_path() / "experts";
if (!fs::is_directory(experts_dir, ec)) return false;
for (const auto& seed : default_expert_seeds()) {
if (!fs::is_regular_file(
experts_dir / seed.relative_path / "expert.json", ec)) {
return false;
}
}
const fs::path hooks_dir = skills_dir.parent_path() / "hooks";
if (!fs::is_directory(hooks_dir, ec)) return false;
for (const auto& seed : default_hook_seeds()) {
if (!fs::is_regular_file(
hooks_dir / seed.relative_path / "hooks.json", ec)) {
return false;
}
}
return true;
}
fs::path normalized_path(const fs::path& path) {
std::error_code ec;
fs::path normalized = fs::weakly_canonical(path, ec);
if (ec) normalized = path.lexically_normal();
return normalized;
}
std::optional<fs::path> valid_seed_dir(const fs::path& path) {
fs::path normalized = normalized_path(path);
if (seed_dir_has_all_resources(normalized)) return normalized;
return std::nullopt;
}
std::optional<std::string> hash_file_fnv1a64(const fs::path& path) {
std::ifstream ifs(path, std::ios::binary);
if (!ifs.is_open()) return std::nullopt;
std::uint64_t hash = 14695981039346656037ULL;
char buffer[4096];
while (ifs.good()) {
ifs.read(buffer, sizeof(buffer));
const std::streamsize count = ifs.gcount();
for (std::streamsize i = 0; i < count; ++i) {
hash ^= static_cast<unsigned char>(buffer[i]);
hash *= 1099511628211ULL;
}
}
if (ifs.bad()) return std::nullopt;
std::ostringstream oss;
oss << "fnv1a64:" << std::hex << std::setfill('0') << std::setw(16)
<< hash;
return oss.str();
}
void sha256_update_u64(Sha256& sha, std::uint64_t value) {
std::array<unsigned char, 8> bytes{};
for (int i = 7; i >= 0; --i) {
bytes[static_cast<std::size_t>(7 - i)] =
static_cast<unsigned char>((value >> (i * 8)) & 0xffu);
}
sha.update(bytes.data(), bytes.size());
}
std::optional<std::string> hash_directory_tree(const fs::path& root,
std::string& error) {
std::error_code ec;
if (!fs::is_directory(root, ec)) {
error = "not a directory: " + path_to_utf8_generic(root);
return std::nullopt;
}
struct TreeEntry {
std::string relative_path;
fs::path path;
bool is_directory = false;
};
std::vector<TreeEntry> entries;
fs::recursive_directory_iterator it(root, fs::directory_options::none, ec);
const fs::recursive_directory_iterator end;
while (!ec && it != end) {
std::error_code status_ec;
const fs::file_status status = it->symlink_status(status_ec);
if (status_ec) {
error = "failed to inspect seed path: " + status_ec.message();
return std::nullopt;
}
if (fs::is_symlink(status)) {
error = "seed directories must not contain symlinks: " +
path_to_utf8_generic(it->path());
return std::nullopt;
}
if (fs::is_regular_file(status) || fs::is_directory(status)) {
std::error_code relative_ec;
const fs::path relative =
fs::relative(it->path(), root, relative_ec);
if (relative_ec) {
error = "failed to make seed path relative: " +
relative_ec.message();
return std::nullopt;
}
entries.push_back({
path_to_utf8_generic(relative),
it->path(),
fs::is_directory(status),
});
} else {
error = "unsupported file type in seed directory: " +
path_to_utf8_generic(it->path());
return std::nullopt;
}
it.increment(ec);
}
if (ec) {
error = "failed to scan seed directory: " + ec.message();
return std::nullopt;
}
std::sort(entries.begin(), entries.end(),
[](const TreeEntry& lhs, const TreeEntry& rhs) {
if (lhs.relative_path != rhs.relative_path) {
return lhs.relative_path < rhs.relative_path;
}
return lhs.is_directory < rhs.is_directory;
});
Sha256 sha;
std::array<char, 64 * 1024> buffer{};
for (const auto& entry : entries) {
const unsigned char entry_type =
entry.is_directory ? 0u : 1u;
sha.update(&entry_type, 1);
sha256_update_u64(sha,
static_cast<std::uint64_t>(
entry.relative_path.size()));
sha.update(entry.relative_path);
if (entry.is_directory) continue;
std::error_code size_ec;
const std::uintmax_t size = fs::file_size(entry.path, size_ec);
if (size_ec || size > UINT64_MAX) {
error = "failed to read seed file size: " +
path_to_utf8_generic(entry.path);
return std::nullopt;
}
sha256_update_u64(sha, static_cast<std::uint64_t>(size));
std::ifstream ifs(entry.path, std::ios::binary);
if (!ifs.is_open()) {
error = "failed to open seed file: " +
path_to_utf8_generic(entry.path);
return std::nullopt;
}
while (ifs) {
ifs.read(buffer.data(), static_cast<std::streamsize>(buffer.size()));
const std::streamsize count = ifs.gcount();
if (count > 0) {
sha.update(
reinterpret_cast<const unsigned char*>(buffer.data()),
static_cast<std::size_t>(count));
}
}
if (ifs.bad()) {
error = "failed to hash seed file: " +
path_to_utf8_generic(entry.path);
return std::nullopt;
}
}
return sha.final_hex();
}
bool directory_contains_only_file(const fs::path& directory,
const std::string& expected_path,
bool allow_directories = true) {
std::error_code ec;
std::size_t file_count = 0;
fs::recursive_directory_iterator it(
directory, fs::directory_options::none, ec);
const fs::recursive_directory_iterator end;
while (!ec && it != end) {
std::error_code status_ec;
const fs::file_status status = it->symlink_status(status_ec);
if (status_ec || fs::is_symlink(status)) return false;
if (fs::is_regular_file(status)) {
std::error_code relative_ec;
const fs::path relative =
fs::relative(it->path(), directory, relative_ec);
if (relative_ec ||
path_to_utf8_generic(relative) != expected_path) {
return false;
}
++file_count;
} else if (fs::is_directory(status)) {
if (!allow_directories) return false;
} else {
return false;
}
it.increment(ec);
}
return !ec && file_count == 1;
}
bool directory_contains_only_skill_md(const fs::path& directory) {
return directory_contains_only_file(directory, "SKILL.md");
}
void read_previous_seed_group(
const nlohmann::json& state,
const char* key,
std::unordered_map<std::string, PreviousSeedState>& previous) {
const auto group_it = state.find(key);
if (group_it == state.end() || !group_it->is_array()) return;
for (const auto& item : *group_it) {
if (!item.is_object()) continue;
const std::string relative_path =
item.value("relative_path", std::string{});
if (relative_path.empty()) continue;
PreviousSeedState entry;
entry.result = item.value("result", std::string{});
entry.installed_tree_sha256 =
item.value("installed_tree_sha256", std::string{});
entry.skill_md_hash =
item.value("skill_md_hash", std::string{});
if (item.contains("acecode_owned") &&
item["acecode_owned"].is_boolean()) {
entry.acecode_owned = item["acecode_owned"].get<bool>();
} else {
entry.acecode_owned =
entry.result == "installed" ||
entry.result == "updated" ||
entry.result == "unchanged";
}
previous[relative_path] = std::move(entry);
}
}
PreviousSeedStates read_previous_seed_state(const fs::path& state_path) {
PreviousSeedStates previous;
std::error_code ec;
if (!fs::is_regular_file(state_path, ec)) return previous;
try {
std::ifstream ifs(state_path, std::ios::binary);
if (!ifs.is_open()) return previous;
const nlohmann::json state = nlohmann::json::parse(ifs);
read_previous_seed_group(state, "skills", previous.skills);
read_previous_seed_group(state, "experts", previous.experts);
read_previous_seed_group(state, "hooks", previous.hooks);
} catch (const std::exception& e) {
LOG_WARN(
std::string("[seed] Ignoring unreadable legacy seed state: ") +
e.what());
previous.skills.clear();
previous.experts.clear();
previous.hooks.clear();
}
return previous;
}
bool previous_state_proves_pristine(const PreviousSeedState* previous,
const fs::path& target_dir,
const std::string& target_tree_sha256) {
if (!previous || !previous->acecode_owned) return false;
if (!previous->installed_tree_sha256.empty()) {
return previous->installed_tree_sha256 == target_tree_sha256;
}
if (previous->skill_md_hash.empty() ||
!directory_contains_only_skill_md(target_dir)) {
return false;
}
auto current_hash = hash_file_fnv1a64(target_dir / "SKILL.md");
return current_hash && *current_hash == previous->skill_md_hash;
}
template <typename Seed>
bool target_matches_known_official_definition(
const Seed&,
const fs::path&) {
return false;
}
bool target_matches_known_official_definition(
const DefaultHookSeed& seed,
const fs::path& target_dir) {
if (!directory_contains_only_file(target_dir, "hooks.json", false)) {
return false;
}
try {
std::ifstream ifs(target_dir / "hooks.json", std::ios::binary);
if (!ifs.is_open()) return false;
const nlohmann::json root = nlohmann::json::parse(ifs);
const std::string definition_sha256 = sha256_hex(root.dump());
if (definition_sha256 == seed.definition_sha256) return true;
return std::find(
seed.previous_definition_sha256s.begin(),
seed.previous_definition_sha256s.end(),
definition_sha256) !=
seed.previous_definition_sha256s.end();
} catch (const std::exception&) {
return false;
}
}
bool same_version_managed_hooks_need_reconciliation(
const fs::path& acecode_home) {
for (const auto& seed : default_hook_seeds()) {
const fs::path target_dir =
acecode_home / "hooks" / seed.relative_path;
std::error_code ec;
const bool target_exists = fs::exists(target_dir, ec);
if (ec || !target_exists) {
return true;
}
// Unknown or user-modified definitions stay preserved. Only a known
// previous official definition may trigger an equal-version repair.
if (!target_matches_known_official_definition(seed, target_dir)) {
continue;
}
try {
std::ifstream ifs(target_dir / "hooks.json", std::ios::binary);
if (!ifs.is_open()) continue;
const nlohmann::json root = nlohmann::json::parse(ifs);
if (sha256_hex(root.dump()) != seed.definition_sha256) {
return true;
}
} catch (const std::exception&) {
// Malformed content is treated as user-modified and is not
// overwritten by managed seed reconciliation.
}
}
return false;
}
bool copy_tree_no_overwrite(const fs::path& source_dir,
const fs::path& target_dir,
std::string& error) {
std::error_code ec;
if (fs::exists(target_dir, ec)) {
error = "target_exists";
return false;
}
fs::create_directories(target_dir, ec);
if (ec) {
error = "create_target_failed: " + ec.message();
return false;
}
fs::recursive_directory_iterator it(
source_dir, fs::directory_options::none, ec);
const fs::recursive_directory_iterator end;
while (!ec && it != end) {
std::error_code status_ec;
const fs::file_status status = it->symlink_status(status_ec);
if (status_ec) {
error = "inspect_source_failed: " + status_ec.message();
return false;
}
if (fs::is_symlink(status)) {
error = "source_symlink_not_supported";
return false;
}
std::error_code relative_ec;
const fs::path relative =
fs::relative(it->path(), source_dir, relative_ec);
if (relative_ec) {
error = "relative_path_failed: " + relative_ec.message();
return false;
}
const fs::path target = target_dir / relative;
if (fs::is_directory(status)) {
fs::create_directories(target, ec);
if (ec) {
error = "create_directory_failed: " + ec.message();
return false;
}
} else if (fs::is_regular_file(status)) {
if (target.has_parent_path()) {
fs::create_directories(target.parent_path(), ec);
if (ec) {
error = "create_parent_failed: " + ec.message();
return false;
}
}
fs::copy_file(it->path(), target, fs::copy_options::none, ec);
if (ec) {
error = "copy_file_failed: " + ec.message();
return false;
}
} else {
error = "unsupported_source_file_type";
return false;
}
it.increment(ec);
}
if (ec) {
error = "scan_source_failed: " + ec.message();
return false;
}
return true;
}
bool stage_seed_directory(const fs::path& source_dir,
const fs::path& stage_dir,
const std::string& source_tree_sha256,
std::string& error) {
std::error_code ec;
fs::remove_all(stage_dir, ec);
if (ec) {
error = "remove_staging_failed: " + ec.message();
return false;
}
if (!copy_tree_no_overwrite(source_dir, stage_dir, error)) return false;
std::string hash_error;
auto stage_hash = hash_directory_tree(stage_dir, hash_error);
if (!stage_hash) {
error = std::move(hash_error);
return false;
}
if (*stage_hash != source_tree_sha256) {
error = "staged seed hash mismatch";
return false;
}
return true;
}
void remove_empty_ancestors(fs::path path, const fs::path& stop) {
std::error_code ec;
while (!path.empty()) {
fs::remove(path, ec);
if (ec) break;
if (path == stop) break;
path = path.parent_path();
}
}
template <typename Seed>
bool recover_seed_group(
const std::vector<Seed>& seeds,
const fs::path& backup_root,
const fs::path& target_root,
const fs::path& cleanup_stop,
DefaultSkillSeedInstallResult& result) {
std::error_code ec;
for (const auto& seed : seeds) {
const fs::path backup_dir = backup_root / seed.relative_path;
const fs::path target_dir = target_root / seed.relative_path;
const bool backup_exists = fs::exists(backup_dir, ec);
if (ec) {
append_error(result, "failed to inspect seed backup: " + ec.message());
return false;
}
if (!backup_exists) continue;
const bool target_exists = fs::exists(target_dir, ec);
if (ec) {
append_error(result, "failed to inspect seed target: " + ec.message());
return false;
}
if (target_exists) {
fs::remove_all(backup_dir, ec);
if (ec) {
append_error(result,
"failed to remove completed seed backup: " +
ec.message());
return false;
}
} else {
fs::create_directories(target_dir.parent_path(), ec);
if (ec) {
append_error(result,
"failed to restore seed backup parent: " +
ec.message());
return false;
}
fs::rename(backup_dir, target_dir, ec);
if (ec) {
append_error(result,
"failed to restore interrupted seed update: " +
ec.message());
return false;
}
}
remove_empty_ancestors(backup_dir.parent_path(), cleanup_stop);
}
return true;
}
bool recover_interrupted_seed_update(
const fs::path& acecode_home,
const fs::path& skill_target_root,
const fs::path& expert_target_root,
const fs::path& hook_target_root,
DefaultSkillSeedInstallResult& result) {
const fs::path staging_root = acecode_home / kSeedStagingDir;
const fs::path backup_root = acecode_home / kSeedBackupDir;
std::error_code ec;
fs::remove_all(staging_root, ec);
if (ec) {
append_error(result, "failed to clean seed staging: " + ec.message());
return false;
}
// Releases before schema 3 stored skill backups directly below the
// backup root. Restore those first, then handle namespaced resource
// backups used by the unified Skill + expert + hook seed transaction.
if (!recover_seed_group(
default_skill_seeds(),
backup_root,
skill_target_root,
backup_root,
result)) {
return false;
}
if (!recover_seed_group(
default_skill_seeds(),
backup_root / "skills",
skill_target_root,
backup_root,
result)) {
return false;
}
if (!recover_seed_group(
default_expert_seeds(),
backup_root / "experts",
expert_target_root,
backup_root,
result)) {
return false;
}
return recover_seed_group(
default_hook_seeds(),
backup_root / "hooks",
hook_target_root,
backup_root,
result);
}
bool publish_staged_seed(const fs::path& stage_dir,
const fs::path& target_dir,
const fs::path& backup_dir,
bool update_existing,
std::string& error) {
std::error_code ec;
fs::create_directories(target_dir.parent_path(), ec);
if (ec) {
error = "create_target_parent_failed: " + ec.message();
return false;
}
if (!update_existing) {
fs::rename(stage_dir, target_dir, ec);
if (ec) {
error = "publish_seed_failed: " + ec.message();
return false;
}
return true;
}
fs::create_directories(backup_dir.parent_path(), ec);
if (ec) {
error = "create_backup_parent_failed: " + ec.message();
return false;
}
fs::rename(target_dir, backup_dir, ec);
if (ec) {
error = "backup_existing_seed_failed: " + ec.message();
return false;
}
fs::rename(stage_dir, target_dir, ec);
if (ec) {
const std::string publish_error = ec.message();
std::error_code restore_ec;
fs::rename(backup_dir, target_dir, restore_ec);
error = "publish_updated_seed_failed: " + publish_error;
if (restore_ec) {
error += "; restore_failed: " + restore_ec.message();
}
return false;
}
fs::remove_all(backup_dir, ec);
if (ec) {
LOG_WARN("[seed] Failed to remove seed update backup: " +
ec.message());
}
return true;
}
void append_seed_state_group(
nlohmann::json& items,
const std::vector<DefaultSkillSeedOutcome>& outcomes,
const std::unordered_map<std::string, PreviousSeedState>& previous,
bool retain_legacy_skill_hash) {
for (const auto& outcome : outcomes) {
nlohmann::json item;
item["name"] = outcome.name;
item["source_id"] = outcome.source_id;
item["relative_path"] = outcome.relative_path;
item["result"] = outcome.result;
bool acecode_owned = outcome.acecode_owned;
std::string installed_tree_sha256 =
outcome.installed_tree_sha256;
std::string legacy_skill_md_hash;
if (outcome.result == "error" ||
outcome.result == "missing_source") {
const auto previous_it =
previous.find(outcome.relative_path);
if (previous_it != previous.end() &&
previous_it->second.acecode_owned) {
acecode_owned = true;
if (installed_tree_sha256.empty()) {
installed_tree_sha256 =
previous_it->second.installed_tree_sha256;
}
legacy_skill_md_hash =
previous_it->second.skill_md_hash;
}
}
item["acecode_owned"] = acecode_owned;
if (!outcome.message.empty()) item["message"] = outcome.message;
if (!outcome.source_tree_sha256.empty()) {
item["source_tree_sha256"] = outcome.source_tree_sha256;
}
if (!installed_tree_sha256.empty()) {
item["installed_tree_sha256"] =
installed_tree_sha256;
}
if (retain_legacy_skill_hash && !legacy_skill_md_hash.empty()) {
item["skill_md_hash"] = legacy_skill_md_hash;
}
items.push_back(std::move(item));
}
}
bool write_seed_state(
DefaultSkillSeedInstallResult& result,
bool completed,
const PreviousSeedStates& previous) {
nlohmann::json state;
state["schema_version"] = 4;
state["bundle_version"] = result.bundle_version;
state["completed"] = completed;
state["seed_skills_dir"] =
path_to_utf8_generic(result.seed_skills_dir);
state["seed_experts_dir"] =
path_to_utf8_generic(result.seed_experts_dir);
state["seed_hooks_dir"] =
path_to_utf8_generic(result.seed_hooks_dir);
state["target_root"] = path_to_utf8_generic(result.target_root);
state["expert_target_root"] =
path_to_utf8_generic(result.expert_target_root);
state["hook_target_root"] =
path_to_utf8_generic(result.hook_target_root);
state["generated_at_unix"] =
static_cast<long long>(std::time(nullptr));
state["skills"] = nlohmann::json::array();
state["experts"] = nlohmann::json::array();
state["hooks"] = nlohmann::json::array();
append_seed_state_group(
state["skills"], result.outcomes, previous.skills, true);
append_seed_state_group(
state["experts"],
result.expert_outcomes,
previous.experts,
false);
append_seed_state_group(
state["hooks"],
result.hook_outcomes,
previous.hooks,
false);
if (!atomic_write_file(
path_to_utf8(result.state_path), state.dump(2) + "\n")) {
append_error(result, "failed to atomically write seed state");
return false;
}
result.state_written = true;
return true;
}
class SeedUpdateFileLock {
public:
explicit SeedUpdateFileLock(const fs::path& acecode_home) {
std::error_code ec;
fs::create_directories(acecode_home, ec);
if (ec) {
throw std::runtime_error(
"failed to create ACECode home for seed lock: " +
ec.message());
}
const fs::path lock_path = acecode_home / kSeedUpdateLockFile;
#ifdef _WIN32
handle_ = ::CreateFileW(
lock_path.wstring().c_str(),
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
nullptr,
OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
nullptr);
if (handle_ == INVALID_HANDLE_VALUE) {
throw std::runtime_error(
"failed to open seed update lock: error " +
std::to_string(::GetLastError()));
}
OVERLAPPED overlapped{};
if (!::LockFileEx(
handle_,
LOCKFILE_EXCLUSIVE_LOCK,
0,
MAXDWORD,
MAXDWORD,
&overlapped)) {
const DWORD error = ::GetLastError();
::CloseHandle(handle_);
handle_ = INVALID_HANDLE_VALUE;
throw std::runtime_error(
"failed to acquire seed update lock: error " +
std::to_string(error));
}
#else
fd_ = ::open(
path_to_utf8(lock_path).c_str(),
O_CREAT | O_RDWR,
S_IRUSR | S_IWUSR);
if (fd_ < 0) {
throw std::runtime_error(
"failed to open seed update lock: " +
std::error_code(errno, std::generic_category()).message());
}
while (::flock(fd_, LOCK_EX) != 0) {
if (errno == EINTR) continue;
const std::string error =
std::error_code(errno, std::generic_category()).message();
::close(fd_);
fd_ = -1;
throw std::runtime_error(
"failed to acquire seed update lock: " + error);
}
#endif
}
SeedUpdateFileLock(const SeedUpdateFileLock&) = delete;
SeedUpdateFileLock& operator=(const SeedUpdateFileLock&) = delete;
~SeedUpdateFileLock() {
#ifdef _WIN32
if (handle_ != INVALID_HANDLE_VALUE) {
OVERLAPPED overlapped{};
::UnlockFileEx(handle_, 0, MAXDWORD, MAXDWORD, &overlapped);
::CloseHandle(handle_);
}
#else
if (fd_ >= 0) {
::flock(fd_, LOCK_UN);
::close(fd_);
}
#endif
}
private:
#ifdef _WIN32
HANDLE handle_ = INVALID_HANDLE_VALUE;
#else
int fd_ = -1;
#endif
};
template <typename Seed>
void reconcile_seed_group(
const std::vector<Seed>& seeds,
const fs::path& source_root,
const fs::path& target_root,
const fs::path& staging_root,
const fs::path& backup_root,
const std::string& resource_namespace,
const char* required_filename,
const char* resource_label,
const std::unordered_map<std::string, PreviousSeedState>& previous,
std::vector<DefaultSkillSeedOutcome>& outcomes,
DefaultSkillSeedInstallResult& result,
bool& completed) {
std::error_code ec;
for (const auto& seed : seeds) {
DefaultSkillSeedOutcome outcome;