Repository navigation
Expand file tree
/
Copy pathskillforge.zig
More file actions
1174 lines (1007 loc) · 42.1 KB
/
Copy pathskillforge.zig
File metadata and controls
1174 lines (1007 loc) · 42.1 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
const std = @import("std");
const builtin = @import("builtin");
const std_compat = @import("compat");
const http_util = @import("http_util.zig");
const json_miniparse = @import("json_miniparse.zig");
// SkillForge -- skill auto-discovery, evaluation, and integration engine.
//
// Mirrors ZeroClaw's skillforge module: Scout -> Evaluate -> Integrate pipeline.
// Discovers skills from external sources, scores them, and generates
// compatible manifests for qualified candidates.
// ── Configuration ───────────────────────────────────────────────
pub const SkillForgeConfig = struct {
enabled: bool = false,
auto_integrate: bool = true,
scan_interval_hours: u64 = 24,
min_score: f64 = 0.7,
output_dir: []const u8 = "./skills",
};
// ── Scout Types ─────────────────────────────────────────────────
pub const ScoutSource = enum {
github,
clawhub,
huggingface,
pub fn fromString(s: []const u8) ScoutSource {
if (eqlLower(s, "github")) return .github;
if (eqlLower(s, "clawhub")) return .clawhub;
if (eqlLower(s, "huggingface") or eqlLower(s, "hf")) return .huggingface;
return .github; // fallback
}
pub fn name(self: ScoutSource) []const u8 {
return switch (self) {
.github => "github",
.clawhub => "clawhub",
.huggingface => "huggingface",
};
}
};
pub const ScoutResult = struct {
result_name: []const u8,
url: []const u8,
description: []const u8,
stars: u64 = 0,
language: ?[]const u8 = null,
source: ScoutSource = .github,
owner: []const u8 = "unknown",
has_license: bool = false,
};
/// A skill candidate with parsed metadata from scout results.
pub const SkillCandidate = struct {
result_name: []const u8,
repo_url: []const u8,
description: []const u8,
stars: u64 = 0,
updated_at: ?[]const u8 = null,
language: ?[]const u8 = null,
owner: []const u8 = "unknown",
has_license: bool = false,
has_build_zig: bool = false,
has_root_zig: bool = false,
};
pub fn freeCandidate(allocator: std.mem.Allocator, candidate: *SkillCandidate) void {
allocator.free(candidate.result_name);
allocator.free(candidate.repo_url);
allocator.free(candidate.description);
if (candidate.updated_at) |value| allocator.free(value);
if (candidate.language) |value| allocator.free(value);
if (!std.mem.eql(u8, candidate.owner, "unknown")) allocator.free(candidate.owner);
candidate.* = undefined;
}
pub fn freeCandidates(allocator: std.mem.Allocator, candidates: []SkillCandidate) void {
for (candidates) |*candidate| freeCandidate(allocator, candidate);
}
// ── Scout ────────────────────────────────────────────────────────
/// Scout: search GitHub for nullclaw-compatible skill repositories.
/// Uses api.github.com/search/repositories?q=QUERY+topic:nullclaw
pub fn scout(allocator: std.mem.Allocator, query: []const u8) !std.ArrayList(SkillCandidate) {
var candidates: std.ArrayList(SkillCandidate) = .empty;
errdefer candidates.deinit(allocator);
if (builtin.is_test) return candidates;
// Build the search URL
const encoded_query = try urlEncode(allocator, query);
defer allocator.free(encoded_query);
const url = try std.fmt.allocPrint(
allocator,
"https://api.github.com/search/repositories?q={s}+topic:nullclaw&sort=stars&order=desc&per_page=30",
.{encoded_query},
);
defer allocator.free(url);
// Fetch through the shared proxy-aware client (curl fallback on Android).
var client = try http_util.ProxyHttpClient.init(allocator);
defer client.deinit();
var aw: std.Io.Writer.Allocating = .init(allocator);
defer aw.deinit();
const result = client.fetch(.{
.location = .{ .url = url },
.method = .GET,
.extra_headers = &.{
.{ .name = "User-Agent", .value = "nullclaw/0.1" },
.{ .name = "Accept", .value = "application/vnd.github.v3+json" },
},
.response_writer = &aw.writer,
}) catch {
// Network unavailable — return empty list gracefully
return candidates;
};
if (result.status != .ok) {
return candidates;
}
// Parse the response body
const body = aw.writer.buffer[0..aw.writer.end];
if (body.len == 0) return candidates;
// Parse GitHub search results JSON — extract "items" array entries
try parseGitHubSearchResults(allocator, body, &candidates);
return candidates;
}
/// Parse GitHub API /search/repositories JSON response into SkillCandidate entries.
/// Uses minimal manual parsing to avoid pulling in std.json for the full response.
fn parseGitHubSearchResults(allocator: std.mem.Allocator, body: []const u8, candidates: *std.ArrayList(SkillCandidate)) !void {
// Look for each "full_name" occurrence which marks a repo item
var pos: usize = 0;
while (pos < body.len) {
// Find next repo entry by looking for "full_name"
const full_name_needle = "\"full_name\"";
const fn_pos = std.mem.indexOfPos(u8, body, pos, full_name_needle) orelse break;
// Extract fields from this item region
// Find the enclosing item boundaries (look back for '{' and forward for next item or end)
const item_start = std.mem.lastIndexOfScalar(u8, body[0..fn_pos], '{') orelse {
pos = fn_pos + full_name_needle.len;
continue;
};
// Find the end of this item — look for the next "full_name" or end of items array
const next_item = std.mem.indexOfPos(u8, body, fn_pos + full_name_needle.len, full_name_needle);
const item_end = if (next_item) |ni|
std.mem.lastIndexOfScalar(u8, body[0..ni], '{') orelse body.len
else
body.len;
const item = body[item_start..item_end];
// Extract repo fields
const repo_name = extractJsonString(item, "name") orelse {
pos = fn_pos + full_name_needle.len;
continue;
};
const html_url = extractJsonString(item, "html_url") orelse {
pos = fn_pos + full_name_needle.len;
continue;
};
const description_raw = extractJsonString(item, "description") orelse "";
const language = extractJsonString(item, "language");
const owner_login = blk: {
// Owner is a nested object; find "login" after "owner"
if (std.mem.indexOf(u8, item, "\"owner\"")) |owner_pos| {
const after_owner = item[owner_pos..];
break :blk extractJsonString(after_owner, "login");
}
break :blk null;
};
const stars = extractJsonNumber(item, "stargazers_count");
const has_license = std.mem.indexOf(u8, item, "\"license\"") != null and
std.mem.indexOf(u8, item, "\"license\":null") == null and
std.mem.indexOf(u8, item, "\"license\": null") == null;
try candidates.append(allocator, .{
.result_name = try allocator.dupe(u8, repo_name),
.repo_url = try allocator.dupe(u8, html_url),
.description = try allocator.dupe(u8, description_raw),
.stars = stars,
.language = if (language) |l| try allocator.dupe(u8, l) else null,
.owner = if (owner_login) |o| try allocator.dupe(u8, o) else "unknown",
.has_license = has_license,
});
pos = fn_pos + full_name_needle.len;
}
}
/// Extract a JSON string value for a given key from a JSON fragment.
fn extractJsonString(json: []const u8, key: []const u8) ?[]const u8 {
return json_miniparse.parseStringField(json, key);
}
/// Extract a JSON integer value for a given key.
fn extractJsonNumber(json: []const u8, key: []const u8) u64 {
return json_miniparse.parseUintField(json, key) orelse 0;
}
/// Build the GitHub search URL for a query.
pub fn buildGitHubSearchUrl(allocator: std.mem.Allocator, query: []const u8) ![]u8 {
const encoded = try urlEncode(allocator, query);
defer allocator.free(encoded);
return std.fmt.allocPrint(
allocator,
"https://api.github.com/search/repositories?q={s}+topic:nullclaw&sort=stars&order=desc&per_page=30",
.{encoded},
);
}
// ── Evaluation ──────────────────────────────────────────────────
pub const Recommendation = enum {
auto,
manual,
skip,
};
pub const Scores = struct {
compatibility: f64,
quality: f64,
security: f64,
/// Weighted total. Weights: compatibility 0.3, quality 0.35, security 0.35.
pub fn total(self: Scores) f64 {
return self.compatibility * 0.30 + self.quality * 0.35 + self.security * 0.35;
}
};
pub const EvalResult = struct {
candidate: ScoutResult,
scores: Scores,
total_score: f64,
recommendation: Recommendation,
};
/// Known-bad patterns in repo names/descriptions.
const bad_patterns = [_][]const u8{
"malware", "exploit", "hack", "crack", "keygen", "ransomware", "trojan",
};
/// Check if haystack contains word as a whole word (bounded by non-alphanumeric).
pub fn containsWord(haystack: []const u8, word: []const u8) bool {
var pos: usize = 0;
while (pos < haystack.len) {
if (std.mem.indexOfPos(u8, haystack, pos, word)) |i| {
const before_ok = i == 0 or !std.ascii.isAlphanumeric(haystack[i - 1]);
const after = i + word.len;
const after_ok = after >= haystack.len or !std.ascii.isAlphanumeric(haystack[after]);
if (before_ok and after_ok) return true;
pos = i + 1;
} else {
break;
}
}
return false;
}
/// Score compatibility dimension.
/// Zig repos get full score; check for build.zig presence in candidates.
fn scoreCompatibility(candidate: ScoutResult) f64 {
const lang = candidate.language orelse return 0.2;
if (std.mem.eql(u8, lang, "Zig")) return 1.0;
if (std.mem.eql(u8, lang, "Rust")) return 1.0;
if (std.mem.eql(u8, lang, "Python") or std.mem.eql(u8, lang, "TypeScript") or std.mem.eql(u8, lang, "JavaScript")) return 0.6;
return 0.3;
}
/// Score quality dimension (star-based, log scale).
fn scoreQuality(candidate: ScoutResult) f64 {
const stars_f: f64 = @floatFromInt(candidate.stars);
const raw = @log2(stars_f + 1.0) / 10.0;
return @min(raw, 1.0);
}
/// Score security dimension.
fn scoreSecurity(candidate: ScoutResult) f64 {
var score: f64 = 0.5;
// License bonus
if (candidate.has_license) score += 0.3;
// Bad pattern penalty (whole-word match)
const lower_name = candidate.result_name;
const lower_desc = candidate.description;
for (bad_patterns) |pat| {
if (containsWord(lower_name, pat) or containsWord(lower_desc, pat)) {
score -= 0.5;
break;
}
}
return std.math.clamp(score, 0.0, 1.0);
}
/// Evaluate a scout result and produce an EvalResult with recommendation.
pub fn evaluate(candidate: ScoutResult, min_score: f64) EvalResult {
const scores = Scores{
.compatibility = scoreCompatibility(candidate),
.quality = scoreQuality(candidate),
.security = scoreSecurity(candidate),
};
const total_score = scores.total();
const recommendation: Recommendation = if (total_score >= min_score)
.auto
else if (total_score >= 0.4)
.manual
else
.skip;
return .{
.candidate = candidate,
.scores = scores,
.total_score = total_score,
.recommendation = recommendation,
};
}
/// Evaluate a SkillCandidate with enhanced compatibility scoring.
pub fn evaluateCandidate(candidate: SkillCandidate, min_score: f64) EvalResult {
// Enhanced compatibility: check for Zig build files
var compat: f64 = 0.2;
if (candidate.language) |lang| {
if (std.mem.eql(u8, lang, "Zig")) {
compat = 1.0;
} else if (std.mem.eql(u8, lang, "Rust")) {
compat = 1.0;
} else if (std.mem.eql(u8, lang, "Python") or std.mem.eql(u8, lang, "TypeScript")) {
compat = 0.6;
} else {
compat = 0.3;
}
}
// Bonus for having build.zig or root.zig
if (candidate.has_build_zig or candidate.has_root_zig) {
compat = @min(compat + 0.2, 1.0);
}
const stars_f: f64 = @floatFromInt(candidate.stars);
const quality = @min(@log2(stars_f + 1.0) / 10.0, 1.0);
var security: f64 = 0.5;
if (candidate.has_license) security += 0.3;
for (bad_patterns) |pat| {
if (containsWord(candidate.result_name, pat) or containsWord(candidate.description, pat)) {
security -= 0.5;
break;
}
}
security = std.math.clamp(security, 0.0, 1.0);
const scores = Scores{ .compatibility = compat, .quality = quality, .security = security };
const total_score = scores.total();
const recommendation: Recommendation = if (total_score >= min_score)
.auto
else if (total_score >= 0.4)
.manual
else
.skip;
return .{
.candidate = .{
.result_name = candidate.result_name,
.url = candidate.repo_url,
.description = candidate.description,
.stars = candidate.stars,
.language = candidate.language,
.owner = candidate.owner,
.has_license = candidate.has_license,
},
.scores = scores,
.total_score = total_score,
.recommendation = recommendation,
};
}
// ── Integration ─────────────────────────────────────────────────
const CloneRepoFn = *const fn (std.mem.Allocator, []const u8, []const u8) anyerror!void;
fn cloneErrorMessage(err: anyerror) []const u8 {
return switch (err) {
error.CloneSpawnFailed => "Failed to spawn git clone",
error.CloneWaitFailed => "Failed to wait for git clone",
error.CloneNonZeroExit => "git clone exited with non-zero status",
error.CloneTerminated => "git clone terminated by signal",
else => "Failed to clone repository",
};
}
fn cloneRepoWithGit(allocator: std.mem.Allocator, repo_url: []const u8, target_path: []const u8) !void {
var child = std_compat.process.Child.init(
&.{ "git", "clone", "--depth", "1", repo_url, target_path },
allocator,
);
child.stderr_behavior = .Pipe;
child.stdout_behavior = .Pipe;
child.spawn() catch return error.CloneSpawnFailed;
const term = child.wait() catch return error.CloneWaitFailed;
switch (term) {
.exited => |code| if (code != 0) return error.CloneNonZeroExit,
else => return error.CloneTerminated,
}
}
fn integrateWithCloneFn(
allocator: std.mem.Allocator,
candidate: SkillCandidate,
skills_dir: []const u8,
clone_repo: CloneRepoFn,
) !IntegrationResult {
const safe_name = try sanitizePathComponent(candidate.result_name);
// Ensure skills directory exists
std_compat.fs.makeDirAbsolute(skills_dir) catch |err| switch (err) {
error.PathAlreadyExists => {},
else => return IntegrationResult{
.skill_name = safe_name,
.install_path = skills_dir,
.success = false,
.error_message = "Failed to create skills directory",
},
};
// Build target path: skills_dir/NAME
const target_path = try std.fmt.allocPrint(allocator, "{s}/{s}", .{ skills_dir, safe_name });
defer allocator.free(target_path);
clone_repo(allocator, candidate.repo_url, target_path) catch |err| {
return IntegrationResult{
.skill_name = safe_name,
.install_path = skills_dir,
.success = false,
.error_message = cloneErrorMessage(err),
};
};
if (!hasSupportedSkillStructure(target_path)) {
// Remove the cloned directory since it lacks expected structure
std_compat.fs.deleteTreeAbsolute(target_path) catch {};
return IntegrationResult{
.skill_name = safe_name,
.install_path = skills_dir,
.success = false,
.error_message = "Cloned repo lacks SKILL.md, SKILL.toml, skill.json, build.zig, or root.zig",
};
}
return IntegrationResult{
.skill_name = safe_name,
.install_path = skills_dir,
.success = true,
};
}
/// Integrate a skill: clone repo to skills_dir/NAME/,
/// verify structure (agent skill manifests, root.zig, or build.zig).
pub fn integrate(allocator: std.mem.Allocator, candidate: SkillCandidate, skills_dir: []const u8) !IntegrationResult {
return integrateWithCloneFn(allocator, candidate, skills_dir, cloneRepoWithGit);
}
/// Check if a file exists in a directory.
fn hasFile(dir_path: []const u8, filename: []const u8) bool {
var buf: [std_compat.fs.max_path_bytes]u8 = undefined;
const full = std.fmt.bufPrint(&buf, "{s}/{s}", .{ dir_path, filename }) catch return false;
std_compat.fs.accessAbsolute(full, .{}) catch return false;
return true;
}
fn hasSupportedSkillStructure(dir_path: []const u8) bool {
return hasFile(dir_path, "SKILL.md") or
hasFile(dir_path, "SKILL.toml") or
hasFile(dir_path, "skill.json") or
hasFile(dir_path, "build.zig") or
hasFile(dir_path, "root.zig");
}
pub const IntegrationResult = struct {
skill_name: []const u8,
install_path: []const u8,
success: bool,
error_message: ?[]const u8 = null,
};
// ── Integration Helpers ─────────────────────────────────────────
/// Escape special characters for TOML basic string values.
pub fn escapeToml(allocator: std.mem.Allocator, s: []const u8) ![]u8 {
var result: std.ArrayList(u8) = .empty;
errdefer result.deinit(allocator);
for (s) |c| {
switch (c) {
'\\' => try result.appendSlice(allocator, "\\\\"),
'"' => try result.appendSlice(allocator, "\\\""),
'\n' => try result.appendSlice(allocator, "\\n"),
'\r' => try result.appendSlice(allocator, "\\r"),
'\t' => try result.appendSlice(allocator, "\\t"),
0x08 => try result.appendSlice(allocator, "\\b"),
0x0C => try result.appendSlice(allocator, "\\f"),
else => try result.append(allocator, c),
}
}
return try result.toOwnedSlice(allocator);
}
/// Sanitize a string for use as a single path component.
/// Rejects empty names, "..", and names containing path separators or NUL.
pub fn sanitizePathComponent(s: []const u8) ![]const u8 {
const trimmed = std.mem.trim(u8, s, " \t.");
if (trimmed.len == 0) return error.EmptyName;
// Check for unsafe patterns
for (trimmed) |c| {
if (c == '/' or c == '\\' or c == 0) return error.UnsafePath;
}
if (std.mem.eql(u8, trimmed, "..")) return error.UnsafePath;
return trimmed;
}
// ── ForgeReport ─────────────────────────────────────────────────
pub const ForgeReport = struct {
discovered: usize = 0,
evaluated: usize = 0,
auto_integrated: usize = 0,
manual_review: usize = 0,
skipped: usize = 0,
};
/// Run the forge pipeline: scout -> evaluate -> integrate.
pub fn forge(allocator: std.mem.Allocator, cfg: SkillForgeConfig) !ForgeReport {
if (!cfg.enabled) {
return .{};
}
// Scout phase
var candidates = try scout(allocator, "nullclaw skill");
defer candidates.deinit(allocator);
var report = ForgeReport{};
report.discovered = candidates.items.len;
// Evaluate phase
for (candidates.items) |candidate| {
report.evaluated += 1;
const result = evaluateCandidate(candidate, cfg.min_score);
switch (result.recommendation) {
.auto => {
if (cfg.auto_integrate) {
const int_result = integrate(allocator, candidate, cfg.output_dir) catch {
report.skipped += 1;
continue;
};
if (int_result.success) {
report.auto_integrated += 1;
} else {
report.skipped += 1;
}
} else {
report.manual_review += 1;
}
},
.manual => report.manual_review += 1,
.skip => report.skipped += 1,
}
}
return report;
}
// ── Helpers ─────────────────────────────────────────────────────
fn eqlLower(a: []const u8, b: []const u8) bool {
if (a.len != b.len) return false;
for (a, b) |ca, cb| {
if (std.ascii.toLower(ca) != std.ascii.toLower(cb)) return false;
}
return true;
}
/// Minimal percent-encoding for query strings (space -> +).
pub fn urlEncode(allocator: std.mem.Allocator, s: []const u8) ![]u8 {
var result: std.ArrayList(u8) = .empty;
errdefer result.deinit(allocator);
for (s) |c| {
switch (c) {
' ' => try result.append(allocator, '+'),
'&' => try result.appendSlice(allocator, "%26"),
'#' => try result.appendSlice(allocator, "%23"),
else => try result.append(allocator, c),
}
}
return try result.toOwnedSlice(allocator);
}
/// Deduplicate scout results by URL (keeps first occurrence).
pub fn dedup(allocator: std.mem.Allocator, results: *std.ArrayList(ScoutResult)) !void {
var seen = std.StringHashMap(void).init(allocator);
defer seen.deinit();
var i: usize = 0;
while (i < results.items.len) {
const url = results.items[i].url;
if (seen.contains(url)) {
_ = results.orderedRemove(i);
} else {
try seen.put(url, {});
i += 1;
}
}
}
/// Deduplicate skill candidates by repo URL (keeps first occurrence).
pub fn dedupCandidates(allocator: std.mem.Allocator, results: *std.ArrayList(SkillCandidate)) !void {
var seen = std.StringHashMap(void).init(allocator);
defer seen.deinit();
var i: usize = 0;
while (i < results.items.len) {
const url = results.items[i].repo_url;
if (seen.contains(url)) {
_ = results.orderedRemove(i);
} else {
try seen.put(url, {});
i += 1;
}
}
}
// ── Tests ───────────────────────────────────────────────────────
test "ScoutSource.fromString github" {
try std.testing.expectEqual(ScoutSource.github, ScoutSource.fromString("github"));
try std.testing.expectEqual(ScoutSource.github, ScoutSource.fromString("GitHub"));
}
test "ScoutSource.fromString clawhub" {
try std.testing.expectEqual(ScoutSource.clawhub, ScoutSource.fromString("clawhub"));
}
test "ScoutSource.fromString huggingface" {
try std.testing.expectEqual(ScoutSource.huggingface, ScoutSource.fromString("huggingface"));
try std.testing.expectEqual(ScoutSource.huggingface, ScoutSource.fromString("hf"));
}
test "ScoutSource.fromString unknown defaults to github" {
try std.testing.expectEqual(ScoutSource.github, ScoutSource.fromString("unknown"));
}
test "ScoutSource.name" {
try std.testing.expectEqualStrings("github", ScoutSource.github.name());
try std.testing.expectEqualStrings("clawhub", ScoutSource.clawhub.name());
try std.testing.expectEqualStrings("huggingface", ScoutSource.huggingface.name());
}
test "scores total weighted" {
const s = Scores{ .compatibility = 1.0, .quality = 1.0, .security = 1.0 };
try std.testing.expect(@abs(s.total() - 1.0) < 0.001);
const s2 = Scores{ .compatibility = 0.0, .quality = 0.0, .security = 0.0 };
try std.testing.expect(@abs(s2.total()) < 0.001);
}
test "high quality Rust repo gets auto" {
const c = ScoutResult{
.result_name = "test-skill",
.url = "https://github.com/test/test-skill",
.description = "A test skill",
.stars = 500,
.language = "Rust",
.has_license = true,
};
const res = evaluate(c, 0.7);
try std.testing.expect(res.total_score >= 0.7);
try std.testing.expectEqual(Recommendation.auto, res.recommendation);
}
test "low star no license gets manual or skip" {
const c = ScoutResult{
.result_name = "test-skill",
.url = "https://github.com/test/test-skill",
.description = "A test skill",
.stars = 1,
.language = null,
.has_license = false,
};
const res = evaluate(c, 0.7);
try std.testing.expect(res.total_score < 0.7);
try std.testing.expect(res.recommendation != .auto);
}
test "bad pattern tanks security" {
const c = ScoutResult{
.result_name = "malware-skill",
.url = "https://github.com/test/malware",
.description = "A bad skill",
.stars = 1000,
.language = "Rust",
.has_license = true,
};
const res = evaluate(c, 0.7);
try std.testing.expect(res.scores.security <= 0.5);
}
test "hackathon not flagged as bad" {
const c = ScoutResult{
.result_name = "hackathon-tools",
.url = "https://github.com/test/hackathon-tools",
.description = "Tools for hackathons and lifehacks",
.stars = 500,
.language = "Rust",
.has_license = true,
};
const res = evaluate(c, 0.7);
// "hack" should NOT match "hackathon" or "lifehacks" (whole-word only)
try std.testing.expect(res.scores.security >= 0.5);
}
test "exact hack is flagged" {
const c = ScoutResult{
.result_name = "hack-tool",
.url = "https://github.com/test/hack-tool",
.description = "A hacking tool",
.stars = 500,
.language = "Rust",
.has_license = false,
};
const res = evaluate(c, 0.7);
try std.testing.expect(res.scores.security < 0.5);
}
test "containsWord basic" {
try std.testing.expect(containsWord("hello world", "hello"));
try std.testing.expect(containsWord("hello world", "world"));
try std.testing.expect(!containsWord("helloworld", "hello"));
}
test "containsWord with hyphens" {
try std.testing.expect(containsWord("hack-tool", "hack"));
try std.testing.expect(!containsWord("hackathon", "hack"));
try std.testing.expect(!containsWord("lifehacks", "hack"));
}
test "containsWord at boundaries" {
try std.testing.expect(containsWord("hack", "hack"));
try std.testing.expect(containsWord("hack!", "hack"));
try std.testing.expect(containsWord("!hack", "hack"));
}
test "escapeToml handles quotes and control chars" {
const allocator = std.testing.allocator;
const r1 = try escapeToml(allocator, "say \"hello\"");
defer allocator.free(r1);
try std.testing.expectEqualStrings("say \\\"hello\\\"", r1);
const r2 = try escapeToml(allocator, "back\\slash");
defer allocator.free(r2);
try std.testing.expectEqualStrings("back\\\\slash", r2);
const r3 = try escapeToml(allocator, "line\nbreak");
defer allocator.free(r3);
try std.testing.expectEqualStrings("line\\nbreak", r3);
const r4 = try escapeToml(allocator, "tab\there");
defer allocator.free(r4);
try std.testing.expectEqualStrings("tab\\there", r4);
const r5 = try escapeToml(allocator, "cr\rhere");
defer allocator.free(r5);
try std.testing.expectEqualStrings("cr\\rhere", r5);
}
test "sanitizePathComponent rejects traversal" {
try std.testing.expectError(error.EmptyName, sanitizePathComponent(".."));
try std.testing.expectError(error.EmptyName, sanitizePathComponent("..."));
try std.testing.expectError(error.EmptyName, sanitizePathComponent(""));
try std.testing.expectError(error.EmptyName, sanitizePathComponent(" "));
}
test "sanitizePathComponent rejects separators" {
try std.testing.expectError(error.UnsafePath, sanitizePathComponent("foo/bar"));
try std.testing.expectError(error.UnsafePath, sanitizePathComponent("foo\\bar"));
}
test "sanitizePathComponent accepts valid names" {
const result = try sanitizePathComponent("test-skill");
try std.testing.expectEqualStrings("test-skill", result);
}
test "sanitizePathComponent rejects traversal and injection payloads" {
try std.testing.expectError(error.EmptyName, sanitizePathComponent(".."));
try std.testing.expectError(error.UnsafePath, sanitizePathComponent("../foo"));
try std.testing.expectError(error.UnsafePath, sanitizePathComponent("foo/../bar"));
try std.testing.expectError(error.UnsafePath, sanitizePathComponent("/etc/passwd"));
try std.testing.expectError(error.UnsafePath, sanitizePathComponent("C:\\Windows"));
// NUL byte injection
try std.testing.expectError(error.UnsafePath, sanitizePathComponent("test\x00skill"));
}
test "sanitizePathComponent trims dots" {
const result = try sanitizePathComponent(".hidden.");
try std.testing.expectEqualStrings("hidden", result);
}
test "urlEncode works" {
const allocator = std.testing.allocator;
const r1 = try urlEncode(allocator, "hello world");
defer allocator.free(r1);
try std.testing.expectEqualStrings("hello+world", r1);
const r2 = try urlEncode(allocator, "a&b#c");
defer allocator.free(r2);
try std.testing.expectEqualStrings("a%26b%23c", r2);
}
test "dedup removes duplicates" {
const allocator = std.testing.allocator;
var results: std.ArrayList(ScoutResult) = .empty;
defer results.deinit(allocator);
try results.append(allocator, .{ .result_name = "a", .url = "https://github.com/x/a", .description = "" });
try results.append(allocator, .{ .result_name = "a-dup", .url = "https://github.com/x/a", .description = "" });
try results.append(allocator, .{ .result_name = "b", .url = "https://github.com/x/b", .description = "" });
try dedup(allocator, &results);
try std.testing.expectEqual(@as(usize, 2), results.items.len);
try std.testing.expectEqualStrings("a", results.items[0].result_name);
try std.testing.expectEqualStrings("b", results.items[1].result_name);
}
test "default config values" {
const cfg = SkillForgeConfig{};
try std.testing.expect(!cfg.enabled);
try std.testing.expect(cfg.auto_integrate);
try std.testing.expectEqual(@as(u64, 24), cfg.scan_interval_hours);
try std.testing.expect(@abs(cfg.min_score - 0.7) < 0.001);
}
test "hasSupportedSkillStructure accepts agent skill manifests" {
const allocator = std.testing.allocator;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
try @import("compat").fs.Dir.wrap(tmp.dir).makePath("md");
try @import("compat").fs.Dir.wrap(tmp.dir).makePath("toml");
try @import("compat").fs.Dir.wrap(tmp.dir).makePath("empty");
{
const f = try @import("compat").fs.Dir.wrap(tmp.dir).createFile("md/SKILL.md", .{});
defer f.close();
try f.writeAll("# Skill");
}
{
const f = try @import("compat").fs.Dir.wrap(tmp.dir).createFile("toml/SKILL.toml", .{});
defer f.close();
try f.writeAll(
\\[skill]
\\name = "toml"
);
}
const base = try @import("compat").fs.Dir.wrap(tmp.dir).realpathAlloc(allocator, ".");
defer allocator.free(base);
const md_path = try std_compat.fs.path.join(allocator, &.{ base, "md" });
defer allocator.free(md_path);
const toml_path = try std_compat.fs.path.join(allocator, &.{ base, "toml" });
defer allocator.free(toml_path);
const empty_path = try std_compat.fs.path.join(allocator, &.{ base, "empty" });
defer allocator.free(empty_path);
try std.testing.expect(hasSupportedSkillStructure(md_path));
try std.testing.expect(hasSupportedSkillStructure(toml_path));
try std.testing.expect(!hasSupportedSkillStructure(empty_path));
}
test "forge disabled returns empty report" {
const allocator = std.testing.allocator;
const cfg = SkillForgeConfig{};
const report = try forge(allocator, cfg);
try std.testing.expectEqual(@as(usize, 0), report.discovered);
try std.testing.expectEqual(@as(usize, 0), report.auto_integrated);
}
test "forge enabled returns empty report (no network)" {
const allocator = std.testing.allocator;
const cfg = SkillForgeConfig{ .enabled = true };
const report = try forge(allocator, cfg);
try std.testing.expectEqual(@as(usize, 0), report.discovered);
}
test "Zig language gets full compatibility score" {
const c = ScoutResult{
.result_name = "zig-skill",
.url = "https://github.com/test/zig-skill",
.description = "A Zig skill",
.stars = 100,
.language = "Zig",
.has_license = true,
};
const res = evaluate(c, 0.7);
try std.testing.expect(@abs(res.scores.compatibility - 1.0) < 0.001);
}
test "Python gets moderate compatibility score" {
const c = ScoutResult{
.result_name = "py-skill",
.url = "https://github.com/test/py-skill",
.description = "A Python skill",
.stars = 100,
.language = "Python",
.has_license = true,
};
const res = evaluate(c, 0.7);
try std.testing.expect(@abs(res.scores.compatibility - 0.6) < 0.001);
}
test "unknown language gets low compatibility" {
const c = ScoutResult{
.result_name = "cobol-skill",
.url = "https://github.com/test/cobol-skill",
.description = "A COBOL skill",
.stars = 100,
.language = "COBOL",
.has_license = true,
};
const res = evaluate(c, 0.7);
try std.testing.expect(@abs(res.scores.compatibility - 0.3) < 0.001);
}
// ── Scout / Integration tests ───────────────────────────────────
test "buildGitHubSearchUrl encodes query" {
const allocator = std.testing.allocator;
const url = try buildGitHubSearchUrl(allocator, "nullclaw skill");
defer allocator.free(url);
try std.testing.expect(std.mem.indexOf(u8, url, "nullclaw+skill") != null);
try std.testing.expect(std.mem.indexOf(u8, url, "api.github.com") != null);
try std.testing.expect(std.mem.indexOf(u8, url, "topic:nullclaw") != null);
}
test "buildGitHubSearchUrl handles special chars" {
const allocator = std.testing.allocator;
const url = try buildGitHubSearchUrl(allocator, "foo & bar");
defer allocator.free(url);
try std.testing.expect(std.mem.indexOf(u8, url, "foo+%26+bar") != null);
}
test "scout bypasses network in test mode" {
const allocator = std.testing.allocator;
var candidates = try scout(allocator, "test");
defer candidates.deinit(allocator);
// builtin.is_test returns empty cleanly without initiating an HTTP request.
try std.testing.expectEqual(@as(usize, 0), candidates.items.len);
}
test "parseGitHubSearchResults extracts candidate metadata" {
const allocator = std.testing.allocator;
var candidates: std.ArrayList(SkillCandidate) = .empty;
defer {
freeCandidates(allocator, candidates.items);
candidates.deinit(allocator);
}
const body =
\\{"items":[
\\ {"name":"zig-skill","full_name":"owner/zig-skill","html_url":"https://github.com/owner/zig-skill","description":"A Zig skill","language":"Zig","stargazers_count":42,"owner":{"login":"owner"},"license":{"key":"mit"}},
\\ {"name":"plain-skill","full_name":"owner/plain-skill","html_url":"https://github.com/owner/plain-skill","description":null,"language":null,"stargazers_count":0,"owner":{"login":"owner"},"license":null}
\\]}
;
try parseGitHubSearchResults(allocator, body, &candidates);
try std.testing.expectEqual(@as(usize, 2), candidates.items.len);
try std.testing.expectEqualStrings("zig-skill", candidates.items[0].result_name);
try std.testing.expectEqualStrings("https://github.com/owner/zig-skill", candidates.items[0].repo_url);
try std.testing.expectEqualStrings("A Zig skill", candidates.items[0].description);
try std.testing.expectEqualStrings("Zig", candidates.items[0].language.?);
try std.testing.expectEqual(@as(u64, 42), candidates.items[0].stars);
try std.testing.expectEqualStrings("owner", candidates.items[0].owner);