| 1 | import { |
| 2 | FACTS as BUILD_TIME_FACTS, |
| 3 | type PublishedReleaseFact, |
| 4 | type ReleaseAssetFact, |
| 5 | type RepoFacts, |
| 6 | type ProviderFact, |
| 7 | type ModelFact, |
| 8 | } from "./facts.generated"; |
| 9 | |
| 10 | const KV_KEY = "facts:current"; |
| 11 | |
| 12 | export type { PublishedReleaseFact, ReleaseAssetFact, RepoFacts, ProviderFact, ModelFact }; |
| 13 | |
| 14 | export interface BuildProvenance { |
| 15 | revision?: string | null; |
| 16 | committedAt?: string | null; |
| 17 | generatedAt?: string | null; |
| 18 | } |
| 19 | |
| 20 | export function withBuildProvenance(base: RepoFacts, stamp: BuildProvenance): RepoFacts { |
| 21 | const { revision, committedAt, generatedAt } = stamp; |
| 22 | if ( |
| 23 | typeof revision !== "string" || !/^[0-9a-f]{40}$/i.test(revision) || |
| 24 | typeof committedAt !== "string" || !Number.isFinite(Date.parse(committedAt)) || |
| 25 | typeof generatedAt !== "string" || !Number.isFinite(Date.parse(generatedAt)) |
| 26 | ) { |
| 27 | return base; |
| 28 | } |
| 29 | return { ...base, sourceRevision: revision, sourceCommittedAt: committedAt, generatedAt }; |
| 30 | } |
| 31 | |
| 32 | export const BUILD_FACTS: RepoFacts = withBuildProvenance(BUILD_TIME_FACTS, { |
| 33 | revision: process.env.NEXT_PUBLIC_CODEWHALE_SOURCE_REVISION, |
| 34 | committedAt: process.env.NEXT_PUBLIC_CODEWHALE_SOURCE_COMMITTED_AT, |
| 35 | generatedAt: process.env.NEXT_PUBLIC_CODEWHALE_FACTS_GENERATED_AT, |
| 36 | }); |
| 37 | |
| 38 | interface KVNamespace { |
| 39 | get(key: string): Promise<string | null>; |
| 40 | put(key: string, value: string, opts?: { expirationTtl?: number }): Promise<void>; |
| 41 | } |
| 42 | |
| 43 | export type FactsSource = "build" | "kv"; |
| 44 | |
| 45 | export interface FactsResolution { |
| 46 | facts: RepoFacts; |
| 47 | source: FactsSource; |
| 48 | reason: |
| 49 | | "no-kv-snapshot" |
| 50 | | "invalid-kv-snapshot" |
| 51 | | "kv-missing-source-provenance" |
| 52 | | "build-missing-source-provenance" |
| 53 | | "same-source-revision" |
| 54 | | "kv-source-newer" |
| 55 | | "build-source-newer-or-ambiguous"; |
| 56 | buildSourceRevision: string | null; |
| 57 | kvSourceRevision: string | null; |
| 58 | } |
| 59 | |
| 60 | function isRecord(value: unknown): value is Record<string, unknown> { |
| 61 | return value !== null && typeof value === "object" && !Array.isArray(value); |
| 62 | } |
| 63 | |
| 64 | function isModelFact(value: unknown): value is ModelFact { |
| 65 | if (!isRecord(value)) return false; |
| 66 | return ( |
| 67 | typeof value.id === "string" && |
| 68 | (value.provider === null || typeof value.provider === "string") && |
| 69 | (value.contextWindow === null || typeof value.contextWindow === "number") && |
| 70 | (value.maxOutput === null || typeof value.maxOutput === "number") && |
| 71 | typeof value.reasoning === "boolean" && |
| 72 | (value.addedAt === null || typeof value.addedAt === "string") |
| 73 | ); |
| 74 | } |
| 75 | |
| 76 | export function isPublishedRelease(value: unknown): value is PublishedReleaseFact { |
| 77 | if (!isRecord(value)) return false; |
| 78 | return ( |
| 79 | typeof value.tag === "string" && |
| 80 | /^v\d+\.\d+\.\d+$/.test(value.tag) && |
| 81 | typeof value.version === "string" && |
| 82 | value.tag === `v${value.version}` && |
| 83 | typeof value.publishedAt === "string" && |
| 84 | Number.isFinite(Date.parse(value.publishedAt)) && |
| 85 | value.url === `https://github.com/codewhale-hq/CodeWhale/releases/tag/${value.tag}` && |
| 86 | (value.readAt === undefined || |
| 87 | (typeof value.readAt === "string" && Number.isFinite(Date.parse(value.readAt)))) && |
| 88 | (value.assets === undefined || |
| 89 | (Array.isArray(value.assets) && |
| 90 | value.assets.every( |
| 91 | (asset) => |
| 92 | isRecord(asset) && |
| 93 | typeof asset.name === "string" && |
| 94 | typeof asset.size === "number" && |
| 95 | Number.isSafeInteger(asset.size) && |
| 96 | asset.size >= 0 && |
| 97 | (asset.sha256 === null || |
| 98 | (typeof asset.sha256 === "string" && /^[0-9a-f]{64}$/.test(asset.sha256))), |
| 99 | ))) |
| 100 | ); |
| 101 | } |
| 102 | |
| 103 | export function isRepoFacts(value: unknown): value is RepoFacts { |
| 104 | if (!isRecord(value)) return false; |
| 105 | const sourceRevisionValid = |
| 106 | value.sourceRevision === null || |
| 107 | (typeof value.sourceRevision === "string" && /^[0-9a-f]{40}$/i.test(value.sourceRevision)); |
| 108 | const sourceCommittedAtValid = |
| 109 | value.sourceCommittedAt === null || |
| 110 | (typeof value.sourceCommittedAt === "string" && |
| 111 | Number.isFinite(Date.parse(value.sourceCommittedAt))); |
| 112 | const sourceProvenancePaired = |
| 113 | (value.sourceRevision === null) === (value.sourceCommittedAt === null); |
| 114 | |
| 115 | return ( |
| 116 | typeof value.generatedAt === "string" && |
| 117 | sourceRevisionValid && |
| 118 | sourceCommittedAtValid && |
| 119 | sourceProvenancePaired && |
| 120 | typeof value.version === "string" && |
| 121 | Array.isArray(value.crates) && |
| 122 | Array.isArray(value.sandboxBackends) && |
| 123 | Array.isArray(value.providers) && |
| 124 | value.providers.every( |
| 125 | (provider) => |
| 126 | isRecord(provider) && |
| 127 | typeof provider.id === "string" && |
| 128 | typeof provider.label === "string" && |
| 129 | typeof provider.env === "string", |
| 130 | ) && |
| 131 | Array.isArray(value.models) && |
| 132 | value.models.every(isModelFact) && |
| 133 | (value.defaultModel === null || typeof value.defaultModel === "string") && |
| 134 | (value.nodeEngines === null || typeof value.nodeEngines === "string") && |
| 135 | (value.toolCount === null || typeof value.toolCount === "number") && |
| 136 | typeof value.contributorCount === "number" && |
| 137 | Number.isSafeInteger(value.contributorCount) && value.contributorCount > 0 && |
| 138 | (value.license === null || typeof value.license === "string") && |
| 139 | (value.latestPublishedRelease === null || |
| 140 | isPublishedRelease(value.latestPublishedRelease)) |
| 141 | ); |
| 142 | } |
| 143 | |
| 144 | export function newestPublishedRelease( |
| 145 | build: PublishedReleaseFact | null, |
| 146 | cached: PublishedReleaseFact | null, |
| 147 | ): PublishedReleaseFact | null { |
| 148 | if (!build) return cached; |
| 149 | if (!cached) return build; |
| 150 | return Date.parse(cached.publishedAt) > Date.parse(build.publishedAt) ? cached : build; |
| 151 | } |
| 152 | |
| 153 | /** |
| 154 | * Select the mechanical fact snapshot independently from the latest published |
| 155 | * release. A legacy or malformed KV value cannot replace a newer build merely |
| 156 | * because it exists. Source commit timestamps provide ordering, while an exact |
| 157 | * revision match permits the runtime snapshot for the same source. |
| 158 | */ |
| 159 | export function resolveFacts(build: RepoFacts, cached: unknown): FactsResolution { |
| 160 | if (cached == null) { |
| 161 | return { |
| 162 | facts: build, |
| 163 | source: "build", |
| 164 | reason: "no-kv-snapshot", |
| 165 | buildSourceRevision: build.sourceRevision, |
| 166 | kvSourceRevision: null, |
| 167 | }; |
| 168 | } |
| 169 | if (!isRepoFacts(cached)) { |
| 170 | return { |
| 171 | facts: build, |
| 172 | source: "build", |
| 173 | reason: "invalid-kv-snapshot", |
| 174 | buildSourceRevision: build.sourceRevision, |
| 175 | kvSourceRevision: null, |
| 176 | }; |
| 177 | } |
| 178 | |
| 179 | const latestPublishedRelease = newestPublishedRelease( |
| 180 | build.latestPublishedRelease, |
| 181 | cached.latestPublishedRelease, |
| 182 | ); |
| 183 | const withLatestRelease = (facts: RepoFacts): RepoFacts => ({ |
| 184 | ...facts, |
| 185 | latestPublishedRelease, |
| 186 | }); |
| 187 | |
| 188 | if (!cached.sourceRevision || !cached.sourceCommittedAt) { |
| 189 | return { |
| 190 | facts: withLatestRelease(build), |
| 191 | source: "build", |
| 192 | reason: "kv-missing-source-provenance", |
| 193 | buildSourceRevision: build.sourceRevision, |
| 194 | kvSourceRevision: cached.sourceRevision, |
| 195 | }; |
| 196 | } |
| 197 | if (!build.sourceRevision || !build.sourceCommittedAt) { |
| 198 | return { |
| 199 | facts: withLatestRelease(build), |
| 200 | source: "build", |
| 201 | reason: "build-missing-source-provenance", |
| 202 | buildSourceRevision: build.sourceRevision, |
| 203 | kvSourceRevision: cached.sourceRevision, |
| 204 | }; |
| 205 | } |
| 206 | if (cached.sourceRevision === build.sourceRevision) { |
| 207 | return { |
| 208 | facts: withLatestRelease(cached), |
| 209 | source: "kv", |
| 210 | reason: "same-source-revision", |
| 211 | buildSourceRevision: build.sourceRevision, |
| 212 | kvSourceRevision: cached.sourceRevision, |
| 213 | }; |
| 214 | } |
| 215 | |
| 216 | const buildTime = Date.parse(build.sourceCommittedAt); |
| 217 | const cachedTime = Date.parse(cached.sourceCommittedAt); |
| 218 | if (Number.isFinite(buildTime) && Number.isFinite(cachedTime) && cachedTime > buildTime) { |
| 219 | return { |
| 220 | facts: withLatestRelease(cached), |
| 221 | source: "kv", |
| 222 | reason: "kv-source-newer", |
| 223 | buildSourceRevision: build.sourceRevision, |
| 224 | kvSourceRevision: cached.sourceRevision, |
| 225 | }; |
| 226 | } |
| 227 | |
| 228 | return { |
| 229 | facts: withLatestRelease(build), |
| 230 | source: "build", |
| 231 | reason: "build-source-newer-or-ambiguous", |
| 232 | buildSourceRevision: build.sourceRevision, |
| 233 | kvSourceRevision: cached.sourceRevision, |
| 234 | }; |
| 235 | } |
| 236 | |
| 237 | async function getKv(): Promise<KVNamespace | undefined> { |
| 238 | if (process.env.NEXT_PHASE === "phase-production-build") { |
| 239 | return undefined; |
| 240 | } |
| 241 | |
| 242 | try { |
| 243 | const mod = await import("@opennextjs/cloudflare"); |
| 244 | const ctx = await mod.getCloudflareContext({ async: true }); |
| 245 | return (ctx.env as { CURATED_KV?: KVNamespace }).CURATED_KV; |
| 246 | } catch { |
| 247 | return undefined; |
| 248 | } |
| 249 | } |
| 250 | |
| 251 | export async function getFactsWithProvenance(): Promise<FactsResolution> { |
| 252 | try { |
| 253 | const kv = await getKv(); |
| 254 | if (!kv) return resolveFacts(BUILD_FACTS, null); |
| 255 | const raw = await kv.get(KV_KEY); |
| 256 | if (!raw) return resolveFacts(BUILD_FACTS, null); |
| 257 | return resolveFacts(BUILD_FACTS, JSON.parse(raw) as unknown); |
| 258 | } catch { |
| 259 | return resolveFacts(BUILD_FACTS, null); |
| 260 | } |
| 261 | } |
| 262 | |
| 263 | /** Resolved facts for the current request, with fail-safe build precedence. */ |
| 264 | export async function getFacts(): Promise<RepoFacts> { |
| 265 | return (await getFactsWithProvenance()).facts; |
| 266 | } |
| 267 |