返回 CodeWhale
facts-lib.mjs
根目录 / web / scripts / facts-lib.mjs
1 /**
2 * facts-lib.mjs — shared derivation logic for website fact generation and
3 * drift checking. Imported by both derive-facts.mjs (prebuild) and
4 * check-facts.mjs (CI gate).
5 *
6 * Sources of truth:
7 * - <repo>/Cargo.toml → version, workspace crates
8 * - <repo>/crates/sandbox/src/lib.rs → enforced sandbox markers
9 * * - <repo>/crates/config/assets/provider_descriptors.json → provider labels and default model
10 * - <repo>/npm/codewhale/package.json → node engines
11 * - <repo>/crates/engine/src/tools/*.rs → tool count (ToolSpec impls)
12 * - <repo>/LICENSE → license
13 * - <repo>/web/data/latest-published-release.json → latest published release
14 */
15 import { parseModelCatalog } from "../lib/model-catalog.mjs";
16 import { parseProviderDescriptors } from "../lib/provider-descriptors.mjs";
17 import { readFileSync, readdirSync, existsSync } from "node:fs";
18 import { spawnSync } from "node:child_process";
19 import { createHash } from "node:crypto";
20 import { join, dirname, resolve } from "node:path";
21 import { fileURLToPath } from "node:url";
22
23 const __dirname = dirname(fileURLToPath(import.meta.url));
24 // __dirname is web/scripts; REPO_ROOT is the workspace root (two levels up).
25 export const REPO_ROOT = resolve(__dirname, "..", "..");
26
27 function read(rel) {
28 const p = join(REPO_ROOT, rel);
29 if (!existsSync(p)) return null;
30 return readFileSync(p, "utf-8");
31 }
32
33 export function deriveVersion() {
34 const cargo = read("Cargo.toml");
35 if (!cargo) return null;
36 const m = cargo.match(/^version\s*=\s*"([^"]+)"/m);
37 return m ? m[1] : null;
38 }
39
40 export function deriveCrates() {
41 const cargo = read("Cargo.toml");
42 if (!cargo) return [];
43 const block = cargo.match(/members\s*=\s*\[([\s\S]*?)\]/);
44 if (!block) return [];
45 return [...block[1].matchAll(/"crates\/([^"]+)"/g)].map((m) => m[1]).sort();
46 }
47
48 export function deriveSandboxBackends() {
49 const source = read("crates/sandbox/src/lib.rs");
50 return source ? deriveSandboxBackendsFromSource(source) : [];
51 }
52
53 export function deriveSandboxBackendsFromSource(source) {
54 const marker = source.match(
55 /pub const PUBLIC_SANDBOX_BACKENDS\s*:\s*&\[&str\]\s*=\s*&\[([\s\S]*?)\];/,
56 );
57 if (!marker) return [];
58 return [...marker[1].matchAll(/"([^"]+)"/g)].map((match) => match[1]);
59 }
60
61 // Descriptor data owns public identities, order, labels and defaults.
62 const descriptorData = parseProviderDescriptors(read("crates/config/assets/provider_descriptors.json"));
63 export function deriveProviders() {
64 if (!descriptorData) throw new Error("missing or malformed provider descriptors");
65 return descriptorData.providers;
66 }
67
68 export function deriveDefaultModel() {
69 return descriptorData?.defaultModel ?? null;
70 }
71
72 export function deriveNodeEngines() {
73 const pkg = read("npm/codewhale/package.json");
74 if (!pkg) return null;
75 try {
76 return JSON.parse(pkg).engines?.node ?? null;
77 } catch {
78 return null;
79 }
80 }
81
82 // Public model identities, labels and source-support dates share the reviewed
83 // Engine catalog owner. A malformed source cannot become a partial/empty list.
84 export function deriveModels() {
85 const models = parseModelCatalog(read("crates/config/assets/catalog_corrections.json"));
86 if (!models) throw new Error("missing or malformed reviewed model catalog");
87 return models;
88 }
89
90 export function countToolSpecs(bodies) {
91 let count = 0;
92 for (const body of bodies) count += (body.match(/^impl ToolSpec for /gm) ?? []).length;
93 return count > 0 ? count : null;
94 }
95
96 function collectToolSourceBodies(dir) {
97 const bodies = [];
98 for (const entry of readdirSync(dir, { withFileTypes: true })) {
99 if (entry.isDirectory()) {
100 if (entry.name === "tests") continue;
101 bodies.push(...collectToolSourceBodies(join(dir, entry.name)));
102 } else if (
103 entry.isFile() &&
104 entry.name.endsWith(".rs") &&
105 entry.name !== "tests.rs" &&
106 !entry.name.endsWith("_tests.rs") &&
107 !entry.name.startsWith("test_cases")
108 ) {
109 bodies.push(readFileSync(join(dir, entry.name), "utf-8"));
110 }
111 }
112 return bodies;
113 }
114
115 export function deriveToolCount() {
116 const dir = join(REPO_ROOT, "crates/engine/src/tools");
117 if (!existsSync(dir)) return null;
118 return countToolSpecs(collectToolSourceBodies(dir));
119 }
120
121 export function deriveContributorCount() {
122 const contributors = JSON.parse(read("docs/contributors.json") ?? "null");
123 const people = contributors?.people;
124 const unlinked = contributors?.unlinked_commit_names ?? [];
125 if (!Array.isArray(people) || people.length === 0 || people.some((person) =>
126 !person || typeof person.login !== "string" || person.login.trim().length === 0)
127 || new Set(people.map((person) => person.login.toLowerCase())).size !== people.length
128 || !Array.isArray(unlinked) || unlinked.some((name) => typeof name !== "string" || name.trim().length === 0)) {
129 throw new Error("missing or malformed contributor roster");
130 }
131 const logins = new Set(people.map((person) => person.login.toLowerCase()));
132 return people.length + unlinked.filter((name) => !logins.has(name.toLowerCase())).length;
133 }
134
135 export function deriveLicense() {
136 const lic = read("LICENSE");
137 if (!lic) return null;
138 const first = lic.split(/\r?\n/).find((l) => l.trim().length > 0);
139 if (!first) return null;
140 if (/^MIT License/i.test(first)) return "MIT";
141 if (/Apache.*2\.0/i.test(first)) return "Apache-2.0";
142 return first.trim();
143 }
144
145 export function deriveLatestPublishedRelease() {
146 const raw = read("web/data/latest-published-release.json");
147 if (!raw) return null;
148 try {
149 const release = JSON.parse(raw);
150 if (
151 typeof release.tag !== "string" ||
152 typeof release.version !== "string" ||
153 release.tag !== `v${release.version}` ||
154 typeof release.publishedAt !== "string" ||
155 !Number.isFinite(Date.parse(release.publishedAt)) ||
156 typeof release.url !== "string" ||
157 release.url !== `https://github.com/codewhale-hq/CodeWhale/releases/tag/${release.tag}` ||
158 (release.readAt !== undefined && !(typeof release.readAt === "string" && Number.isFinite(Date.parse(release.readAt)))) ||
159 (release.assets !== undefined && !(Array.isArray(release.assets) && release.assets.every((asset) =>
160 asset && typeof asset.name === "string" && Number.isSafeInteger(asset.size) && asset.size >= 0 &&
161 (asset.sha256 === null || (typeof asset.sha256 === "string" && /^[0-9a-f]{64}$/.test(asset.sha256))))))
162 ) {
163 return null;
164 }
165 return release;
166 } catch {
167 return null;
168 }
169 }
170
171 export function parseFeatureRows(source) {
172 const parsed = spawnSync("python3", ["-c", "import json, sys, tomllib; print(json.dumps(tomllib.loads(sys.stdin.read())['feature']))"],
173 { input: source, encoding: "utf8", maxBuffer: 4 * 1024 * 1024 });
174 if (parsed.status !== 0) throw new Error(`feature registry parse failed: ${parsed.stderr || parsed.error || parsed.status}`);
175 const rows = JSON.parse(parsed.stdout);
176 if (!Array.isArray(rows) || rows.length === 0) throw new Error("empty feature registry");
177 return rows;
178 }
179
180 export function deriveFeatures() {
181 const source = read("docs/features.toml");
182 if (!source) throw new Error("missing feature registry");
183 const rows = parseFeatureRows(source);
184 const ids = new Set();
185 const features = rows.map((row) => {
186 if (!row || typeof row.id !== "string" || !/^[a-z0-9-]+$/.test(row.id) || ids.has(row.id)
187 || typeof row.name !== "string" || typeof row.summary !== "string"
188 || !["stable", "flagged", "experimental"].includes(row.status)
189 || !row.surfaces || typeof row.surfaces !== "object" || Array.isArray(row.surfaces)) {
190 throw new Error(`invalid feature registry row: ${row?.id ?? "unknown"}`);
191 }
192 ids.add(row.id);
193 for (const [surface, state] of Object.entries(row.surfaces)) {
194 if (!["tui", "desktop", "web", "api"].includes(surface) || !["stable", "partial", "preview", "none"].includes(state)) {
195 throw new Error(`invalid feature surface: ${row.id}/${surface}`);
196 }
197 }
198 for (const field of ["docs", "flag", "since"]) {
199 if (row[field] !== undefined && typeof row[field] !== "string") throw new Error(`invalid feature ${field}: ${row.id}`);
200 }
201 const documentation = row.docs ?? null;
202 if (documentation) {
203 const path = documentation.split("#", 1)[0];
204 if (path.startsWith("/") || path.includes("..") || !existsSync(join(REPO_ROOT, path))) {
205 throw new Error(`missing feature document: ${row.id}/${path}`);
206 }
207 }
208 const match = source.match(new RegExp(`^[ \\t]*id[ \\t]*=[ \\t]*["']${row.id}["']`, "m"));
209 if (!match) throw new Error(`feature registry location missing: ${row.id}`);
210 const line = source.slice(0, match.index).split("\n").length;
211 return { id: row.id, name: row.name, summary: row.summary, status: row.status,
212 surfaces: row.surfaces, since: row.since ?? null, flag: row.flag ?? null,
213 docs: documentation, registryLine: line };
214 });
215 return { format: "codewhale.features.v1", source: { path: "docs/features.toml", sha256: createHash("sha256").update(source).digest("hex") }, features };
216 }
217
218 /**
219 * Re-derive all mechanical facts from the current workspace. The returned
220 * object is the same shape as web/lib/facts.generated.ts → RepoFacts.
221 */
222 export function buildFacts() {
223 const providers = deriveProviders();
224
225 const facts = {
226 generatedAt: new Date().toISOString(),
227 // next.config.ts injects these from the exact checkout into the built
228 // artifact. They stay null in the tracked snapshot to avoid a
229 // self-referential generated-file diff after every commit.
230 sourceRevision: null,
231 sourceCommittedAt: null,
232 version: deriveVersion(),
233 crates: deriveCrates(),
234 sandboxBackends: deriveSandboxBackends(),
235 providers,
236 models: deriveModels(),
237 defaultModel: deriveDefaultModel(),
238 nodeEngines: deriveNodeEngines(),
239 toolCount: deriveToolCount(),
240 contributorCount: deriveContributorCount(),
241 license: deriveLicense(),
242 latestPublishedRelease: deriveLatestPublishedRelease(),
243 };
244
245 return facts;
246 }
247
247 lines Plain Text