Repository navigation
Expand file tree
/
Copy pathvalidate.ts
More file actions
787 lines (717 loc) · 29 KB
/
Copy pathvalidate.ts
File metadata and controls
787 lines (717 loc) · 29 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
// CLI: yarn validate
// Static skill validation. Exits 0 on success, 1 if any error-level finding.
//
// Implements priority-1.A of README's foundational-quality TODO + the distribution-layer
// release guardrails:
// - SKILL.md frontmatter (name, description, length, version).
// - Internal links resolve across SKILL/README/developers/references/examples.
// - No hardcoded author-local paths (/Users/<x>/..., /home/<x>/...).
// - No committed secrets or vendored deps.
// - Address-set parity: scripts/src/config/addresses.ts ⊆ README.md ⊆ references/addresses.md.
// - Subgraph URLs (v2, v3, ve) consistent across docs, config, manifest and .env.example.
// - skill.json manifest is present, valid JSON, has install/update/verify commands,
// and its `version` matches SKILL.md frontmatter (release-time parity).
// - Brand channel URLs appear on every front-door surface (README, SKILL, references/brand.md).
import * as fs from "node:fs";
import * as path from "node:path";
import { execSync } from "node:child_process";
import { fileURLToPath } from "node:url";
import { getAddress } from "ethers";
import { BRAND } from "../config/brand.js";
import {
parseEvalSpec,
discoverEvalFiles,
EvalSpecError,
OUTPUT_KINDS,
} from "../lib/evalSpec.js";
const SELF_FILE = fileURLToPath(import.meta.url);
const SCRIPTS_DIR = path.resolve(path.dirname(SELF_FILE), "../..");
const REPO_ROOT = path.resolve(SCRIPTS_DIR, "..");
// Include new skill files before staging, but exclude ignored dependencies, env files and build artifacts.
const TRACKED_FILES: Set<string> = (() => {
const out = execSync("git ls-files --cached --others --exclude-standard", { cwd: REPO_ROOT, encoding: "utf8" });
return new Set(
out
.split("\n")
.map((l) => l.trim())
.filter(Boolean)
.map((rel) => path.resolve(REPO_ROOT, rel)),
);
})();
const isTracked = (abs: string): boolean => TRACKED_FILES.has(path.resolve(abs));
type Severity = "error" | "warn";
interface Finding {
severity: Severity;
file: string;
line?: number;
msg: string;
}
const FINDINGS: Finding[] = [];
const repoRel = (abs: string): string =>
path.relative(REPO_ROOT, abs) || path.basename(abs);
const error = (file: string, msg: string, line?: number): void => {
FINDINGS.push({ severity: "error", file, msg, line });
};
const warn = (file: string, msg: string, line?: number): void => {
FINDINGS.push({ severity: "warn", file, msg, line });
};
const readText = (abs: string): string => fs.readFileSync(abs, "utf8");
const walkDir = (
dir: string,
match: (name: string) => boolean,
out: string[] = [],
skip: Set<string> = new Set(["node_modules", ".git", "dist", "build", ".yarn"]),
): string[] => {
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
if (skip.has(entry.name)) continue;
const abs = path.join(dir, entry.name);
if (entry.isDirectory()) {
walkDir(abs, match, out, skip);
} else if (entry.isFile() && match(entry.name)) {
out.push(abs);
}
}
return out;
};
const MD_FILES_TO_LINK_CHECK = (): string[] =>
Array.from(TRACKED_FILES).filter((f) => f.endsWith(".md"));
const lineOf = (text: string, idx: number): number =>
text.slice(0, idx).split("\n").length;
// --- A1. SKILL.md frontmatter ---
// Agent-skill convention (Anthropic Skills, Hermes, and most agent runtimes that read
// SKILL.md frontmatter) requires name + description; description ≤ 1024 chars.
const SKILL_DESCRIPTION_MAX = 1024;
interface Frontmatter {
name?: string;
description?: string;
version?: string;
license?: string;
raw?: string;
}
const parseFrontmatter = (md: string): Frontmatter => {
const m = md.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n/);
if (!m) return {};
const raw = m[1];
const fields: Record<string, string> = {};
for (const line of raw.split(/\r?\n/)) {
const kv = line.match(/^([A-Za-z_][\w-]*)\s*:\s*(.*)$/);
if (!kv) continue;
fields[kv[1]] = kv[2].trim();
}
return {
name: fields.name,
description: fields.description,
version: fields.version,
license: fields.license,
raw,
};
};
const checkFrontmatter = (): void => {
const skillPath = path.join(REPO_ROOT, "SKILL.md");
const md = readText(skillPath);
const fm = parseFrontmatter(md);
if (!fm.raw) {
error(repoRel(skillPath), "missing YAML frontmatter (expected `---` … `---` at top of file)");
return;
}
if (!fm.name) error(repoRel(skillPath), "frontmatter missing `name`");
if (!fm.description) error(repoRel(skillPath), "frontmatter missing `description`");
if (fm.description && fm.description.length > SKILL_DESCRIPTION_MAX) {
error(
repoRel(skillPath),
`frontmatter \`description\` is ${fm.description.length} chars; limit is ${SKILL_DESCRIPTION_MAX}`,
);
}
};
// --- A2. Internal links resolve ---
// Markdown links: [text](url) — skip http/https/mailto/anchor-only/empty.
// Also scan inline backticked paths that look like internal refs.
const isExternalOrAnchor = (url: string): boolean =>
/^(?:https?:|mailto:|#|tel:|data:)/.test(url) || url === "" || url.startsWith("~/");
// Strip ?query / #anchor for filesystem resolution.
const stripQueryAndAnchor = (url: string): string => url.split(/[?#]/)[0];
// Replace fenced code blocks (```...```) with spaces of matching length so line numbers
// stay accurate but markdown-link / backtick-path scanning ignores embedded source.
const maskFencedCode = (text: string): string =>
text.replace(/```[\s\S]*?```/g, (block) => block.replace(/[^\n]/g, " "));
const checkInternalLinks = (): void => {
const linkRe = /\[([^\]]*)\]\(([^)]+)\)/g;
const backtickRe = /`([^`\n]+)`/g;
// Backticked content treated as a candidate path when it:
// - is not a URL, not a 0x... address, not a `~/...` source pointer, not a code snippet
// - looks like a real path (contains `/` and ends with .md/.ts/.json/.sol)
// We only check paths inside `references/`, `developers/`, `examples/`, `scripts/` — relative paths
// typed in nav tables.
const isCandidateBacktickPath = (s: string): boolean => {
if (s.startsWith("0x") || s.startsWith("~/") || s.startsWith("/")) return false;
if (s.includes(" ")) return false; // not a path
if (s.includes("://")) return false;
if (s.includes("*")) return false; // glob describing a set, not a real path
if (/^[A-Z_][A-Z0-9_]*$/.test(s)) return false; // CONSTANT
if (/\(.*\)$/.test(s)) return false; // function call
if (!s.includes("/")) return false;
if (!/\.(md|ts|tsx|json|sol|py|graphql)$/.test(s)) return false;
return /^(?:\.\/|\.\.\/)?(references|developers|examples|scripts|sdk)\//.test(s);
};
for (const file of MD_FILES_TO_LINK_CHECK()) {
const raw = readText(file);
const noFence = maskFencedCode(raw);
// For link detection, also mask inline backtick spans so embedded code (which
// can contain `[...](...)` shapes) doesn't trigger false positives.
const linkText = noFence.replace(/`[^`\n]+`/g, (s) => s.replace(/[^\n]/g, " "));
const dir = path.dirname(file);
let m: RegExpExecArray | null;
linkRe.lastIndex = 0;
while ((m = linkRe.exec(linkText)) !== null) {
const url = m[2].trim();
if (isExternalOrAnchor(url)) continue;
const target = stripQueryAndAnchor(url);
const resolved = path.resolve(dir, target);
if (!fs.existsSync(resolved)) {
error(repoRel(file), `broken link → \`${url}\``, lineOf(linkText, m.index));
}
}
backtickRe.lastIndex = 0;
while ((m = backtickRe.exec(noFence)) !== null) {
const candidate = m[1].trim();
if (!isCandidateBacktickPath(candidate)) continue;
const resolved = path.resolve(dir, candidate);
if (!fs.existsSync(resolved)) {
// Try resolving from repo root — many nav tables list paths relative to root.
const alt = path.resolve(REPO_ROOT, candidate);
if (!fs.existsSync(alt)) {
error(repoRel(file), `backticked path does not resolve → \`${candidate}\``, lineOf(noFence, m.index));
}
}
}
}
};
// --- A3. No hardcoded author-local paths ---
// Allowed: ~/<...> shell shorthand. Banned: /Users/<real-name>/..., /home/<real-name>/...
// Placeholder usernames in meta-documentation (`foo`, `bar`, `someone`, `<name>`, ...) are skipped.
const AUTHOR_PATH_RE = /\/(?:Users|home)\/([A-Za-z0-9_.-]+|<[^>]+>)\//g;
const PLACEHOLDER_USERS = new Set([
"foo", "bar", "baz", "qux", "someone", "someuser", "user", "username",
"your-username", "you", "yourname",
]);
const checkAuthorPaths = (): void => {
for (const file of TRACKED_FILES) {
if (path.resolve(file) === path.resolve(SELF_FILE)) continue;
if (!/\.(md|ts|tsx|json|sh|yaml|yml)$|\.env\.example$/.test(file)) continue;
const text = readText(file);
AUTHOR_PATH_RE.lastIndex = 0;
let m: RegExpExecArray | null;
while ((m = AUTHOR_PATH_RE.exec(text)) !== null) {
const user = m[1];
if (user.startsWith("<") && user.endsWith(">")) continue; // <name> placeholder
if (PLACEHOLDER_USERS.has(user)) continue;
error(
repoRel(file),
`hardcoded author-local path \`${m[0]}\` (use \`~/\` or a project-relative path)`,
lineOf(text, m.index),
);
}
}
};
// --- A3b. No external-repo source pointers ---
// Pointers like `~/topaz/topaz-{contracts,slipstream,interface,v2-subgraph,v3-subgraph}/...`
// are valid only on the author's machine. They belong in `.claude/INTERNAL-SOURCE-POINTERS.md`
// (gitignored), not in public skill files. `~/topaz/topaz-skill/...` is permitted because that
// is THIS skill (users can install it under that path or elsewhere).
const EXTERNAL_REPO_RE = /~\/topaz\/topaz-(contracts|slipstream|interface|v2-subgraph|v3-subgraph)\//g;
const checkNoExternalRepoPointers = (): void => {
for (const file of TRACKED_FILES) {
if (path.resolve(file) === path.resolve(SELF_FILE)) continue;
if (!/\.(md|ts|tsx|json|sh|yaml|yml)$|\.env\.example$/.test(file)) continue;
const text = readText(file);
EXTERNAL_REPO_RE.lastIndex = 0;
let m: RegExpExecArray | null;
while ((m = EXTERNAL_REPO_RE.exec(text)) !== null) {
error(
repoRel(file),
`external-repo source pointer \`${m[0]}\` — move to .claude/INTERNAL-SOURCE-POINTERS.md (gitignored)`,
lineOf(text, m.index),
);
}
}
};
// --- A4. No committed secrets / vendored deps ---
const SECRET_BASENAMES = /^(\.env|\.env\.[^.]+|id_rsa(\.pub)?|id_ed25519(\.pub)?|.*\.pem|.*\.key|.*\.keystore)$/;
const VENDOR_BASENAMES_DIR = new Set(["node_modules"]);
const VENDOR_FILE_RE = /^\.pnp\..+$/;
// Yarn 4 caches under .yarn/ that should never be committed (releases/plugins/patches are OK).
const YARN_CACHE_PATHS = [
/(?:^|\/)\.yarn\/cache(?:\/|$)/,
/(?:^|\/)\.yarn\/unplugged(?:\/|$)/,
/(?:^|\/)\.yarn\/build-state\.yml$/,
/(?:^|\/)\.yarn\/install-state\.gz$/,
];
const checkSecretsAndVendored = (): void => {
for (const abs of TRACKED_FILES) {
const base = path.basename(abs);
const rel = path.relative(REPO_ROOT, abs);
if (base === ".env.example") continue;
if (SECRET_BASENAMES.test(base)) {
error(repoRel(abs), `secret-shaped tracked file (\`${base}\`)`);
}
if (VENDOR_FILE_RE.test(base)) {
error(repoRel(abs), `vendored dep artifact tracked in git (\`${base}\`)`);
}
const parts = rel.split(path.sep);
if (parts.some((p) => VENDOR_BASENAMES_DIR.has(p))) {
error(repoRel(abs), "tracked file inside a vendored-dependency directory");
}
if (YARN_CACHE_PATHS.some((re) => re.test(rel))) {
error(repoRel(abs), "yarn cache artifact tracked in git (should be gitignored)");
}
}
};
// --- A5. Address-set parity ---
// addresses.ts is canonical. Every address declared there MUST appear in both README.md and
// references/addresses.md (case-insensitive). Docs may carry extra addresses (libraries, legacy)
// that the TS config does not export — those are warnings, not errors.
const ADDR_RE = /0x[a-fA-F0-9]{40}/g;
const ADDR_KV_RE = /^\s*([A-Za-z_][\w]*)\s*:\s*["'](0x[a-fA-F0-9]{40})["']/gm;
const parseAddrConfig = (): Map<string, string> => {
const file = path.join(SCRIPTS_DIR, "src/config/addresses.ts");
const text = readText(file);
const out = new Map<string, string>();
ADDR_KV_RE.lastIndex = 0;
let m: RegExpExecArray | null;
while ((m = ADDR_KV_RE.exec(text)) !== null) {
out.set(m[1], m[2].toLowerCase());
}
return out;
};
const extractAddressesFromMarkdown = (file: string): Set<string> => {
const text = readText(file);
const set = new Set<string>();
let m: RegExpExecArray | null;
ADDR_RE.lastIndex = 0;
while ((m = ADDR_RE.exec(text)) !== null) {
set.add(m[0].toLowerCase());
}
return set;
};
const checkAddressParity = (): void => {
const config = parseAddrConfig();
if (config.size === 0) {
error("scripts/src/config/addresses.ts", "no addresses parsed — ADDR object missing or regex mismatch");
return;
}
const readmeAddrs = extractAddressesFromMarkdown(path.join(REPO_ROOT, "README.md"));
const refAddrs = extractAddressesFromMarkdown(path.join(REPO_ROOT, "references/addresses.md"));
for (const [name, addr] of config) {
if (!readmeAddrs.has(addr)) {
error(
"README.md",
`address for \`ADDR.${name}\` (${addr}) is in scripts/src/config/addresses.ts but not in README.md`,
);
}
if (!refAddrs.has(addr)) {
error(
"references/addresses.md",
`address for \`ADDR.${name}\` (${addr}) is in scripts/src/config/addresses.ts but not in references/addresses.md`,
);
}
}
// Doc-only addresses (libraries, legacy) → warn so we notice drift.
const configAddrs = new Set(Array.from(config.values()));
for (const a of readmeAddrs) {
if (!configAddrs.has(a)) {
warn("README.md", `address \`${a}\` appears in README.md but not in scripts/src/config/addresses.ts`);
}
}
for (const a of refAddrs) {
if (!configAddrs.has(a)) {
warn(
"references/addresses.md",
`address \`${a}\` appears in references/addresses.md but not in scripts/src/config/addresses.ts`,
);
}
}
};
// --- A5b. EIP-55 checksum validity ---
// Every mixed-case 0x-address in the canonical files must be a valid EIP-55 checksum.
// All-lowercase or all-uppercase variants are skipped (legal per spec, just not checksummed).
const CHECKSUM_TARGET_FILES = [
"scripts/src/config/addresses.ts",
"scripts/src/config/tokens.ts",
"README.md",
"references/addresses.md",
"references/tokens.md",
"SKILL.md",
];
const isMixedCaseHex = (a: string): boolean => {
const hex = a.slice(2);
return /[a-f]/.test(hex) && /[A-F]/.test(hex);
};
const checkChecksums = (): void => {
for (const rel of CHECKSUM_TARGET_FILES) {
const abs = path.join(REPO_ROOT, rel);
if (!fs.existsSync(abs)) continue;
const text = readText(abs);
const seen = new Set<string>();
ADDR_RE.lastIndex = 0;
let m: RegExpExecArray | null;
while ((m = ADDR_RE.exec(text)) !== null) {
const a = m[0];
if (!isMixedCaseHex(a)) continue;
if (seen.has(a)) continue;
seen.add(a);
try {
const canonical = getAddress(a.toLowerCase());
if (a !== canonical) {
error(
rel,
`bad EIP-55 checksum \`${a}\` — should be \`${canonical}\``,
lineOf(text, m.index),
);
}
} catch {
error(rel, `invalid address \`${a}\``, lineOf(text, m.index));
}
}
}
};
// --- A6. Subgraph URL consistency ---
const SUBGRAPH_V2_RE = /https:\/\/api\.goldsky\.com\/api\/public\/[^\s)`'"]+subgraphs\/topaz-v2\/[^\s)`'"]+/g;
const SUBGRAPH_V3_RE = /https:\/\/api\.goldsky\.com\/api\/public\/[^\s)`'"]+subgraphs\/topaz-v3\/[^\s)`'"]+/g;
const SUBGRAPH_VE_RE = /https:\/\/api\.goldsky\.com\/api\/public\/[^\s)`'"]+subgraphs\/topaz-ve\/[^\s)`'"]+/g;
const SUBGRAPH_PATTERNS: ReadonlyArray<{ label: string; re: RegExp }> = [
{ label: "v2", re: SUBGRAPH_V2_RE },
{ label: "v3", re: SUBGRAPH_V3_RE },
{ label: "ve", re: SUBGRAPH_VE_RE },
];
const REQUIRED_SUBGRAPH_FILES = [
"README.md",
"SKILL.md",
"skill.json",
"scripts/.env.example",
"scripts/src/lib/subgraph.ts",
"developers/subgraph-recipes.md",
"developers/DEVELOPERS.md",
"references/analytics-subgraph.md",
];
const checkSubgraphUrls = (): void => {
const found = new Map<string, Set<string>>(SUBGRAPH_PATTERNS.map((p) => [p.label, new Set<string>()]));
for (const rel of REQUIRED_SUBGRAPH_FILES) {
const abs = path.join(REPO_ROOT, rel);
if (!fs.existsSync(abs)) {
error(rel, "expected file does not exist (subgraph-consistency check)");
continue;
}
const text = readText(abs);
for (const { label, re } of SUBGRAPH_PATTERNS) {
const urls = text.match(re) ?? [];
if (urls.length === 0) warn(rel, `no ${label} subgraph URL found`);
for (const u of urls) found.get(label)!.add(u);
}
}
for (const { label } of SUBGRAPH_PATTERNS) {
const uniq = found.get(label)!;
if (uniq.size > 1) {
error("subgraph", `${label} subgraph URL drift: ${Array.from(uniq).join(" | ")}`);
}
}
};
// --- A6b. skill.json manifest + version parity ---
// skill.json must exist at repo root, parse as JSON, declare the required fields,
// and its `version` must equal the `version` declared in SKILL.md's frontmatter.
// This is the single guardrail that catches "released v1.1.0 but forgot to bump
// the manifest" before it ships.
interface SkillManifest {
schema_version?: string;
name?: string;
version?: string;
description?: string;
repository?: string;
install?: { command?: string };
update?: { command?: string };
verify?: { commands?: string[] };
}
const checkSkillManifest = (): void => {
const manifestPath = path.join(REPO_ROOT, "skill.json");
if (!fs.existsSync(manifestPath)) {
error("skill.json", "skill.json is missing at repo root (distribution manifest)");
return;
}
let parsed: SkillManifest;
try {
parsed = JSON.parse(readText(manifestPath)) as SkillManifest;
} catch (e) {
error("skill.json", `skill.json is not valid JSON: ${(e as Error).message}`);
return;
}
const required: (keyof SkillManifest)[] = [
"schema_version",
"name",
"version",
"description",
"repository",
];
for (const k of required) {
if (!parsed[k]) error("skill.json", `missing required field \`${k}\``);
}
if (!parsed.install?.command) error("skill.json", "missing `install.command`");
if (!parsed.update?.command) error("skill.json", "missing `update.command`");
if (!parsed.verify?.commands || parsed.verify.commands.length === 0) {
error("skill.json", "missing `verify.commands` (at least one verification command expected)");
}
// skill.json.name must equal SKILL.md frontmatter `name`.
const skillPath = path.join(REPO_ROOT, "SKILL.md");
const fm = parseFrontmatter(readText(skillPath));
if (parsed.name && fm.name && parsed.name !== fm.name) {
error(
"skill.json",
`name drift: SKILL.md declares \`${fm.name}\`, skill.json declares \`${parsed.name}\``,
);
}
// Version parity: skill.json.version === SKILL.md frontmatter `version`.
// SKILL.md's frontmatter parser is flat, so a top-level `version: x.y.z` line is required.
const skillVersion = fm.version;
if (!skillVersion) {
error("SKILL.md", "frontmatter missing top-level `version` (required for release parity with skill.json)");
} else if (parsed.version && parsed.version !== skillVersion) {
error(
"skill.json",
`version drift: SKILL.md declares \`${skillVersion}\`, skill.json declares \`${parsed.version}\``,
);
}
// README.md "Current version" line must match. The release CLI bumps this line,
// but a hand-edit could drift — this catches it.
const readmePath = path.join(REPO_ROOT, "README.md");
if (parsed.version && fs.existsSync(readmePath)) {
const readmeText = readText(readmePath);
const m = readmeText.match(/\*\*Current version:\*\*\s+`([^`]+)`/);
if (!m) {
error(
"README.md",
"missing the `**Current version:** \\`X.Y.Z\\`` marker (release.ts uses this to bump README in sync with SKILL.md / skill.json)",
);
} else if (m[1] !== parsed.version) {
error(
"README.md",
`version drift: README.md declares \`${m[1]}\`, skill.json declares \`${parsed.version}\``,
);
}
}
// CHANGELOG should mention the current version so we never tag without release notes.
const changelogPath = path.join(REPO_ROOT, "CHANGELOG.md");
if (parsed.version && fs.existsSync(changelogPath)) {
const cl = readText(changelogPath);
const versionHeading = new RegExp(`^##\\s*\\[?${parsed.version.replace(/\./g, "\\.")}\\]?`, "m");
if (!versionHeading.test(cl)) {
warn(
"CHANGELOG.md",
`no \`## [${parsed.version}]\` (or \`## ${parsed.version}\`) section found — add release notes before tagging`,
);
}
} else if (!fs.existsSync(changelogPath)) {
warn("CHANGELOG.md", "no CHANGELOG.md at repo root (recommended for releases)");
}
};
// --- A7. Brand URL parity ---
// Channel URLs (web/docs/socials/github/assetsRepo) must appear in every "front door"
// surface — README.md, SKILL.md, and references/brand.md.
// Asset deep-links (logoPng, logoSvg, ...) only need to appear in references/brand.md;
// requiring them in README/SKILL would just be clutter.
const BRAND_FRONT_DOOR_FILES = ["README.md", "SKILL.md", "references/brand.md"];
const BRAND_ASSET_HOME = "references/brand.md";
const collectChannelUrls = (): string[] => {
const out: string[] = [];
for (const [key, v] of Object.entries(BRAND)) {
if (key === "assets") continue;
if (typeof v === "string" && v.startsWith("http")) out.push(v);
}
return out;
};
const collectAssetUrls = (): string[] =>
Object.values(BRAND.assets).filter((v) => typeof v === "string" && v.startsWith("http"));
const checkBrandUrls = (): void => {
const channelUrls = collectChannelUrls();
for (const rel of BRAND_FRONT_DOOR_FILES) {
const abs = path.join(REPO_ROOT, rel);
if (!fs.existsSync(abs)) {
error(rel, "expected file does not exist (brand-URL parity check)");
continue;
}
const text = readText(abs);
for (const url of channelUrls) {
if (!text.includes(url)) {
error(rel, `BRAND channel URL \`${url}\` is in scripts/src/config/brand.ts but not in ${rel}`);
}
}
}
const assetText = fs.existsSync(path.join(REPO_ROOT, BRAND_ASSET_HOME))
? readText(path.join(REPO_ROOT, BRAND_ASSET_HOME))
: "";
for (const url of collectAssetUrls()) {
if (!assetText.includes(url)) {
error(
BRAND_ASSET_HOME,
`BRAND asset URL \`${url}\` is in scripts/src/config/brand.ts but not in ${BRAND_ASSET_HOME}`,
);
}
}
};
// --- A8. Eval assertion blocks ---
// Every evals/NN-*.md must have a parseable ```yaml assertions: ...``` block.
// output_kind must be a comma-separated list of OUTPUT_KINDS values; regex
// patterns must compile. This is what makes priority-1.G evals runnable
// without per-merge human review of each YAML block.
const validateRegex = (file: string, field: string, patterns: string[]): void => {
for (const [i, p] of patterns.entries()) {
try {
new RegExp(p, "i");
} catch (e) {
error(`evals/${file}`, `\`${field}[${i}]\`: invalid regex — ${(e as Error).message}`);
}
}
};
const checkEvalAssertions = (): void => {
const evalsDir = path.join(REPO_ROOT, "evals");
if (!fs.existsSync(evalsDir)) {
error("evals/", "directory missing");
return;
}
const files = discoverEvalFiles(evalsDir);
if (files.length === 0) {
warn("evals/", "no eval files found (expected evals/NN-*.md)");
return;
}
for (const abs of files) {
try {
const spec = parseEvalSpec(abs);
if (spec.cases.length === 0) {
error(`evals/${spec.filename}`, "no cases parsed from assertions block");
continue;
}
for (const c of spec.cases) {
if (c.outputKind.length === 0) {
error(`evals/${spec.filename}`, `case \`${c.id}\`: output_kind is empty`);
}
for (const k of c.outputKind) {
if (!OUTPUT_KINDS.includes(k)) {
error(
`evals/${spec.filename}`,
`case \`${c.id}\`: unknown output_kind \`${k}\``,
);
}
}
if (c.prompt.trim() === "") {
error(`evals/${spec.filename}`, `case \`${c.id}\`: empty prompt`);
}
validateRegex(spec.filename, `cases[${c.id}].expected_tool_calls`, c.expectedToolCalls);
validateRegex(spec.filename, `cases[${c.id}].forbidden_tool_calls`, c.forbiddenToolCalls);
validateRegex(spec.filename, `cases[${c.id}].must_include`, c.mustInclude);
validateRegex(spec.filename, `cases[${c.id}].must_not_include`, c.mustNotInclude);
}
} catch (e) {
if (e instanceof EvalSpecError) {
error(`evals/${path.basename(abs)}`, e.message.replace(/^[^:]+:\s*/, ""));
} else {
error(`evals/${path.basename(abs)}`, `unexpected error: ${(e as Error).message}`);
}
}
}
};
// --- Documented helper names ---
// Docs that point at `scripts/src/<file>.ts` and name a function, or import names from the
// scripts package, must use names that exist. Catches invented helpers and stale renames.
const SCRIPT_SRC_RE = /(?:scripts\/)?src\/((?:lib|read|write|config|cli)\/[\w]+)\.ts/g;
const DOC_IMPORT_RE = /import\s*\{([^}]*)\}\s*from\s*["'][^"']*(?:\bsrc\b|scripts)[^"']*["']/g;
const DECLARED_RE = (name: string): RegExp =>
new RegExp(`(?:function\\*?|const|let|class|interface|type|enum)\\s+${name}\\b`);
const checkDocumentedHelpers = (): void => {
const srcRoot = path.join(SCRIPTS_DIR, "src");
const sources = new Map<string, string>();
for (const abs of walkDir(srcRoot, (f) => f.endsWith(".ts") && !f.endsWith(".test.ts"))) {
sources.set(path.relative(srcRoot, abs).replace(/\\/g, "/").replace(/\.ts$/, ""), readText(abs));
}
const all = Array.from(sources.values()).join("\n");
const exported = new Set(Array.from(all.matchAll(/export\s+(?:async\s+)?(?:function\*?|const|let|class|interface|type|enum)\s+(\w+)/g), (m) => m[1]));
for (const m of all.matchAll(/export\s*\{([^}]*)\}/g)) for (const n of m[1].matchAll(/\b(\w+)\b(?!\s+as\b)/g)) exported.add(n[1]);
for (const abs of MD_FILES_TO_LINK_CHECK()) {
const rel = repoRel(abs);
if (rel === "CHANGELOG.md" || rel.startsWith("docs/ai-wallet-agent-review")) continue;
const text = readText(abs);
for (const m of text.matchAll(DOC_IMPORT_RE)) {
for (const n of m[1].replace(/\/\/[^\n]*/g, "").matchAll(/\b([A-Za-z_]\w*)\b/g)) {
if (n[1] === "type" || exported.has(n[1])) continue;
error(rel, `imports \`${n[1]}\` from the scripts package, which exports no such name`, lineOf(text, m.index ?? 0));
}
}
text.split("\n").forEach((line, i) => {
for (const cell of line.split("|")) {
for (const pm of cell.matchAll(SCRIPT_SRC_RE)) {
const source = sources.get(pm[1]);
if (source === undefined) {
error(rel, `references scripts/src/${pm[1]}.ts, which does not exist`, i + 1);
continue;
}
const after = cell.slice((pm.index ?? 0) + pm[0].length);
const names = [
...Array.from(after.matchAll(/^:([a-z][A-Za-z0-9]*)\(/g), (x) => x[1]),
...Array.from(after.matchAll(/`([a-z][A-Za-z0-9]*)\(/g), (x) => x[1]),
];
for (const name of names) {
if (DECLARED_RE(name).test(source)) continue;
error(rel, `names \`${name}\` in scripts/src/${pm[1]}.ts, which does not define it`, i + 1);
}
}
}
});
}
};
// --- Run ---
const sectionHeader = (label: string): void => {
console.log(`\n— ${label} —`);
};
sectionHeader("Frontmatter");
checkFrontmatter();
sectionHeader("Internal links");
checkInternalLinks();
sectionHeader("Author-local paths");
checkAuthorPaths();
sectionHeader("External-repo source pointers");
checkNoExternalRepoPointers();
sectionHeader("Secrets and vendored deps");
checkSecretsAndVendored();
sectionHeader("Address parity");
checkAddressParity();
sectionHeader("EIP-55 checksums");
checkChecksums();
sectionHeader("Subgraph URLs");
checkSubgraphUrls();
sectionHeader("Manifest (skill.json)");
checkSkillManifest();
sectionHeader("Brand URLs");
checkBrandUrls();
sectionHeader("Eval assertions");
checkEvalAssertions();
sectionHeader("Documented helper names");
checkDocumentedHelpers();
// --- Report ---
const errors = FINDINGS.filter((f) => f.severity === "error");
const warnings = FINDINGS.filter((f) => f.severity === "warn");
const fmt = (f: Finding): string => {
const at = f.line !== undefined ? `${f.file}:${f.line}` : f.file;
const tag = f.severity === "error" ? "ERR" : "warn";
return ` [${tag}] ${at} — ${f.msg}`;
};
console.log("");
if (warnings.length > 0) {
console.log(`Warnings (${warnings.length}):`);
for (const w of warnings) console.log(fmt(w));
console.log("");
}
if (errors.length > 0) {
console.log(`Errors (${errors.length}):`);
for (const e of errors) console.log(fmt(e));
console.log("");
console.log(`FAIL: ${errors.length} error(s), ${warnings.length} warning(s)`);
process.exit(1);
}
console.log(`OK: 0 errors, ${warnings.length} warning(s)`);
process.exit(0);