-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild_site.py
More file actions
965 lines (832 loc) · 36.2 KB
/
build_site.py
File metadata and controls
965 lines (832 loc) · 36.2 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
#!/usr/bin/env python3
"""Build the Starkskills static site from repository data."""
from __future__ import annotations
import argparse
import hashlib
import html
import json
import re
from collections import Counter
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable
from urllib.parse import quote
DEFAULT_REPO_SLUG = "keep-starknet-strange/starknet-skills"
DEFAULT_REPO_REF = "main"
DOMAIN_PATTERN = re.compile(r"(?=.{1,253}\Z)(?!-)(?:[A-Za-z0-9-]{1,63}\.)+[A-Za-z0-9-]{2,63}(?<!-)")
REPO_SLUG_PATTERN = re.compile(r"^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$")
MODULES: list[tuple[str, str, str]] = [
("cairo-auditor", "Audit workflow for Cairo contracts", "AUD"),
("cairo-contract-authoring", "Contract implementation patterns", "AUTH"),
("cairo-testing", "Unit, integration, and invariant testing", "TEST"),
("cairo-optimization", "Performance and resource usage", "OPT"),
("cairo-toolchain", "Build, declare, deploy, and verify", "OPS"),
("account-abstraction", "Accounts, sessions, and threat patterns", "AA"),
("starknet-network-facts", "Network semantics and constraints", "NET"),
]
ASCII_LOGO = r"""
███████╗████████╗ █████╗ ██████╗ ██╗ ██╗███████╗██╗ ██╗██╗██╗ ██╗ ███████╗
██╔════╝╚══██╔══╝██╔══██╗██╔══██╗██║ ██╔╝██╔════╝██║ ██╔╝██║██║ ██║ ██╔════╝
███████╗ ██║ ███████║██████╔╝█████╔╝ ███████╗█████╔╝ ██║██║ ██║ ███████╗
╚════██║ ██║ ██╔══██║██╔══██╗██╔═██╗ ╚════██║██╔═██╗ ██║██║ ██║ ╚════██║
███████║ ██║ ██║ ██║██║ ██║██║ ██╗███████║██║ ██╗██║███████╗███████╗███████║
╚══════╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚═╝╚══════╝╚══════╝╚══════╝
""".strip("\n")
@dataclass
class ScorecardMetrics:
path: Path
cases: int | None
precision: float | None
recall: float | None
@dataclass
class VulnCard:
name: str
path: Path
trigger: str
detection_rule: str
source_findings: list[str]
severity_distribution: dict[str, int]
def read_jsonl(path: Path) -> list[dict]:
rows: list[dict] = []
for line in path.read_text(encoding="utf-8").splitlines():
line = line.strip()
if not line:
continue
rows.append(json.loads(line))
return rows
def count_md_files(directory: Path) -> int:
return sum(1 for p in directory.glob("*.md") if p.name != "README.md")
def parse_version(path: Path) -> tuple[int, int, int]:
match = re.match(r"^v(\d+)\.(\d+)\.(\d+)", path.name)
if not match:
return (0, 0, 0)
return tuple(int(match.group(i)) for i in (1, 2, 3))
def parse_scorecard(path: Path) -> ScorecardMetrics:
text = path.read_text(encoding="utf-8")
cases = _find_int(r"- Cases:\s+(\d+)", text)
precision = _find_float(r"- Precision:\s+([0-9.]+)", text)
recall = _find_float(r"- Recall:\s+([0-9.]+)", text)
return ScorecardMetrics(path=path, cases=cases, precision=precision, recall=recall)
def _find_int(pattern: str, text: str) -> int | None:
match = re.search(pattern, text)
return int(match.group(1)) if match else None
def _find_float(pattern: str, text: str) -> float | None:
match = re.search(pattern, text)
return float(match.group(1)) if match else None
def pick_latest_scorecards(
scorecard_dir: Path,
) -> tuple[ScorecardMetrics | None, ScorecardMetrics | None, ScorecardMetrics | None]:
files = [p for p in scorecard_dir.glob("v*.md") if p.is_file()]
if not files:
return None, None, None
real_world = [p for p in files if "cairo-auditor-realworld-benchmark" in p.name]
deterministic = [p for p in files if "cairo-auditor-benchmark" in p.name and "realworld" not in p.name]
contract_skill = [p for p in files if "contract-skill-benchmark" in p.name]
def _pick(candidates: list[Path]) -> ScorecardMetrics | None:
if not candidates:
return None
chosen = max(candidates, key=lambda item: (parse_version(item), item.name))
return parse_scorecard(chosen)
return _pick(deterministic), _pick(contract_skill), _pick(real_world)
def parse_card_sections(markdown_text: str) -> dict[str, str]:
sections: dict[str, str] = {}
current: str | None = None
buf: list[str] = []
for line in markdown_text.splitlines():
if line.startswith("## "):
if current is not None:
sections[current] = "\n".join(buf).strip()
current = line[3:].strip()
buf = []
continue
if current is not None:
buf.append(line)
if current is not None:
sections[current] = "\n".join(buf).strip()
return sections
def compact_markdown_text(value: str, limit: int = 220) -> str:
if not value:
return ""
text = value
text = re.sub(r"```[\s\S]*?```", " ", text)
text = re.sub(r"`([^`]+)`", r"\1", text)
text = re.sub(r"\[(.*?)\]\(.*?\)", r"\1", text)
text = re.sub(r"^[-*]\s+", "", text, flags=re.MULTILINE)
text = re.sub(r"\s+", " ", text).strip()
if len(text) <= limit:
return text
return text[: limit - 1].rstrip() + "…"
def parse_source_findings(section: str) -> list[str]:
ids: list[str] = []
for line in section.splitlines():
match = re.search(r"`([^`]+)`", line)
if match:
ids.append(match.group(1).strip())
return ids
def github_blob(path: Path, root: Path, repo_github: str, repo_ref: str) -> str:
rel = path.relative_to(root).as_posix()
return f"{repo_github}/blob/{repo_ref}/{rel}"
def raw_skill_url(skill_name: str, repo_raw: str) -> str:
return f"{repo_raw}/{skill_name}/SKILL.md"
def normalize_domain(value: str | None) -> str | None:
if value is None:
return None
domain = value.strip().lower()
if not domain:
raise ValueError("Domain must not be empty.")
if any(ch.isspace() for ch in domain):
raise ValueError(f"Domain contains whitespace: {value!r}")
if not DOMAIN_PATTERN.fullmatch(domain):
raise ValueError(f"Invalid domain: {value!r}")
return domain
def normalize_repo_slug(value: str) -> str:
slug = value.strip()
if not REPO_SLUG_PATTERN.fullmatch(slug):
raise ValueError(f"Invalid repo slug: {value!r}. Expected OWNER/REPO.")
return slug
def normalize_repo_ref(value: str) -> str:
ref = value.strip()
if not ref or any(ch.isspace() for ch in ref):
raise ValueError(f"Invalid repo ref: {value!r}")
return ref
def require_file(path: Path) -> Path:
if not path.is_file():
raise SystemExit(f"[build_site] Required file not found: {path}")
return path
def require_directory(path: Path) -> Path:
if not path.is_dir():
raise SystemExit(f"[build_site] Required directory not found: {path}")
return path
def fingerprint_files(root: Path, files: list[Path]) -> str:
digest = hashlib.sha256()
for path in sorted(set(files)):
rel = path.relative_to(root).as_posix()
digest.update(rel.encode("utf-8"))
digest.update(b"\0")
digest.update(path.read_bytes())
digest.update(b"\0")
return digest.hexdigest()[:16]
def build_dataset(root: Path, repo_slug: str, repo_ref: str) -> dict:
repo_github = f"https://github.com/{repo_slug}"
repo_raw = f"https://raw.githubusercontent.com/{repo_slug}/{repo_ref}"
manifest_path = require_file(root / "datasets/manifests/audits.jsonl")
manifests = read_jsonl(manifest_path)
normalized_findings_dir = require_directory(root / "datasets/normalized/findings")
normalized_findings_files = sorted(normalized_findings_dir.glob("*.jsonl"))
if not normalized_findings_files:
raise SystemExit(f"[build_site] No normalized finding files found in: {normalized_findings_dir}")
normalized_findings = [
finding
for jsonl_path in normalized_findings_files
for finding in read_jsonl(jsonl_path)
]
finding_by_id = {
item["finding_id"]: item
for item in normalized_findings
if item.get("finding_id")
}
normalized_audits_dir = require_directory(root / "datasets/normalized/audits")
normalized_audits_files = sorted(normalized_audits_dir.glob("*.json"))
normalized_audits_count = len(normalized_audits_files)
segments_dir = require_directory(root / "datasets/segments")
segment_files = sorted(segments_dir.glob("*.jsonl"))
segments_count = len(segment_files)
vuln_cards_dir = require_directory(root / "datasets/distilled/vuln-cards")
vuln_card_paths = sorted(p for p in vuln_cards_dir.glob("*.md") if p.name != "README.md")
fix_patterns_dir = require_directory(root / "datasets/distilled/fix-patterns")
test_recipes_dir = require_directory(root / "datasets/distilled/test-recipes")
fix_pattern_files = sorted(fix_patterns_dir.glob("*.md"))
test_recipe_files = sorted(test_recipes_dir.glob("*.md"))
scorecards_dir = require_directory(root / "evals/scorecards")
scorecard_files = sorted(scorecards_dir.glob("v*.md"))
vuln_cards: list[VulnCard] = []
for card_path in vuln_card_paths:
text = card_path.read_text(encoding="utf-8")
sections = parse_card_sections(text)
source_ids = parse_source_findings(sections.get("Source Findings", ""))
sev_counter = Counter(
finding_by_id[item_id].get("severity_normalized", "unknown")
for item_id in source_ids
if item_id in finding_by_id
)
vuln_cards.append(
VulnCard(
name=card_path.stem,
path=card_path,
trigger=compact_markdown_text(sections.get("Trigger", "")),
detection_rule=compact_markdown_text(sections.get("Detection Rule", "")),
source_findings=source_ids,
severity_distribution=dict(sev_counter),
)
)
deterministic_scorecard, contract_skill_scorecard, realworld_scorecard = pick_latest_scorecards(
scorecards_dir
)
source_fingerprint = fingerprint_files(
root,
[
manifest_path,
*normalized_findings_files,
*normalized_audits_files,
*segment_files,
*vuln_card_paths,
*fix_pattern_files,
*test_recipe_files,
*scorecard_files,
],
)
return {
"source_fingerprint": source_fingerprint,
"counts": {
"cataloged_audits": len(manifests),
"segmented_audits": segments_count,
"normalized_audits": normalized_audits_count,
"normalized_findings": len(normalized_findings),
"distilled_vuln_cards": len(vuln_cards),
"distilled_fix_patterns": count_md_files(fix_patterns_dir),
"distilled_test_recipes": count_md_files(test_recipes_dir),
"skill_modules": len(MODULES),
"skills_total_with_router": len(MODULES) + 1,
},
"latest_scorecards": {
"deterministic": scorecard_to_dict(deterministic_scorecard, root, repo_github, repo_ref),
"contract_skill": scorecard_to_dict(contract_skill_scorecard, root, repo_github, repo_ref),
"realworld": scorecard_to_dict(realworld_scorecard, root, repo_github, repo_ref),
},
"modules": [
{
"name": name,
"description": description,
"sigil": sigil,
"skill_path": f"{name}/SKILL.md",
"raw_skill_url": raw_skill_url(name, repo_raw),
"github_url": f"{repo_github}/blob/{repo_ref}/{name}/SKILL.md",
}
for name, description, sigil in MODULES
],
"vuln_cards": [
{
"name": card.name,
"trigger": card.trigger,
"detection_rule": card.detection_rule,
"source_findings": card.source_findings,
"severity_distribution": card.severity_distribution,
"github_url": github_blob(card.path, root, repo_github, repo_ref),
}
for card in vuln_cards
],
"links": {
"repo": repo_github,
"repo_ref": repo_ref,
"license": f"{repo_github}/blob/{repo_ref}/LICENSE",
"router_skill_raw": f"{repo_raw}/SKILL.md",
"router_skill_github": f"{repo_github}/blob/{repo_ref}/SKILL.md",
"quality_workflow": f"{repo_github}/actions/workflows/quality.yml",
"full_evals_workflow": f"{repo_github}/actions/workflows/full-evals.yml",
"heldout_policy": f"{repo_github}/blob/{repo_ref}/evals/heldout/README.md",
"contributing": f"{repo_github}/blob/{repo_ref}/CONTRIBUTING.md",
"cairo_auditor": f"{repo_github}/blob/{repo_ref}/cairo-auditor/SKILL.md",
"cairo_auditor_readme": f"{repo_github}/blob/{repo_ref}/cairo-auditor/README.md",
"pipeline_readme": f"{repo_github}/blob/{repo_ref}/datasets/README.md",
"vuln_cards_dir": f"{repo_github}/tree/{repo_ref}/datasets/distilled/vuln-cards",
},
}
def scorecard_to_dict(
scorecard: ScorecardMetrics | None,
root: Path,
repo_github: str,
repo_ref: str,
) -> dict | None:
if scorecard is None:
return None
return {
"path": scorecard.path.relative_to(root).as_posix(),
"github_url": github_blob(scorecard.path, root, repo_github, repo_ref),
"cases": scorecard.cases,
"precision": scorecard.precision,
"recall": scorecard.recall,
}
def e(value: object) -> str:
return html.escape(str(value), quote=True)
def fmt_int(value: int) -> str:
return f"{value:,}"
def fmt_metric(value: int | float | None) -> str:
if value is None:
return "n/a"
if isinstance(value, float):
return f"{value:.1f}" if value.is_integer() else f"{value:.2f}".rstrip("0").rstrip(".")
return str(value)
def severity_badges(counter: dict[str, int]) -> str:
if not counter:
return '<span class="pill pill-muted">none</span>'
order = ["critical", "high", "medium", "low", "best_practice", "info", "unknown"]
parts = []
for key in order:
if key not in counter:
continue
parts.append(f'<span class="pill">{e(key)}: {counter[key]}</span>')
for key, value in sorted(counter.items()):
if key in order:
continue
parts.append(f'<span class="pill">{e(key)}: {value}</span>')
return "".join(parts)
def source_finding_links(ids: Iterable[str], repo_github: str) -> str:
output: list[str] = []
for item_id in ids:
encoded_id = quote(item_id, safe="")
output.append(
(
'<a class="finding-link" '
f'href="{e(repo_github)}/search?q={e(encoded_id)}" '
f'target="_blank" rel="noreferrer">{e(item_id)}</a>'
)
)
return "".join(output) if output else '<span class="muted">none</span>'
def site_url(domain: str | None, path: str = "") -> str | None:
if not domain:
return None
path = path.lstrip("/")
return f"https://{domain}/{path}" if path else f"https://{domain}"
def head_meta(title: str, description: str, css_path: str, domain: str | None, page_path: str) -> str:
canonical = site_url(domain, page_path)
og_image = site_url(domain, "assets/og-card.png")
favicon = site_url(domain, "assets/favicon.svg")
meta = [
' <meta charset="utf-8" />',
' <meta name="viewport" content="width=device-width, initial-scale=1" />',
f" <title>{e(title)}</title>",
f' <meta name="description" content="{e(description)}" />',
' <meta name="theme-color" content="#0a0a0a" />',
' <link rel="preconnect" href="https://fonts.googleapis.com" />',
' <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />',
' <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500;700;800&display=swap" rel="stylesheet" />',
f' <link rel="stylesheet" href="{e(css_path)}" />',
]
if favicon:
meta.append(f' <link rel="icon" href="{e(favicon)}" type="image/svg+xml" />')
if canonical:
meta.extend(
[
f' <link rel="canonical" href="{e(canonical)}" />',
f' <meta property="og:url" content="{e(canonical)}" />',
' <meta property="og:type" content="website" />',
f' <meta property="og:title" content="{e(title)}" />',
f' <meta property="og:description" content="{e(description)}" />',
' <meta name="twitter:card" content="summary_large_image" />',
f' <meta name="twitter:title" content="{e(title)}" />',
f' <meta name="twitter:description" content="{e(description)}" />',
]
)
if og_image:
meta.extend(
[
f' <meta property="og:image" content="{e(og_image)}" />',
f' <meta name="twitter:image" content="{e(og_image)}" />',
]
)
return "\n".join(meta)
def command_block(title: str, description: str, code: str, accent: str = "") -> str:
safe_accent = re.sub(r"[^a-z0-9-]", "", accent.lower())
modifier = f" command-card--{safe_accent}" if safe_accent else ""
return (
f'<article class="command-card{modifier} reveal">'
'<div class="command-head">'
f"<div><h2>{e(title)}</h2><p>{e(description)}</p></div>"
f'<button class="copy-button" type="button" data-copy="{e(code)}" aria-label="Copy {e(title)}">copy</button>'
"</div>"
f'<pre><code>{e(code)}</code></pre>'
"</article>"
)
def module_card(item: dict) -> str:
return (
f'<article class="module-card reveal" data-href="{e(item["raw_skill_url"])}">'
'<div class="module-head">'
f'<span class="module-sigil">{e(item["sigil"])}</span>'
'<span class="status">stable</span>'
"</div>"
f'<h3><a href="{e(item["raw_skill_url"])}" target="_blank" rel="noreferrer">{e(item["name"])}</a></h3>'
f'<p>{e(item["description"])}</p>'
'<div class="module-actions">'
f'<button class="icon-button copy-button" type="button" data-copy="{e(item["raw_skill_url"])}" aria-label="Copy raw URL for {e(item["name"])}">cp</button>'
f'<a class="icon-button" href="{e(item["raw_skill_url"])}" target="_blank" rel="noreferrer" aria-label="Open raw SKILL.md for {e(item["name"])}">raw</a>'
f'<a class="icon-button" href="{e(item["github_url"])}" target="_blank" rel="noreferrer" aria-label="Open GitHub page for {e(item["name"])}">gh</a>'
"</div>"
"</article>"
)
def pipeline_step(number: int, name: str, stat: str, note: str) -> str:
return (
'<article class="pipeline-step reveal">'
f'<div class="step-index">{number:02d}</div>'
f"<h3>{e(name)}</h3>"
f'<div class="step-stat">{e(stat)}</div>'
f'<p>{e(note)}</p>'
"</article>"
)
def verify_link(label: str, href: str, meta: str) -> str:
return (
f'<a class="verify-link reveal" href="{e(href)}" target="_blank" rel="noreferrer">'
f'<span class="verify-name">{e(label)}</span>'
f'<span class="verify-meta">{e(meta)}</span>'
"</a>"
)
def scorecard_metric(label: str, value: int | float | None) -> str:
metric_value = fmt_metric(value)
data_value = ""
data_decimals = ""
if isinstance(value, (int, float)):
data_value = f' data-value="{value}"'
decimals = metric_value.partition(".")[2]
data_decimals = f' data-decimals="{len(decimals)}"'
return (
'<article class="score-metric reveal">'
f'<p>{e(label)}</p>'
f'<strong class="count-up"{data_value}{data_decimals}>{e(metric_value)}</strong>'
"</article>"
)
def shared_script() -> str:
return """
<script>
(() => {
const prefersReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
const setCopied = (button) => {
const previous = button.textContent;
button.textContent = 'copied';
button.classList.add('is-copied');
window.setTimeout(() => {
button.textContent = previous;
button.classList.remove('is-copied');
}, 2000);
};
document.addEventListener('click', async (event) => {
const copyButton = event.target.closest('.copy-button');
if (copyButton) {
const text = copyButton.getAttribute('data-copy');
if (text) {
try {
await navigator.clipboard.writeText(text);
setCopied(copyButton);
} catch (_error) {
copyButton.textContent = 'failed';
window.setTimeout(() => {
copyButton.textContent = copyButton.classList.contains('icon-button') ? 'cp' : 'copy';
}, 1500);
}
}
return;
}
const card = event.target.closest('.module-card[data-href]');
if (card && !event.target.closest('a, button')) {
const href = card.getAttribute('data-href');
if (href) {
window.open(href, '_blank', 'noopener,noreferrer');
}
}
});
if (prefersReducedMotion) {
document.querySelectorAll('.reveal').forEach((element) => element.classList.add('is-visible'));
return;
}
const revealObserver = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (!entry.isIntersecting) return;
entry.target.classList.add('is-visible');
revealObserver.unobserve(entry.target);
});
}, { threshold: 0.12, rootMargin: '0px 0px -40px 0px' });
document.querySelectorAll('.reveal').forEach((element) => revealObserver.observe(element));
const countObserver = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (!entry.isIntersecting) return;
const element = entry.target;
const target = Number(element.getAttribute('data-value'));
if (!Number.isFinite(target)) {
countObserver.unobserve(element);
return;
}
const parsedDecimals = Number(element.getAttribute('data-decimals') ?? 0);
const decimals = Number.isFinite(parsedDecimals) && parsedDecimals >= 0 ? parsedDecimals : 0;
const duration = 450;
const start = performance.now();
const tick = (now) => {
const progress = Math.min((now - start) / duration, 1);
const value = target * progress;
element.textContent = value.toFixed(decimals);
if (progress < 1) {
requestAnimationFrame(tick);
} else {
element.textContent = target.toFixed(decimals);
}
};
requestAnimationFrame(tick);
countObserver.unobserve(element);
});
}, { threshold: 0.3 });
document.querySelectorAll('.count-up[data-value]').forEach((element) => countObserver.observe(element));
})();
</script>
""".strip()
def build_index_html(data: dict, domain: str | None) -> str:
counts = data["counts"]
links = data["links"]
scorecard = data["latest_scorecards"].get("realworld") or data["latest_scorecards"].get("deterministic")
stats_bar = "\n".join(
[
f'<span class="stat-pill">{fmt_int(counts["cataloged_audits"])} audits</span>',
f'<span class="stat-pill">{fmt_int(counts["normalized_findings"])} findings</span>',
f'<span class="stat-pill">{fmt_int(counts["skill_modules"])} modules</span>',
'<span class="stat-pill">router</span>',
]
)
modules_html = "\n".join(module_card(item) for item in data["modules"])
pipeline_html = "\n".join(
[
pipeline_step(1, "ingest", fmt_int(counts["cataloged_audits"]), "audit manifests"),
pipeline_step(2, "segment", fmt_int(counts["segmented_audits"]), "segmented corpora"),
pipeline_step(3, "normalize", fmt_int(counts["normalized_findings"]), "normalized findings"),
pipeline_step(4, "distill", fmt_int(counts["distilled_vuln_cards"]), "vuln cards"),
pipeline_step(5, "skillize", fmt_int(counts["skill_modules"]), "published modules"),
]
)
scorecard_html = ""
scorecard_nav = ""
if scorecard:
scorecard_nav = '<a href="#scorecard">scorecard</a>'
scorecard_html = (
'<section class="section section-score reveal" id="scorecard">'
'<div class="section-head">'
'<div><p class="section-kicker">Scorecard</p><h2>Latest run</h2></div>'
f'<a href="{e(scorecard["github_url"])}" target="_blank" rel="noreferrer">open scorecard</a>'
'</div>'
'<div class="score-grid">'
f'{scorecard_metric("cases", scorecard.get("cases"))}'
f'{scorecard_metric("precision", scorecard.get("precision"))}'
f'{scorecard_metric("recall", scorecard.get("recall"))}'
'</div>'
'<p class="section-note">Benchmark snapshot from repo data. Informational only; not a security guarantee.</p>'
'</section>'
)
verify_html = "\n".join(
[
verify_link("quality", links["quality_workflow"], "ci"),
verify_link("evals", links["full_evals_workflow"], "workflow"),
verify_link("held-out", links["heldout_policy"], "policy"),
verify_link("contributing", links["contributing"], "guide"),
verify_link("vuln cards", "vuln-cards/", "index"),
verify_link("site data", "data/site-data.json", "json"),
]
)
primary_command = command_block("Raw URL", "Use the router skill directly.", links["router_skill_raw"], "primary")
secondary_commands = "\n".join(
[
command_block(
"Claude",
"Install in Claude.",
"/plugin marketplace add keep-starknet-strange/starknet-skills\n/plugin install starknet-skills",
),
command_block("Git clone", "Clone the repo locally.", f"git clone {links['repo']}.git"),
]
)
return f"""<!DOCTYPE html>
<html lang="en">
<head>
{head_meta('starkskills', 'Cairo and Starknet skills, audit data, and direct links.', 'assets/site.css', domain, '')}
</head>
<body>
<header class="topbar">
<a class="brand" href="#top">starkskills</a>
<nav class="site-nav" aria-label="Primary navigation">
<a href="#skills">skills</a>
<a href="#data">pipeline</a>
{scorecard_nav}
<a href="#verify">verify</a>
</nav>
<a class="nav-icon" href="{e(links['repo'])}" target="_blank" rel="noreferrer" aria-label="Open GitHub repository">gh</a>
</header>
<main class="shell" id="top">
<section class="hero reveal">
<pre class="ascii-logo" aria-label="STARKSKILLS">{e(ASCII_LOGO)}</pre>
<h1>Cairo and Starknet skills for agents.</h1>
<p class="hero-copy">Plain markdown skills, audit data, and direct links.</p>
<div class="stats-bar">
{stats_bar}
</div>
<div class="hero-install">
{primary_command}
<div class="command-stack">
{secondary_commands}
</div>
</div>
</section>
<section class="section section-card reveal" id="showcase">
<div class="section-head">
<div>
<p class="section-kicker">Example</p>
<h2>cairo-auditor</h2>
</div>
<div class="section-links">
<a href="{e(links['cairo_auditor'])}" target="_blank" rel="noreferrer">skill</a>
<a href="{e(links['cairo_auditor_readme'])}" target="_blank" rel="noreferrer">readme</a>
</div>
</div>
<p class="section-copy">One example module. Discover files, scan patterns, verify findings, write the report.</p>
<ul class="workflow" aria-label="Audit workflow">
<li><span>01</span> discover</li>
<li><span>02</span> scan</li>
<li><span>03</span> verify</li>
<li><span>04</span> report</li>
</ul>
</section>
<section class="section reveal" id="skills">
<div class="section-head">
<div>
<p class="section-kicker">Skills</p>
<h2>Index</h2>
</div>
<div class="section-links">
<a href="{e(links['router_skill_github'])}" target="_blank" rel="noreferrer">router</a>
<button class="copy-button inline-copy" type="button" data-copy="{e(links['router_skill_raw'])}">copy router url</button>
</div>
</div>
<div class="module-grid">
{modules_html}
</div>
</section>
<section class="section reveal" id="data">
<div class="section-head">
<div>
<p class="section-kicker">Pipeline</p>
<h2>Data flow</h2>
</div>
<a href="{e(links['pipeline_readme'])}" target="_blank" rel="noreferrer">datasets</a>
</div>
<div class="pipeline-grid">
{pipeline_html}
</div>
<p class="section-note">Counts are generated from repo data at build time.</p>
</section>
{scorecard_html}
<section class="section reveal" id="verify">
<div class="section-head">
<div>
<p class="section-kicker">Verify</p>
<h2>Repo links</h2>
</div>
<a href="vuln-cards/">vuln cards</a>
</div>
<div class="verify-grid">
{verify_html}
</div>
</section>
</main>
<footer class="footer">
<div class="footer-links">
<a href="{e(links['license'])}" target="_blank" rel="noreferrer">MIT License</a>
<a href="{e(links['repo'])}" target="_blank" rel="noreferrer">GitHub</a>
<a href="{e(links['contributing'])}" target="_blank" rel="noreferrer">Contributing</a>
</div>
<div class="fingerprint">$ fingerprint {e(data['source_fingerprint'])}</div>
</footer>
{shared_script()}
</body>
</html>
"""
def build_vuln_cards_html(data: dict, domain: str | None) -> str:
repo_github = data["links"]["repo"]
rows = []
for card in data["vuln_cards"]:
rows.append(
'<article class="vuln-card reveal">'
'<div class="vuln-head">'
f"<h3><a href=\"{e(card['github_url'])}\" target=\"_blank\" rel=\"noreferrer\">{e(card['name'])}</a></h3>"
f"<div>{severity_badges(card['severity_distribution'])}</div>"
"</div>"
'<p class="meta-label">Trigger</p>'
f"<p>{e(card['trigger'])}</p>"
'<p class="meta-label">Detection</p>'
f"<p>{e(card['detection_rule'])}</p>"
'<p class="meta-label">Findings</p>'
f"<div>{source_finding_links(card['source_findings'], repo_github)}</div>"
"</article>"
)
row_markup = "\n".join(rows) if rows else '<article class="vuln-card"><p>No vuln cards published yet.</p></article>'
counts = data["counts"]
links = data["links"]
return f"""<!DOCTYPE html>
<html lang="en">
<head>
{head_meta('starkskills | vuln cards', 'Distilled vulnerability cards from Starknet audit findings.', '../assets/site.css', domain, 'vuln-cards/')}
</head>
<body>
<header class="topbar">
<a class="brand" href="../">starkskills</a>
<nav class="site-nav" aria-label="Secondary navigation">
<a href="../#skills">skills</a>
<a href="../#verify">verify</a>
<a href="../">home</a>
</nav>
<a class="nav-icon" href="{e(links['vuln_cards_dir'])}" target="_blank" rel="noreferrer" aria-label="Open vulnerability cards directory">gh</a>
</header>
<main class="shell">
<section class="hero reveal">
<pre class="ascii-logo ascii-logo--small" aria-label="STARKSKILLS">{e(ASCII_LOGO)}</pre>
<h1>Vuln cards.</h1>
<p class="hero-copy">Distilled classes from normalized findings.</p>
<div class="stats-bar">
<span class="stat-pill">{fmt_int(counts['distilled_vuln_cards'])} cards</span>
<span class="stat-pill">{fmt_int(counts['normalized_findings'])} findings</span>
<span class="stat-pill">{fmt_int(counts['cataloged_audits'])} audits</span>
</div>
</section>
<section class="section reveal">
<div class="section-head">
<div>
<p class="section-kicker">Index</p>
<h2>Browse</h2>
</div>
<a href="{e(links['vuln_cards_dir'])}" target="_blank" rel="noreferrer">repo dir</a>
</div>
<div class="vuln-grid">
{row_markup}
</div>
</section>
</main>
<footer class="footer">
<div class="footer-links">
<a href="../">Home</a>
<a href="{e(links['repo'])}" target="_blank" rel="noreferrer">GitHub</a>
<a href="../data/site-data.json">site-data.json</a>
</div>
<div class="fingerprint">$ fingerprint {e(data['source_fingerprint'])}</div>
</footer>
{shared_script()}
</body>
</html>
"""
def build_og_card_svg(domain: str | None) -> str:
label = domain or "starkskills"
logo_lines = " ".join(html.escape(line) for line in ASCII_LOGO.splitlines()[:3])
return f"""<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="630" viewBox="0 0 1200 630" role="img" aria-label="starkskills">
<rect width="1200" height="630" fill="#0a0a0a"/>
<rect x="56" y="56" width="1088" height="518" rx="20" fill="#101010" stroke="#242424"/>
<text x="88" y="140" font-family="monospace" font-size="26" fill="#00d4aa" xml:space="preserve">{logo_lines}</text>
<text x="88" y="340" font-family="monospace" font-size="38" fill="#e0e0e0">Cairo and Starknet skills for agents.</text>
<text x="88" y="392" font-family="sans-serif" font-size="26" fill="#a0a0a0">Plain markdown skills, audit data, and direct links.</text>
<text x="88" y="500" font-family="monospace" font-size="24" fill="#00d4aa">{html.escape(label)}</text>
</svg>
"""
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--repo-root",
default=".",
help="Path to repository root (default: current directory)",
)
parser.add_argument(
"--domain",
default=None,
help="Optional production domain to write into website/CNAME",
)
parser.add_argument(
"--repo-slug",
default=DEFAULT_REPO_SLUG,
help="Repository slug used for generated links (OWNER/REPO).",
)
parser.add_argument(
"--repo-ref",
default=DEFAULT_REPO_REF,
help="Repository ref used for generated links (branch, tag, or commit).",
)
args = parser.parse_args()
root = Path(args.repo_root).resolve()
website = root / "website"
cname_path = website / "CNAME"
try:
repo_slug = normalize_repo_slug(args.repo_slug)
repo_ref = normalize_repo_ref(args.repo_ref)
except ValueError as exc:
raise SystemExit(f"[build_site] {exc}") from exc
try:
domain = normalize_domain(args.domain)
except ValueError as exc:
if cname_path.exists():
cname_path.unlink()
raise SystemExit(f"[build_site] {exc}") from exc
data = build_dataset(root, repo_slug=repo_slug, repo_ref=repo_ref)
(website / "assets").mkdir(parents=True, exist_ok=True)
(website / "data").mkdir(parents=True, exist_ok=True)
(website / "vuln-cards").mkdir(parents=True, exist_ok=True)
(website / "data/site-data.json").write_text(
json.dumps(data, indent=2, sort_keys=True) + "\n",
encoding="utf-8",
)
(website / "index.html").write_text(build_index_html(data, domain), encoding="utf-8")
(website / "vuln-cards/index.html").write_text(build_vuln_cards_html(data, domain), encoding="utf-8")
(website / "assets/og-card.svg").write_text(build_og_card_svg(domain), encoding="utf-8")
# Ensure GitHub Pages serves paths literally and applies custom domain when configured.
(website / ".nojekyll").write_text("\n", encoding="utf-8")
if domain:
cname_path.write_text(domain + "\n", encoding="utf-8")
elif cname_path.exists():
cname_path.unlink()
if __name__ == "__main__":
main()