返回 CodeWhale
content-watch.test.ts
根目录 / web / lib / content-watch.test.ts
1 import { describe, it, expect, vi, beforeEach, afterEach, type Mock } from "vitest";
2
3 vi.mock("./community-agent", async (importOriginal) => {
4 const actual = await importOriginal<typeof import("./community-agent")>();
5 return { ...actual, agentChat: vi.fn() };
6 });
7
8 import { FakeDraftClaimLock } from "./draft-claim-lock.fake";
9 import { runLinkCheck, runSemanticDrift, watchDraftId } from "./content-watch";
10 import { agentChat, deleteDraft, draftStorageKey, markDraftResolved, type AgentDraft } from "./community-agent";
11
12 const agentChatMock = agentChat as Mock;
13
14 function createFakeKV() {
15 const store = new Map<string, string>();
16 return {
17 store,
18 lock: new FakeDraftClaimLock(),
19 async get(key: string): Promise<string | null> {
20 return store.get(key) ?? null;
21 },
22 async put(key: string, value: string): Promise<void> {
23 store.set(key, value);
24 },
25 async list(opts?: { prefix?: string; limit?: number }): Promise<{ keys: { name: string }[] }> {
26 const prefix = opts?.prefix ?? "";
27 const limit = opts?.limit ?? 100;
28 return {
29 keys: [...store.keys()]
30 .filter((k) => k.startsWith(prefix))
31 .slice(0, limit)
32 .map((name) => ({ name })),
33 };
34 },
35 async delete(key: string): Promise<void> {
36 store.delete(key);
37 },
38 };
39 }
40
41 type FakeKV = ReturnType<typeof createFakeKV>;
42
43 function draftEntries(kv: FakeKV): [string, AgentDraft][] {
44 return [...kv.store.entries()]
45 .filter(([key]) => key.startsWith("draft:"))
46 .map(([key, value]) => [key, JSON.parse(value) as AgentDraft] as [string, AgentDraft]);
47 }
48
49 function okResponse(body = ""): Response {
50 return new Response(body, { status: 200 });
51 }
52
53 describe("runLinkCheck draft identity", () => {
54 let kv: FakeKV;
55
56 beforeEach(() => {
57 kv = createFakeKV();
58 // Break exactly one target; everything else answers 200 to HEAD.
59 vi.stubGlobal(
60 "fetch",
61 vi.fn(async (input: RequestInfo | URL) => {
62 const url = String(input);
63 return url === "https://buymeacoffee.com/hmbown"
64 ? new Response("broken", { status: 500 })
65 : okResponse();
66 })
67 );
68 });
69
70 afterEach(() => {
71 vi.unstubAllGlobals();
72 });
73
74 it("creates a linkcheck draft under the canonical key on first run", async () => {
75 const result = await runLinkCheck({ CURATED_KV: kv, DRAFT_CLAIM_LOCK: kv.lock });
76
77 expect(result.ok).toBe(true);
78 expect(result.broken).toBe(1);
79
80 const drafts = draftEntries(kv);
81 expect(drafts).toHaveLength(1);
82 const [key, draft] = drafts[0];
83 expect(draft.type).toBe("linkcheck");
84 expect(draft.targetUrl).toBe("https://buymeacoffee.com/hmbown");
85 expect(key).toBe(draftStorageKey(draft));
86 expect(key.startsWith("draft:linkcheck:")).toBe(true);
87 expect(draft.id.length).toBeLessThanOrEqual(80);
88 });
89
90 it("creates no duplicate when the same breakage is seen again", async () => {
91 await runLinkCheck({ CURATED_KV: kv, DRAFT_CLAIM_LOCK: kv.lock });
92 const second = await runLinkCheck({ CURATED_KV: kv, DRAFT_CLAIM_LOCK: kv.lock });
93
94 expect(second.broken).toBe(1); // still broken…
95 expect(draftEntries(kv)).toHaveLength(1); // …but not re-drafted
96 });
97 });
98
99 describe("runSemanticDrift draft identity", () => {
100 let kv: FakeKV;
101
102 const env = () => ({ CURATED_KV: kv, DRAFT_CLAIM_LOCK: kv.lock, DEEPSEEK_API_KEY: "test-key" });
103
104 function mockSources() {
105 vi.stubGlobal(
106 "fetch",
107 vi.fn(async (input: RequestInfo | URL) => {
108 const { hostname } = new URL(String(input));
109 if (hostname === "api.github.com") return new Response("[]", { status: 200 });
110 if (hostname === "raw.githubusercontent.com") return okResponse("# Changelog\n- things");
111 return okResponse("<html><body>site copy</body></html>");
112 })
113 );
114 }
115
116 function mockDrifts(drifts: unknown) {
117 agentChatMock.mockResolvedValue({
118 content: JSON.stringify({ drifts }),
119 usage: { input: 0, output: 0 },
120 });
121 }
122
123 const finding = {
124 page: "homepage",
125 claim: "Codewhale supports three modes",
126 evidence: "CHANGELOG: modes renamed in 0.9.0",
127 suggested_replacement: "Codewhale supports Plan / Work / Operate",
128 };
129
130 beforeEach(() => {
131 kv = createFakeKV();
132 agentChatMock.mockReset();
133 mockSources();
134 });
135
136 afterEach(() => {
137 vi.unstubAllGlobals();
138 });
139
140 it("creates a semantic-drift draft under the canonical key on first run", async () => {
141 mockDrifts([finding]);
142 const result = await runSemanticDrift(env());
143
144 expect(result).toEqual({ ok: true, drafted: 1 });
145 const drafts = draftEntries(kv);
146 expect(drafts).toHaveLength(1);
147 const [key, draft] = drafts[0];
148 expect(draft.type).toBe("semantic-drift");
149 expect(key).toBe(draftStorageKey(draft));
150 expect(key.startsWith("draft:semantic-drift:")).toBe(true);
151 });
152
153 it("creates no duplicate when the same finding is reported again", async () => {
154 mockDrifts([finding]);
155 await runSemanticDrift(env());
156 const second = await runSemanticDrift(env());
157
158 expect(second).toEqual({ ok: true, drafted: 0 });
159 expect(draftEntries(kv)).toHaveLength(1);
160 });
161
162 it("does not count a finding the maintainer already discarded as drafted", async () => {
163 mockDrifts([finding]);
164 await runSemanticDrift(env());
165 const [[key, draft]] = draftEntries(kv);
166 await markDraftResolved(kv, "semantic-drift", draft.id, "discarded");
167 await deleteDraft(kv, key);
168
169 const second = await runSemanticDrift(env());
170
171 expect(second).toEqual({ ok: true, drafted: 0 });
172 expect(draftEntries(kv)).toHaveLength(0);
173 });
174
175 it("creates a new draft when the finding's evidence changes", async () => {
176 mockDrifts([finding]);
177 await runSemanticDrift(env());
178
179 mockDrifts([{ ...finding, evidence: "CHANGELOG: modes renamed in 0.9.1" }]);
180 const second = await runSemanticDrift(env());
181
182 expect(second).toEqual({ ok: true, drafted: 1 });
183 expect(draftEntries(kv)).toHaveLength(2);
184 });
185
186 it("does not collide findings whose truncated slug prefixes are identical", async () => {
187 const sharedPrefix = "a".repeat(120);
188 const first = { ...finding, claim: `${sharedPrefix}-first-variant` };
189 const second = { ...finding, claim: `${sharedPrefix}-second-variant` };
190 mockDrifts([first, second]);
191
192 const result = await runSemanticDrift(env());
193
194 expect(result).toEqual({ ok: true, drafted: 2 });
195 const drafts = draftEntries(kv);
196 expect(drafts).toHaveLength(2);
197 const keys = drafts.map(([key]) => key);
198 expect(new Set(keys).size).toBe(2);
199 for (const [, draft] of drafts) {
200 expect(draft.id.length).toBeLessThanOrEqual(80);
201 }
202 });
203
204 it("bounds excessive model output and skips malformed entries", async () => {
205 const flood = Array.from({ length: 500 }, (_, i) => ({
206 ...finding,
207 claim: `claim number ${i}`,
208 }));
209 const malformed = [
210 { page: "evil-page", claim: "x", evidence: "y", suggested_replacement: "z" },
211 { page: "homepage", claim: "", evidence: "y", suggested_replacement: "z" },
212 { page: "homepage", claim: "x", evidence: 42, suggested_replacement: "z" },
213 "not-an-object",
214 null,
215 ];
216 mockDrifts([...malformed, ...flood]);
217
218 const result = await runSemanticDrift(env());
219
220 expect(result.ok).toBe(true);
221 expect(result.drafted).toBe(10); // MAX_DRIFT_DRAFTS_PER_RUN
222 expect(draftEntries(kv)).toHaveLength(10);
223 });
224
225 it("treats a non-array drifts payload as empty", async () => {
226 mockDrifts(undefined);
227 const result = await runSemanticDrift(env());
228 expect(result).toEqual({ ok: true, drafted: 0 });
229 });
230 });
231
232 describe("watchDraftId", () => {
233 it("is deterministic for the same identity", async () => {
234 const a = await watchDraftId("some-slug", "identity");
235 const b = await watchDraftId("some-slug", "identity");
236 expect(a).toBe(b);
237 });
238
239 it("separates identities that share a long slug prefix", async () => {
240 const prefix = `https://example.com/${"a".repeat(120)}`;
241 const a = await watchDraftId(prefix, `linkcheck\n${prefix}?x=1`);
242 const b = await watchDraftId(prefix, `linkcheck\n${prefix}?x=2`);
243 expect(a).not.toBe(b);
244 expect(a.length).toBeLessThanOrEqual(80);
245 expect(b.length).toBeLessThanOrEqual(80);
246 });
247 });
248
248 lines TYPESCRIPT