| 1 | import { afterEach, describe, expect, it, vi } from "vitest"; |
| 2 | import { readFileSync } from "node:fs"; |
| 3 | import { isRepoFacts } from "./facts"; |
| 4 | import { FakeDraftClaimLock } from "./draft-claim-lock.fake"; |
| 5 | import { deriveFactsFromRemote, runFactsDrift } from "./facts-drift"; |
| 6 | |
| 7 | const REVISION = "b".repeat(40); |
| 8 | |
| 9 | function response(body: string, status = 200): Response { |
| 10 | return new Response(body, { status }); |
| 11 | } |
| 12 | |
| 13 | const VALID_GENERATED_FACTS = |
| 14 | 'export const FACTS: RepoFacts = {"toolCount":73,"contributorCount":390,"models":[]};'; |
| 15 | |
| 16 | function installGitHubFixture( |
| 17 | toolCountSource: string | null, |
| 18 | releaseHtmlUrl = "https://github.com/codewhale-hq/CodeWhale/releases/tag/v0.9.0", |
| 19 | sourceOverrides: Record<string, string> = {}, |
| 20 | ): void { |
| 21 | vi.stubGlobal( |
| 22 | "fetch", |
| 23 | vi.fn(async (input: string | URL | Request) => { |
| 24 | const url = String(input); |
| 25 | if (url.endsWith("/commits/main")) { |
| 26 | return response( |
| 27 | JSON.stringify({ |
| 28 | sha: REVISION, |
| 29 | commit: { committer: { date: "2026-07-21T23:00:00Z" } }, |
| 30 | }), |
| 31 | ); |
| 32 | } |
| 33 | if (url.endsWith("/releases/latest")) { |
| 34 | return response( |
| 35 | JSON.stringify({ |
| 36 | tag_name: "v0.9.0", |
| 37 | draft: false, |
| 38 | prerelease: false, |
| 39 | published_at: "2026-07-16T20:05:39Z", |
| 40 | html_url: releaseHtmlUrl, |
| 41 | }), |
| 42 | ); |
| 43 | } |
| 44 | const rawPath = url.split(`/${REVISION}/`)[1]; |
| 45 | const sources: Record<string, string> = { |
| 46 | "Cargo.toml": 'version = "0.9.2"\nmembers = ["crates/tui"]', |
| 47 | "crates/config/assets/provider_descriptors.json": JSON.stringify({ |
| 48 | schema_version: 3, |
| 49 | providers: [{ kind: "Deepseek", id: "deepseek", label: "Remote DeepSeek", default_model: "remote-model", env_vars: ["REMOTE_KEY"], retired: false, selectable: true, web: { order: 0 }, tui_wire_tag: "deepseek", catalog_id: "deepseek", catalog_source_id: "deepseek" }], |
| 50 | constant_refs: { DEFAULT_TEXT_MODEL: { provider: "deepseek", field: "default_model" } }, |
| 51 | }), |
| 52 | "crates/config/assets/catalog_corrections.json": JSON.stringify({ reviewed: { |
| 53 | revision: "remote-reviewed", intrinsic: { "deepseek-v4-pro": { source: "exact remote fixture", context_window: 1000000, max_output: 128000, reasoning: true } }, |
| 54 | public_models: [{ id: "deepseek-v4-pro", label: "DeepSeek", added_at: "2026-07-01", aliases: [] }], |
| 55 | } }), |
| 56 | "crates/sandbox/src/lib.rs": ` |
| 57 | pub const PUBLIC_SANDBOX_BACKENDS: &[&str] = &[ |
| 58 | "seatbelt (macOS, when available)", |
| 59 | "bubblewrap (Linux, opt-in when installed)", |
| 60 | ]; |
| 61 | `, |
| 62 | "npm/codewhale/package.json": JSON.stringify({ engines: { node: ">=18" } }), |
| 63 | LICENSE: "MIT License\n", |
| 64 | ...sourceOverrides, |
| 65 | }; |
| 66 | if (rawPath === "web/lib/facts.generated.ts") { |
| 67 | return toolCountSource === null ? response("not found", 404) : response(toolCountSource); |
| 68 | } |
| 69 | return rawPath && rawPath in sources |
| 70 | ? response(sources[rawPath]) |
| 71 | : response("not found", 404); |
| 72 | }), |
| 73 | ); |
| 74 | } |
| 75 | |
| 76 | afterEach(() => { |
| 77 | vi.unstubAllGlobals(); |
| 78 | }); |
| 79 | |
| 80 | describe("deriveFactsFromRemote", () => { |
| 81 | it("derives counts and model rows from the same exact remote revision", async () => { |
| 82 | installGitHubFixture( |
| 83 | 'export const FACTS: RepoFacts = {"toolCount":73,"contributorCount":390,"models":[' + |
| 84 | '{"id":"deepseek-v4-pro","provider":"DeepSeek","contextWindow":1000000,' + |
| 85 | '"maxOutput":128000,"reasoning":true,"addedAt":"2026-07-01"}' + |
| 86 | "]};", |
| 87 | ); |
| 88 | |
| 89 | const facts = await deriveFactsFromRemote(); |
| 90 | |
| 91 | expect(facts?.sourceRevision).toBe(REVISION); |
| 92 | expect(facts?.version).toBe("0.9.2"); |
| 93 | expect(facts?.toolCount).toBe(73); |
| 94 | expect(facts?.contributorCount).toBe(390); |
| 95 | expect(facts?.defaultModel).toBe("remote-model"); |
| 96 | expect(facts?.providers).toEqual([{ id: "deepseek", label: "Remote DeepSeek", env: "REMOTE_KEY" }]); |
| 97 | expect(facts?.models).toEqual([ |
| 98 | { |
| 99 | id: "deepseek-v4-pro", |
| 100 | provider: "DeepSeek", |
| 101 | contextWindow: 1000000, |
| 102 | maxOutput: 128000, |
| 103 | reasoning: true, |
| 104 | addedAt: "2026-07-01", |
| 105 | }, |
| 106 | ]); |
| 107 | expect(facts?.sandboxBackends).toEqual([ |
| 108 | "seatbelt (macOS, when available)", |
| 109 | "bubblewrap (Linux, opt-in when installed)", |
| 110 | ]); |
| 111 | const fetchMock = vi.mocked(fetch); |
| 112 | expect( |
| 113 | fetchMock.mock.calls.some(([input]) => String(input).includes("/contents/")), |
| 114 | ).toBe(false); |
| 115 | }); |
| 116 | |
| 117 | it("refuses missing, malformed or incompatible exact-revision provider metadata", async () => { |
| 118 | for (const metadata of ["not json", "{}", '{"schema_version":1,"providers":[]}']) { |
| 119 | installGitHubFixture(VALID_GENERATED_FACTS, undefined, { |
| 120 | "crates/config/assets/provider_descriptors.json": metadata, |
| 121 | }); |
| 122 | await expect(deriveFactsFromRemote()).resolves.toBeNull(); |
| 123 | } |
| 124 | }); |
| 125 | |
| 126 | it("fails derivation when the exact revision has no valid tool count", async () => { |
| 127 | installGitHubFixture(null); |
| 128 | |
| 129 | await expect(deriveFactsFromRemote()).resolves.toBeNull(); |
| 130 | }); |
| 131 | |
| 132 | it("refuses missing or malformed model metadata from the exact source revision", async () => { |
| 133 | for (const catalog of ["not json", "{}", '{"reviewed":{"revision":"x","intrinsic":{},"public_models":[{"id":42}]}}']) { |
| 134 | installGitHubFixture(VALID_GENERATED_FACTS, undefined, { "crates/config/assets/catalog_corrections.json": catalog }); |
| 135 | await expect(deriveFactsFromRemote()).resolves.toBeNull(); |
| 136 | } |
| 137 | }); |
| 138 | |
| 139 | it("stores a canonical release URL when GitHub answers with the repo's other casing", async () => { |
| 140 | installGitHubFixture( |
| 141 | VALID_GENERATED_FACTS, |
| 142 | "https://github.com/codewhale-hq/Codewhale/releases/tag/v0.9.0", |
| 143 | ); |
| 144 | |
| 145 | const facts = await deriveFactsFromRemote(); |
| 146 | |
| 147 | expect(facts?.latestPublishedRelease?.url).toBe( |
| 148 | "https://github.com/codewhale-hq/CodeWhale/releases/tag/v0.9.0", |
| 149 | ); |
| 150 | expect(isRepoFacts(facts)).toBe(true); |
| 151 | }); |
| 152 | }); |
| 153 | |
| 154 | describe("runFactsDrift", () => { |
| 155 | it("writes a KV snapshot that getFacts() accepts", async () => { |
| 156 | installGitHubFixture( |
| 157 | VALID_GENERATED_FACTS, |
| 158 | "https://github.com/codewhale-hq/Codewhale/releases/tag/v0.9.0", |
| 159 | ); |
| 160 | const store = new Map<string, string>(); |
| 161 | const kv = { |
| 162 | get: async (key: string) => store.get(key) ?? null, |
| 163 | put: async (key: string, value: string) => { |
| 164 | store.set(key, value); |
| 165 | }, |
| 166 | }; |
| 167 | |
| 168 | expect((await runFactsDrift({ CURATED_KV: kv })).ok).toBe(false); |
| 169 | expect(fetch).not.toHaveBeenCalled(); |
| 170 | const env = { CURATED_KV: kv, DRAFT_CLAIM_LOCK: new FakeDraftClaimLock() }; |
| 171 | const results = await Promise.all([runFactsDrift(env), runFactsDrift(env)]); |
| 172 | expect(results.every((result) => result.ok)).toBe(true); |
| 173 | expect(results.filter((result) => result.changed)).toHaveLength(1); |
| 174 | expect(vi.mocked(fetch).mock.calls.filter(([url]) => String(url).endsWith("/commits/main"))).toHaveLength(1); |
| 175 | expect(JSON.parse(store.get("facts:drift-log") ?? "[]")).toHaveLength(1); |
| 176 | expect(isRepoFacts(JSON.parse(store.get("facts:current") ?? "null"))).toBe(true); |
| 177 | }); |
| 178 | |
| 179 | it("never replaces a snapshot from a newer source commit with an older one", async () => { |
| 180 | installGitHubFixture(VALID_GENERATED_FACTS); |
| 181 | const newer = JSON.stringify({ sourceCommittedAt: "2026-07-22T00:00:00Z", version: "9.9.9" }); |
| 182 | const store = new Map<string, string>([["facts:current", newer]]); |
| 183 | const kv = { |
| 184 | get: async (key: string) => store.get(key) ?? null, |
| 185 | put: async (key: string, value: string) => { store.set(key, value); }, |
| 186 | }; |
| 187 | // The fixture's source commit is 2026-07-21T23:00:00Z: an overlapping, |
| 188 | // slower run finishing after a newer one. |
| 189 | expect(await runFactsDrift({ CURATED_KV: kv, DRAFT_CLAIM_LOCK: new FakeDraftClaimLock() })).toEqual({ ok: true, changed: false }); |
| 190 | expect(store.get("facts:current")).toBe(newer); |
| 191 | }); |
| 192 | |
| 193 | // The scheduled handler discards the result, so the log line is the only |
| 194 | // signal that the cron stopped refreshing KV. |
| 195 | it("warns and writes nothing when the derived facts fail validation", async () => { |
| 196 | installGitHubFixture(VALID_GENERATED_FACTS, undefined, { |
| 197 | // A non-string engines.node survives derivation but fails isRepoFacts. |
| 198 | "npm/codewhale/package.json": JSON.stringify({ engines: { node: 18 } }), |
| 199 | }); |
| 200 | const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); |
| 201 | const store = new Map<string, string>(); |
| 202 | const kv = { |
| 203 | get: async (key: string) => store.get(key) ?? null, |
| 204 | put: async (key: string, value: string) => { |
| 205 | store.set(key, value); |
| 206 | }, |
| 207 | }; |
| 208 | |
| 209 | const result = await runFactsDrift({ CURATED_KV: kv, DRAFT_CLAIM_LOCK: new FakeDraftClaimLock() }); |
| 210 | |
| 211 | expect(result).toEqual({ ok: false, reason: "remote facts failed validation" }); |
| 212 | expect(store.size).toBe(0); |
| 213 | expect(warn).toHaveBeenCalledWith( |
| 214 | expect.stringContaining("[facts-drift] remote facts failed validation"), |
| 215 | ); |
| 216 | warn.mockRestore(); |
| 217 | }); |
| 218 | }); |
| 219 | |
| 220 | describe("complete remote provider roster", () => { |
| 221 | it("keeps all public providers with the labels and credentials from that exact revision", async () => { |
| 222 | const metadata = JSON.parse(readFileSync(new URL("../../crates/config/assets/provider_descriptors.json", import.meta.url), "utf8")); |
| 223 | for (const row of metadata.providers) { |
| 224 | if (row.web && !row.retired) { |
| 225 | row.web.label = `Pinned ${row.id}`; |
| 226 | row.web.env = `PINNED_${row.id}`; |
| 227 | } |
| 228 | } |
| 229 | installGitHubFixture(VALID_GENERATED_FACTS, undefined, { |
| 230 | "crates/runtime/src/config.rs": readFileSync(new URL("../../crates/runtime/src/config.rs", import.meta.url), "utf8"), |
| 231 | "crates/config/assets/provider_descriptors.json": JSON.stringify(metadata), |
| 232 | }); |
| 233 | const facts = await deriveFactsFromRemote(); |
| 234 | expect(facts?.sourceRevision).toBe(REVISION); |
| 235 | expect(facts?.providers).toHaveLength(50); |
| 236 | expect(new Set(facts?.providers.map(row => row.id)).size).toBe(50); |
| 237 | expect(facts?.providers.every(row => row.label === `Pinned ${row.id}` && row.env === `PINNED_${row.id}`)).toBe(true); |
| 238 | }); |
| 239 | }); |
| 240 |