| 1 | /** |
| 2 | * facts-drift.ts — runtime version of scripts/derive-facts.mjs. |
| 3 | * |
| 4 | * Fetches source-of-truth files from raw.githubusercontent.com on a schedule, |
| 5 | * re-derives the same RepoFacts shape, compares to the value cached in KV (or |
| 6 | * to the build-time fallback on first run), and if anything changed writes |
| 7 | * the new facts to CURATED_KV under "facts:current". `getFacts()` accepts the |
| 8 | * KV value only when its exact source provenance is at least as new as the |
| 9 | * deployed build; published-release metadata is resolved separately. |
| 10 | * |
| 11 | * Mechanical drift (provider added, sandbox backend renamed, version bumped) |
| 12 | * fixes itself within one cron tick — no redeploy. Semantic drift (a new |
| 13 | * feature should be advertised on the homepage) is still left to humans. |
| 14 | */ |
| 15 | import { withGenerationLease, type DraftClaimLockNamespace } from "./draft-claim-lock"; |
| 16 | import { parseModelCatalog } from "./model-catalog.mjs"; |
| 17 | import { parseProviderDescriptors } from "./provider-descriptors.mjs"; |
| 18 | import { fetchBoundedText } from "./bounded-body"; |
| 19 | import type { RepoFacts } from "./facts.generated"; |
| 20 | import { FACTS as BUILD_FACTS } from "./facts.generated"; |
| 21 | import { isPublishedRelease, isRepoFacts, newestPublishedRelease } from "./facts"; |
| 22 | import { fetchLatestPublishedRelease } from "./published-release"; |
| 23 | |
| 24 | const RAW_ROOT = "https://raw.githubusercontent.com/codewhale-hq/CodeWhale"; |
| 25 | const KV_KEY = "facts:current"; |
| 26 | const LOG_KEY = "facts:drift-log"; |
| 27 | |
| 28 | interface KVNamespace { |
| 29 | get(k: string): Promise<string | null>; |
| 30 | put(k: string, v: string, o?: { expirationTtl?: number }): Promise<void>; |
| 31 | } |
| 32 | |
| 33 | interface SourceMarker { |
| 34 | revision: string; |
| 35 | committedAt: string; |
| 36 | } |
| 37 | |
| 38 | async function fetchText( |
| 39 | path: string, |
| 40 | revision: string, |
| 41 | ghToken?: string, |
| 42 | ): Promise<string | null> { |
| 43 | const headers: Record<string, string> = { |
| 44 | "User-Agent": "codewhale-web-drift", |
| 45 | }; |
| 46 | if (ghToken) headers["Authorization"] = `Bearer ${ghToken}`; |
| 47 | try { |
| 48 | const r = await fetchBoundedText(`${RAW_ROOT}/${revision}/${path}`, { headers }); |
| 49 | return r.ok ? r.text : null; |
| 50 | } catch { |
| 51 | return null; |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | async function fetchSourceMarker(ghToken?: string): Promise<SourceMarker | null> { |
| 56 | const headers: Record<string, string> = { |
| 57 | Accept: "application/vnd.github+json", |
| 58 | "User-Agent": "codewhale-web-drift", |
| 59 | "X-GitHub-Api-Version": "2022-11-28", |
| 60 | }; |
| 61 | if (ghToken) headers.Authorization = `Bearer ${ghToken}`; |
| 62 | try { |
| 63 | const response = await fetchBoundedText( |
| 64 | "https://api.github.com/repos/codewhale-hq/CodeWhale/commits/main", |
| 65 | { headers }, |
| 66 | ); |
| 67 | if (!response.ok) return null; |
| 68 | const json = JSON.parse(response.text) as { |
| 69 | sha?: string; |
| 70 | commit?: { committer?: { date?: string } }; |
| 71 | }; |
| 72 | const revision = json.sha; |
| 73 | const committedAt = json.commit?.committer?.date; |
| 74 | if ( |
| 75 | !revision || |
| 76 | !/^[0-9a-f]{40}$/i.test(revision) || |
| 77 | !committedAt || |
| 78 | !Number.isFinite(Date.parse(committedAt)) |
| 79 | ) { |
| 80 | return null; |
| 81 | } |
| 82 | return { revision, committedAt }; |
| 83 | } catch { |
| 84 | return null; |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | function deriveVersion(cargo: string): string | null { |
| 89 | const m = cargo.match(/^version\s*=\s*"([^"]+)"/m); |
| 90 | return m ? m[1] : null; |
| 91 | } |
| 92 | |
| 93 | function deriveCrates(cargo: string): string[] { |
| 94 | const block = cargo.match(/members\s*=\s*\[([\s\S]*?)\]/); |
| 95 | if (!block) return []; |
| 96 | return [...block[1].matchAll(/"crates\/([^"]+)"/g)].map((m) => m[1]).sort(); |
| 97 | } |
| 98 | |
| 99 | function deriveSandboxBackends(source: string): string[] { |
| 100 | const marker = source.match( |
| 101 | /pub const PUBLIC_SANDBOX_BACKENDS\s*:\s*&\[&str\]\s*=\s*&\[([\s\S]*?)\];/, |
| 102 | ); |
| 103 | if (!marker) return []; |
| 104 | return [...marker[1].matchAll(/"([^"]+)"/g)].map((match) => match[1]); |
| 105 | } |
| 106 | |
| 107 | function deriveLicense(licText: string): string | null { |
| 108 | const first = licText.split(/\r?\n/).find((l) => l.trim().length > 0); |
| 109 | if (!first) return null; |
| 110 | if (/^MIT License/i.test(first)) return "MIT"; |
| 111 | if (/Apache.*2\.0/i.test(first)) return "Apache-2.0"; |
| 112 | return first.trim(); |
| 113 | } |
| 114 | |
| 115 | function parseGeneratedFacts(source: string): Record<string, unknown> | null { |
| 116 | const match = source.match( |
| 117 | /export\s+const\s+FACTS(?:\s*:\s*RepoFacts)?\s*=\s*(\{[\s\S]*\})\s*;?\s*$/, |
| 118 | ); |
| 119 | if (!match) return null; |
| 120 | |
| 121 | try { |
| 122 | const parsed = JSON.parse(match[1]) as unknown; |
| 123 | return parsed && typeof parsed === "object" && !Array.isArray(parsed) |
| 124 | ? (parsed as Record<string, unknown>) |
| 125 | : null; |
| 126 | } catch { |
| 127 | return null; |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | function deriveCountFromGeneratedFacts(facts: Record<string, unknown> | null, field: "toolCount" | "contributorCount"): number | null { |
| 132 | const count = facts?.[field]; |
| 133 | return typeof count === "number" && Number.isSafeInteger(count) && count >= (field === "contributorCount" ? 1 : 0) |
| 134 | ? count |
| 135 | : null; |
| 136 | } |
| 137 | |
| 138 | /** |
| 139 | * Model presentation comes from the exact revision's reviewed catalog; |
| 140 | * tool and contributor counts retain the existing generated-source boundary. |
| 141 | */ |
| 142 | export async function deriveFactsFromRemote(ghToken?: string): Promise<RepoFacts | null> { |
| 143 | const source = await fetchSourceMarker(ghToken); |
| 144 | if (!source) return null; |
| 145 | |
| 146 | const [cargo, providerMetadata, sandboxSource, npmPkg, licText, generatedFacts, modelCatalog, latestPublishedRelease] = await Promise.all([ |
| 147 | fetchText("Cargo.toml", source.revision, ghToken), |
| 148 | fetchText("crates/config/assets/provider_descriptors.json", source.revision, ghToken), |
| 149 | fetchText("crates/sandbox/src/lib.rs", source.revision, ghToken), |
| 150 | fetchText("npm/codewhale/package.json", source.revision, ghToken), |
| 151 | fetchText("LICENSE", source.revision, ghToken), |
| 152 | fetchText("web/lib/facts.generated.ts", source.revision, ghToken), |
| 153 | fetchText("crates/config/assets/catalog_corrections.json", source.revision, ghToken), |
| 154 | fetchLatestPublishedRelease(ghToken), |
| 155 | ]); |
| 156 | |
| 157 | if (!cargo) return null; |
| 158 | const providerData = parseProviderDescriptors(providerMetadata); |
| 159 | if (!providerData) return null; |
| 160 | const generated = generatedFacts ? parseGeneratedFacts(generatedFacts) : null; |
| 161 | const toolCount = deriveCountFromGeneratedFacts(generated, "toolCount"); |
| 162 | const contributorCount = deriveCountFromGeneratedFacts(generated, "contributorCount"); |
| 163 | const models = parseModelCatalog(modelCatalog); |
| 164 | // Never attach current-main provenance to build-time tool/model/contributor facts. The |
| 165 | // checked-in generated snapshot is guarded by the exact revision's CI drift |
| 166 | // check, so an absent or malformed value makes the whole derivation fail. |
| 167 | if (toolCount === null || contributorCount === null || models === null) return null; |
| 168 | |
| 169 | const facts: RepoFacts = { |
| 170 | generatedAt: new Date().toISOString(), |
| 171 | sourceRevision: source.revision, |
| 172 | sourceCommittedAt: source.committedAt, |
| 173 | version: deriveVersion(cargo), |
| 174 | crates: deriveCrates(cargo), |
| 175 | sandboxBackends: sandboxSource |
| 176 | ? deriveSandboxBackends(sandboxSource) |
| 177 | : BUILD_FACTS.sandboxBackends, |
| 178 | providers: providerData.providers, |
| 179 | models, |
| 180 | defaultModel: providerData.defaultModel, |
| 181 | nodeEngines: (() => { |
| 182 | try { return npmPkg ? JSON.parse(npmPkg).engines?.node ?? null : null; } catch { return null; } |
| 183 | })(), |
| 184 | toolCount, |
| 185 | contributorCount, |
| 186 | license: licText ? deriveLicense(licText) : BUILD_FACTS.license, |
| 187 | latestPublishedRelease: |
| 188 | latestPublishedRelease ?? BUILD_FACTS.latestPublishedRelease, |
| 189 | }; |
| 190 | |
| 191 | if (!facts.version || facts.crates.length === 0 || facts.providers.length === 0) { |
| 192 | return null; |
| 193 | } |
| 194 | return facts; |
| 195 | } |
| 196 | |
| 197 | interface DriftDiff { |
| 198 | field: keyof RepoFacts; |
| 199 | before: unknown; |
| 200 | after: unknown; |
| 201 | } |
| 202 | |
| 203 | function diff(a: RepoFacts, b: RepoFacts): DriftDiff[] { |
| 204 | const fields: (keyof RepoFacts)[] = [ |
| 205 | "sourceRevision", |
| 206 | "sourceCommittedAt", |
| 207 | "version", |
| 208 | "crates", |
| 209 | "sandboxBackends", |
| 210 | "providers", |
| 211 | "models", |
| 212 | "defaultModel", |
| 213 | "nodeEngines", |
| 214 | "toolCount", |
| 215 | "contributorCount", |
| 216 | "license", |
| 217 | "latestPublishedRelease", |
| 218 | ]; |
| 219 | const out: DriftDiff[] = []; |
| 220 | for (const f of fields) { |
| 221 | const av = JSON.stringify(a[f]); |
| 222 | const bv = JSON.stringify(b[f]); |
| 223 | if (av !== bv) out.push({ field: f, before: a[f], after: b[f] }); |
| 224 | } |
| 225 | return out; |
| 226 | } |
| 227 | |
| 228 | export interface FactsDriftResult { |
| 229 | ok: boolean; |
| 230 | changed?: boolean; |
| 231 | diffs?: DriftDiff[]; |
| 232 | reason?: string; |
| 233 | } |
| 234 | |
| 235 | export async function runFactsDrift(env: { |
| 236 | CURATED_KV?: KVNamespace; |
| 237 | DRAFT_CLAIM_LOCK?: DraftClaimLockNamespace; |
| 238 | GITHUB_TOKEN?: string; |
| 239 | }): Promise<FactsDriftResult> { |
| 240 | const kv = env.CURATED_KV; |
| 241 | if (!kv) return { ok: false, reason: "CURATED_KV not bound" }; |
| 242 | const result = env.DRAFT_CLAIM_LOCK |
| 243 | ? await withGenerationLease(env.DRAFT_CLAIM_LOCK, "facts-drift", () => refreshFacts(kv, env.GITHUB_TOKEN)) |
| 244 | : "unavailable"; |
| 245 | if (result === "busy") return { ok: true, changed: false, reason: "facts refresh already in progress or recently completed" }; |
| 246 | if (result === "unavailable") { |
| 247 | const reason = "facts refresh claim unavailable"; |
| 248 | console.warn(`[facts-drift] ${reason}`); |
| 249 | return { ok: false, reason }; |
| 250 | } |
| 251 | return result; |
| 252 | } |
| 253 | |
| 254 | async function refreshFacts(kv: KVNamespace, githubToken?: string): Promise<FactsDriftResult> { |
| 255 | const remote = await deriveFactsFromRemote(githubToken); |
| 256 | if (!remote) return { ok: false, reason: "remote derivation failed" }; |
| 257 | // getFacts() discards a snapshot isRepoFacts rejects, so never store one. |
| 258 | // The scheduled handler drops this result, so say it here: otherwise the |
| 259 | // cron stops refreshing KV with no signal at all. |
| 260 | const { sourceRevision, sourceCommittedAt, version } = remote; |
| 261 | if (!isRepoFacts(remote)) { |
| 262 | const reason = "remote facts failed validation"; |
| 263 | console.warn( |
| 264 | `[facts-drift] ${reason}; KV snapshot not refreshed ` + |
| 265 | `(sourceRevision=${String(sourceRevision)}, ` + |
| 266 | `sourceCommittedAt=${String(sourceCommittedAt)}, version=${String(version)})`, |
| 267 | ); |
| 268 | return { ok: false, reason }; |
| 269 | } |
| 270 | |
| 271 | const cachedRaw = await kv.get(KV_KEY); |
| 272 | let cached: RepoFacts = BUILD_FACTS; |
| 273 | if (cachedRaw) { |
| 274 | try { |
| 275 | const parsed = JSON.parse(cachedRaw) as unknown; |
| 276 | if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) { |
| 277 | cached = parsed as RepoFacts; |
| 278 | } |
| 279 | } catch { |
| 280 | // A truncated or legacy cache is replaced by the newly derived snapshot. |
| 281 | } |
| 282 | } |
| 283 | |
| 284 | const cachedAt = Date.parse(String(cached.sourceCommittedAt ?? "")); |
| 285 | if (cachedRaw && Number.isFinite(cachedAt) && cachedAt > Date.parse(String(remote.sourceCommittedAt))) { |
| 286 | return { ok: true, changed: false }; |
| 287 | } |
| 288 | |
| 289 | remote.latestPublishedRelease = newestPublishedRelease( |
| 290 | remote.latestPublishedRelease, |
| 291 | isPublishedRelease(cached.latestPublishedRelease) ? cached.latestPublishedRelease : null, |
| 292 | ); |
| 293 | |
| 294 | const diffs = diff(cached, remote); |
| 295 | if (diffs.length === 0) { |
| 296 | return { ok: true, changed: false }; |
| 297 | } |
| 298 | |
| 299 | // Write new facts. No TTL — they live until next drift overwrites them. |
| 300 | await kv.put(KV_KEY, JSON.stringify(remote)); |
| 301 | |
| 302 | // Append to drift log (last 20 entries). |
| 303 | try { |
| 304 | const logRaw = await kv.get(LOG_KEY); |
| 305 | const log = logRaw ? (JSON.parse(logRaw) as Array<{ at: string; diffs: DriftDiff[] }>) : []; |
| 306 | log.unshift({ at: remote.generatedAt, diffs }); |
| 307 | await kv.put(LOG_KEY, JSON.stringify(log.slice(0, 20))); |
| 308 | } catch { |
| 309 | /* non-fatal */ |
| 310 | } |
| 311 | |
| 312 | return { ok: true, changed: true, diffs }; |
| 313 | } |
| 314 |