返回 CodeWhale
community-agent-review-state.test.ts
根目录 / web / lib / community-agent-review-state.test.ts
1 import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2
3 const mocks = vi.hoisted(() => ({
4 agentChat: vi.fn(),
5 getAgentEnv: vi.fn(),
6 validateSession: vi.fn(),
7 fetchRepoStats: vi.fn(),
8 }));
9
10 vi.mock("@/lib/community-agent", async (importOriginal) => {
11 const actual = await importOriginal<typeof import("./community-agent")>();
12 return {
13 ...actual,
14 agentChat: mocks.agentChat,
15 getAgentEnv: mocks.getAgentEnv,
16 validateSession: mocks.validateSession,
17 };
18 });
19
20 vi.mock("@/lib/github", async (importOriginal) => {
21 const actual = await importOriginal<typeof import("./github")>();
22 return { ...actual, fetchRepoStats: mocks.fetchRepoStats };
23 });
24
25 import { POST as adminPost } from "../app/api/admin/post/route";
26 import {
27 isPublishedDigest,
28 listDrafts,
29 MAX_LISTED_DRAFTS,
30 reviewedBodyHash,
31 saveDraft,
32 type AgentDraft,
33 } from "./community-agent";
34 import { runDigest } from "./community-agent-tasks";
35 import { FakeDraftClaimLock } from "./draft-claim-lock.fake";
36
37 /** In-memory KV that pages like Cloudflare KV (max 1000 keys per list call). */
38 class FakeKv {
39 readonly draftStores = { CURATED_KV: this, DRAFT_CLAIM_LOCK: new FakeDraftClaimLock() };
40 readonly values = new Map<string, string>();
41 failPutsMatching: RegExp | null = null;
42 /** Yield to the event loop inside every call, like a network round trip. */
43 yieldEachOp = false;
44 pageSize = 1000;
45 failListAtCursor: string | null = null;
46 /** Awaited before a put lands, to hold a request at an exact step. */
47 beforePut: ((key: string, value: string) => Promise<void>) | null = null;
48
49 private async tick() {
50 if (this.yieldEachOp) await new Promise((resolve) => setTimeout(resolve, 0));
51 }
52
53 async get(key: string): Promise<string | null> {
54 await this.tick();
55 return this.values.get(key) ?? null;
56 }
57
58 async put(key: string, value: string): Promise<void> {
59 await this.tick();
60 if (this.beforePut) await this.beforePut(key, value);
61 if (this.failPutsMatching?.test(key)) throw new Error("kv put failed");
62 this.values.set(key, value);
63 }
64
65 async list(options?: { prefix?: string; limit?: number; cursor?: string }) {
66 if (options?.cursor && options.cursor === this.failListAtCursor) throw new Error("kv list failed");
67 const prefix = options?.prefix ?? "";
68 const limit = Math.min(options?.limit ?? 1000, this.pageSize);
69 const start = options?.cursor ? Number(options.cursor) : 0;
70 const all = [...this.values.keys()].filter((k) => k.startsWith(prefix)).sort();
71 const page = all.slice(start, start + limit);
72 const next = start + page.length;
73 const complete = next >= all.length;
74 return {
75 keys: page.map((name) => ({ name })),
76 list_complete: complete,
77 ...(complete ? {} : { cursor: String(next) }),
78 };
79 }
80
81 async delete(key: string): Promise<void> {
82 this.values.delete(key);
83 }
84 }
85
86 function draft(overrides: Partial<AgentDraft> = {}): AgentDraft {
87 return {
88 id: "42",
89 type: "linkcheck",
90 targetNumber: 42,
91 bodyEn: "English body",
92 bodyZh: "中文正文",
93 generatedAt: "2026-01-01T00:00:00.000Z",
94 posted: false,
95 ...overrides,
96 };
97 }
98
99 function jsonResponse(value: unknown, status = 200): Response {
100 return new Response(JSON.stringify(value), { status, headers: { "content-type": "application/json" } });
101 }
102
103 function inputUrl(input: string | URL | Request): string {
104 if (typeof input === "string") return input;
105 return input instanceof URL ? input.toString() : input.url;
106 }
107
108 function adminRequest(body: BodyInit, headers: Record<string, string> = {}): Request {
109 return new Request("https://codewhale.net/api/admin/post", {
110 method: "POST",
111 headers: {
112 "content-type": "application/json",
113 cookie: "mt_sid=test-session",
114 origin: "https://codewhale.net",
115 ...headers,
116 },
117 body,
118 // Required by undici for a streamed request body.
119 ...(body instanceof ReadableStream ? { duplex: "half" } : {}),
120 } as RequestInit);
121 }
122
123 function postBody(value: Record<string, unknown>): string {
124 return JSON.stringify(value);
125 }
126
127 /**
128 * An admin action as the admin page sends it: bound to the stored draft text
129 * in the selected language, as shown to the maintainer.
130 */
131 async function act(kv: FakeKv, fields: Record<string, unknown>): Promise<Response> {
132 let reviewedSha256 = fields.reviewedSha256;
133 if (reviewedSha256 === undefined) {
134 const raw = kv.values.get(String(fields.draftKey));
135 const stored = raw ? (JSON.parse(raw) as AgentDraft) : null;
136 reviewedSha256 = await reviewedBodyHash(
137 stored ? (fields.lang === "zh" ? stored.bodyZh : stored.bodyEn) : ""
138 );
139 }
140 return adminPost(adminRequest(postBody({ ...fields, reviewedSha256 })));
141 }
142
143 function stubAdminEnv(kv: FakeKv, lock?: FakeDraftClaimLock) {
144 mocks.getAgentEnv.mockResolvedValue({
145 CURATED_KV: kv,
146 ...(lock ? { DRAFT_CLAIM_LOCK: lock } : {}),
147 MAINTAINER_TOKEN: "local-fixture-token-0123456789-abcdefghij",
148 MAINTAINER_GITHUB_PAT: "ghp_test",
149 GITHUB_REPO: "codewhale-hq/CodeWhale",
150 });
151 }
152
153 /**
154 * GitHub stub that records every comment/issue creation. Reads (the lookup
155 * for an earlier unknown-outcome post) answer `existing` and are not posts.
156 */
157 function stubGitHub(status = 201, existing: unknown[] = []) {
158 const posts: string[] = [];
159 const fetchMock = vi.fn(async (input: string | URL | Request, init?: RequestInit) => {
160 const url = inputUrl(input);
161 if ((init?.method ?? "GET") === "GET") return jsonResponse(existing);
162 posts.push(url);
163 if (url.endsWith("/issues")) {
164 return jsonResponse({ number: 900, html_url: "https://github.com/codewhale-hq/CodeWhale/issues/900" }, status);
165 }
166 return jsonResponse({ id: 1 }, status);
167 });
168 vi.stubGlobal("fetch", fetchMock);
169 return posts;
170 }
171
172 const DIGEST_MODEL_OUTPUT = {
173 titleEn: "Weekly Digest",
174 titleZh: "每周摘要",
175 summaryEn: "A quiet week.",
176 summaryZh: "平静的一周。",
177 sections: [{ heading: "Shipped", items: ["PR #1: fix"] }],
178 };
179
180 function stubDigestSources() {
181 mocks.fetchRepoStats.mockResolvedValue({ stars: 1, forks: 1 });
182 vi.stubGlobal("fetch", vi.fn(async (input: string | URL | Request) => {
183 const url = inputUrl(input);
184 if (url.includes("/issues?") || url.includes("/pulls?")) return jsonResponse([]);
185 throw new Error(`unexpected URL: ${url}`);
186 }));
187 }
188
189 function onlyKey(kv: FakeKv, prefix: string): string {
190 const keys = [...kv.values.keys()].filter((k) => k.startsWith(prefix));
191 expect(keys).toHaveLength(1);
192 return keys[0];
193 }
194
195 beforeEach(() => {
196 mocks.agentChat.mockReset();
197 mocks.getAgentEnv.mockReset();
198 mocks.fetchRepoStats.mockReset();
199 mocks.validateSession.mockReset();
200 mocks.validateSession.mockResolvedValue(true);
201 });
202
203 afterEach(() => {
204 vi.unstubAllGlobals();
205 });
206
207 describe("weekly digest publication requires maintainer approval", () => {
208 it("stages the cron digest unapproved and publishes it only when the maintainer posts it", async () => {
209 const kv = new FakeKv();
210 stubDigestSources();
211 // Model output cannot self-approve.
212 mocks.agentChat.mockResolvedValue({
213 content: JSON.stringify({ ...DIGEST_MODEL_OUTPUT, approved: true }),
214 usage: { input: 1, output: 1 },
215 });
216
217 await expect(runDigest({ CURATED_KV: kv, DRAFT_CLAIM_LOCK: new FakeDraftClaimLock(), DEEPSEEK_API_KEY: "k" })).resolves.toMatchObject({ ok: true });
218 const recordKey = onlyKey(kv, "digest:weekly-");
219 const staged: unknown = JSON.parse(kv.values.get(recordKey)!);
220 expect(staged).toMatchObject({ approved: false });
221 expect(isPublishedDigest(staged)).toBe(false);
222
223 stubAdminEnv(kv);
224 const posts = stubGitHub();
225 const draftKey = onlyKey(kv, "draft:digest:");
226 const res = await act(kv, { action: "post", draftKey, lang: "en" });
227 await expect(res.json()).resolves.toMatchObject({ ok: true, published: true, number: 900 });
228 expect(posts).toHaveLength(1);
229 const published = JSON.parse(kv.values.get(recordKey)!);
230 expect(isPublishedDigest(published)).toBe(true);
231 // Only the reviewed language is published.
232 expect(published).toMatchObject({ approvedLang: "en" });
233 });
234
235 it("records the Chinese review as the published language when posted from the zh admin", async () => {
236 const kv = new FakeKv();
237 stubDigestSources();
238 mocks.agentChat.mockResolvedValue({ content: JSON.stringify(DIGEST_MODEL_OUTPUT), usage: { input: 1, output: 1 } });
239 await runDigest({ CURATED_KV: kv, DRAFT_CLAIM_LOCK: new FakeDraftClaimLock(), DEEPSEEK_API_KEY: "k" });
240
241 stubAdminEnv(kv);
242 stubGitHub();
243 const draftKey = onlyKey(kv, "draft:digest:");
244 const res = await act(kv, { action: "post", draftKey, lang: "zh" });
245 await expect(res.json()).resolves.toMatchObject({ ok: true, published: true });
246 expect(JSON.parse(kv.values.get(onlyKey(kv, "digest:weekly-"))!)).toMatchObject({ approvedLang: "zh" });
247 });
248
249 it("refuses to discard a posted digest, which would silently unpublish it", async () => {
250 const kv = new FakeKv();
251 stubDigestSources();
252 mocks.agentChat.mockResolvedValue({ content: JSON.stringify(DIGEST_MODEL_OUTPUT), usage: { input: 1, output: 1 } });
253 await runDigest({ CURATED_KV: kv, DRAFT_CLAIM_LOCK: new FakeDraftClaimLock(), DEEPSEEK_API_KEY: "k" });
254
255 stubAdminEnv(kv);
256 stubGitHub();
257 const draftKey = onlyKey(kv, "draft:digest:");
258 expect((await act(kv, { action: "post", draftKey, lang: "en" })).status).toBe(200);
259
260 const discard = await act(kv, { action: "discard", draftKey });
261 expect(discard.status).toBe(409);
262 expect(isPublishedDigest(JSON.parse(kv.values.get(onlyKey(kv, "digest:weekly-"))!))).toBe(true);
263 });
264
265 it("does not publish an edited digest's unedited model text", async () => {
266 const kv = new FakeKv();
267 stubDigestSources();
268 mocks.agentChat.mockResolvedValue({ content: JSON.stringify(DIGEST_MODEL_OUTPUT), usage: { input: 1, output: 1 } });
269 await runDigest({ CURATED_KV: kv, DRAFT_CLAIM_LOCK: new FakeDraftClaimLock(), DEEPSEEK_API_KEY: "k" });
270
271 stubAdminEnv(kv);
272 stubGitHub();
273 const draftKey = onlyKey(kv, "draft:digest:");
274 const res = await act(kv, { action: "post", draftKey, lang: "en", editedBody: "# Edited" });
275 // The maintainer is told why the digest is not on /digest.
276 await expect(res.json()).resolves.toMatchObject({
277 ok: true,
278 published: false,
279 warning: expect.stringContaining("/digest"),
280 });
281 expect(isPublishedDigest(JSON.parse(kv.values.get(onlyKey(kv, "digest:weekly-"))!))).toBe(false);
282 });
283
284 it("discarding a digest removes the staged record and the cron does not regenerate it", async () => {
285 const kv = new FakeKv();
286 stubDigestSources();
287 mocks.agentChat.mockResolvedValue({ content: JSON.stringify(DIGEST_MODEL_OUTPUT), usage: { input: 1, output: 1 } });
288 await runDigest({ CURATED_KV: kv, DRAFT_CLAIM_LOCK: new FakeDraftClaimLock(), DEEPSEEK_API_KEY: "k" });
289
290 stubAdminEnv(kv);
291 const draftKey = onlyKey(kv, "draft:digest:");
292 const res = await act(kv, { action: "discard", draftKey });
293 await expect(res.json()).resolves.toMatchObject({ ok: true, action: "discarded" });
294 expect([...kv.values.keys()].filter((k) => k.startsWith("digest:weekly-"))).toEqual([]);
295
296 mocks.agentChat.mockClear();
297 await expect(runDigest({ CURATED_KV: kv, DRAFT_CLAIM_LOCK: new FakeDraftClaimLock(), DEEPSEEK_API_KEY: "k" })).resolves.toMatchObject({ skipped: true });
298 expect(mocks.agentChat).not.toHaveBeenCalled();
299 expect(kv.values.has(draftKey)).toBe(false);
300 });
301
302 it("surfaces a GitHub failure on a digest post as a 502 and does not publish", async () => {
303 const kv = new FakeKv();
304 stubDigestSources();
305 mocks.agentChat.mockResolvedValue({ content: JSON.stringify(DIGEST_MODEL_OUTPUT), usage: { input: 1, output: 1 } });
306 await runDigest({ CURATED_KV: kv, DRAFT_CLAIM_LOCK: new FakeDraftClaimLock(), DEEPSEEK_API_KEY: "k" });
307
308 stubAdminEnv(kv);
309 stubGitHub(422);
310 const draftKey = onlyKey(kv, "draft:digest:");
311 const res = await act(kv, { action: "post", draftKey, lang: "en" });
312 expect(res.status).toBe(502);
313 const payload = await res.json();
314 expect(payload.ok).toBeUndefined();
315 expect(payload.error).toMatch(/^GitHub 422/);
316 expect(isPublishedDigest(JSON.parse(kv.values.get(onlyKey(kv, "digest:weekly-"))!))).toBe(false);
317 });
318
319 it("finds a digest issue an unknown-outcome attempt created and publishes without a second issue", async () => {
320 const kv = new FakeKv();
321 stubDigestSources();
322 mocks.agentChat.mockResolvedValue({ content: JSON.stringify(DIGEST_MODEL_OUTPUT), usage: { input: 1, output: 1 } });
323 await runDigest({ CURATED_KV: kv, DRAFT_CLAIM_LOCK: new FakeDraftClaimLock(), DEEPSEEK_API_KEY: "k" });
324 stubAdminEnv(kv);
325 const draftKey = onlyKey(kv, "draft:digest:");
326 stubGitHub(504);
327 expect((await act(kv, { action: "post", draftKey, lang: "en" })).status).toBe(502);
328 // The claim and "posting" marker lapse (15 minutes in production).
329 for (const key of [...kv.values.keys()]) if (/^draft-(claim|resolved):digest:/.test(key)) kv.values.delete(key);
330
331 const body = JSON.parse(kv.values.get(draftKey)!).bodyEn as string;
332 const title = body.split("\n")[0].replace(/^#+\s*/, "").trim();
333 const posts = stubGitHub(201, [{ number: 901, html_url: "https://github.com/codewhale-hq/CodeWhale/issues/901", title, body }]);
334 const retry = await act(kv, { action: "post", draftKey, lang: "en" });
335 await expect(retry.json()).resolves.toMatchObject({ ok: true, number: 901, published: true });
336 expect(posts).toEqual([]);
337 });
338
339 it("never publishes an older record when a later run saved its draft but not its record", async () => {
340 const kv = new FakeKv();
341 stubDigestSources();
342 mocks.agentChat.mockResolvedValue({ content: JSON.stringify(DIGEST_MODEL_OUTPUT), usage: { input: 1, output: 1 } });
343 await runDigest({ CURATED_KV: kv, DRAFT_CLAIM_LOCK: new FakeDraftClaimLock(), DEEPSEEK_API_KEY: "k" });
344 const recordKey = onlyKey(kv, "digest:weekly-");
345 const recordA = kv.values.get(recordKey)!;
346
347 // Run B saves its draft, then its record write fails: draft B + record A.
348 mocks.agentChat.mockResolvedValue({
349 content: JSON.stringify({ ...DIGEST_MODEL_OUTPUT, titleEn: "Digest B", summaryEn: "Run B." }),
350 usage: { input: 1, output: 1 },
351 });
352 kv.failPutsMatching = /^digest:weekly-/;
353 await expect(runDigest({ CURATED_KV: kv, DRAFT_CLAIM_LOCK: new FakeDraftClaimLock(), DEEPSEEK_API_KEY: "k" })).resolves.toMatchObject({ ok: false });
354 kv.failPutsMatching = null;
355 const draftKey = onlyKey(kv, "draft:digest:");
356 expect(JSON.parse(kv.values.get(draftKey)!).bodyEn).toContain("Digest B");
357 expect(kv.values.get(recordKey)).toBe(recordA);
358
359 stubAdminEnv(kv);
360 const bodies: string[] = [];
361 vi.stubGlobal("fetch", vi.fn(async (_input: string | URL | Request, init?: RequestInit) => {
362 bodies.push(String(init?.body));
363 return jsonResponse({ number: 900, html_url: "https://github.com/codewhale-hq/CodeWhale/issues/900" }, 201);
364 }));
365 const res = await act(kv, { action: "post", draftKey, lang: "en" });
366 await expect(res.json()).resolves.toMatchObject({
367 ok: true,
368 published: false,
369 warning: expect.stringContaining("does not match the reviewed text"),
370 });
371 // GitHub got the reviewed B; /digest shows nothing rather than A.
372 expect(bodies).toHaveLength(1);
373 expect(JSON.parse(bodies[0]).title).toBe("Digest B");
374 expect(isPublishedDigest(JSON.parse(kv.values.get(recordKey)!))).toBe(false);
375 });
376
377 it("publishes only the fields of a record that matches the reviewed text", async () => {
378 const kv = new FakeKv();
379 stubDigestSources();
380 mocks.agentChat.mockResolvedValue({ content: JSON.stringify(DIGEST_MODEL_OUTPUT), usage: { input: 1, output: 1 } });
381 await runDigest({ CURATED_KV: kv, DRAFT_CLAIM_LOCK: new FakeDraftClaimLock(), DEEPSEEK_API_KEY: "k" });
382 const recordKey = onlyKey(kv, "digest:weekly-");
383 kv.values.set(recordKey, JSON.stringify({ ...JSON.parse(kv.values.get(recordKey)!), extra: "<script>" }));
384
385 stubAdminEnv(kv);
386 stubGitHub();
387 const draftKey = onlyKey(kv, "draft:digest:");
388 await expect((await act(kv, { action: "post", draftKey, lang: "zh" })).json()).resolves.toMatchObject({
389 published: true,
390 });
391 const published = JSON.parse(kv.values.get(recordKey)!);
392 expect(isPublishedDigest(published)).toBe(true);
393 expect(published).not.toHaveProperty("extra");
394 expect(published).toMatchObject({ approvedLang: "zh", titleZh: DIGEST_MODEL_OUTPUT.titleZh });
395 });
396
397 it("hides legacy records that were never approved", () => {
398 const legacy = { ...DIGEST_MODEL_OUTPUT, weekId: "2026-W01", generatedAt: "2026-01-05T00:00:00.000Z" };
399 expect(isPublishedDigest(legacy)).toBe(false);
400 expect(isPublishedDigest({ ...legacy, approved: true })).toBe(false);
401 expect(isPublishedDigest({ ...legacy, approved: true, approvedLang: "en" })).toBe(true);
402 expect(
403 isPublishedDigest({ ...legacy, approved: true, approvedLang: "en", sections: [{ heading: "x", items: [1] }] })
404 ).toBe(false);
405 });
406 });
407
408 describe("admin post action is idempotent and bounded", () => {
409 it("refuses to post a draft that is already posted", async () => {
410 const kv = new FakeKv();
411 kv.values.set("draft:linkcheck:42", JSON.stringify(draft({ posted: true })));
412 stubAdminEnv(kv);
413 const posts = stubGitHub();
414
415 const res = await act(kv, { action: "post", draftKey: "draft:linkcheck:42" });
416 expect(res.status).toBe(409);
417 expect(posts).toEqual([]);
418 });
419
420 it("returns ok when saving state fails after GitHub accepted the comment, and a retry does not post twice", async () => {
421 const kv = new FakeKv();
422 await saveDraft(kv.draftStores, draft());
423 stubAdminEnv(kv);
424 const posts = stubGitHub();
425 kv.failPutsMatching = /^draft:linkcheck:42$/;
426
427 const first = await act(kv, { action: "post", draftKey: "draft:linkcheck:42" });
428 expect(first.status).toBe(200);
429 await expect(first.json()).resolves.toMatchObject({ ok: true, action: "posted", warning: expect.any(String) });
430
431 const retry = await act(kv, { action: "post", draftKey: "draft:linkcheck:42" });
432 expect(retry.status).toBe(409);
433 expect(posts).toHaveLength(1);
434 });
435
436 it("releases the claim when GitHub rejects the post so the maintainer can retry", async () => {
437 const kv = new FakeKv();
438 await saveDraft(kv.draftStores, draft());
439 stubAdminEnv(kv);
440 stubGitHub(422);
441
442 const failed = await act(kv, { action: "post", draftKey: "draft:linkcheck:42" });
443 expect(failed.status).toBe(502);
444
445 const posts = stubGitHub();
446 const retry = await act(kv, { action: "post", draftKey: "draft:linkcheck:42" });
447 expect(retry.status).toBe(200);
448 expect(posts).toHaveLength(1);
449 });
450
451 it.each([500, 502, 504, 429])(
452 "keeps the claim when GitHub answers %i, since the post may have been created",
453 async (status) => {
454 const kv = new FakeKv();
455 await saveDraft(kv.draftStores, draft());
456 stubAdminEnv(kv);
457 const posts = stubGitHub(status);
458
459 const failed = await act(kv, { action: "post", draftKey: "draft:linkcheck:42" });
460 expect(failed.status).toBe(502);
461 await expect(failed.json()).resolves.toMatchObject({ error: expect.stringContaining("check GitHub before retrying") });
462
463 stubGitHub();
464 const retry = await act(kv, { action: "post", draftKey: "draft:linkcheck:42" });
465 expect(retry.status).toBe(409);
466 expect(posts).toHaveLength(1);
467 }
468 );
469
470 it("never posts twice when two requests for the same draft race", async () => {
471 const kv = new FakeKv();
472 await saveDraft(kv.draftStores, draft());
473 kv.yieldEachOp = true;
474 stubAdminEnv(kv);
475 const posts = stubGitHub();
476
477 const results = await Promise.all([
478 act(kv, { action: "post", draftKey: "draft:linkcheck:42" }),
479 act(kv, { action: "post", draftKey: "draft:linkcheck:42" }),
480 ]);
481 const statuses = results.map((r) => r.status);
482 // This fake KV makes every write visible at once, so the claim is exact
483 // here; on Workers KV it is best effort (see claimDraft).
484 expect(statuses.filter((s) => s === 200)).toHaveLength(posts.length);
485 expect(posts.length).toBeLessThanOrEqual(1);
486 expect(statuses.every((s) => s === 200 || s === 409)).toBe(true);
487
488 // Refused claims are released, so the maintainer's retry posts exactly once.
489 if (posts.length === 0) {
490 expect((await act(kv, { action: "post", draftKey: "draft:linkcheck:42" })).status).toBe(200);
491 }
492 expect(posts).toHaveLength(1);
493 expect((await act(kv, { action: "post", draftKey: "draft:linkcheck:42" })).status).toBe(409);
494 expect(posts).toHaveLength(1);
495 });
496
497 /**
498 * Hold two admin actions at the reviewer's interleaving: both pass the
499 * "no decision yet" check, the first takes its claim and reaches GitHub,
500 * and only then does the second's claim write land.
501 */
502 function raceAfterAbsenceChecks(kv: FakeKv) {
503 let prechecks = 0;
504 let bothChecked!: () => void;
505 const bothCheckedP = new Promise<void>((resolve) => (bothChecked = resolve));
506 let firstAtGitHub!: () => void;
507 const firstAtGitHubP = new Promise<void>((resolve) => (firstAtGitHub = resolve));
508 const realGet = kv.get.bind(kv);
509 kv.get = async (key: string) => {
510 const value = await realGet(key);
511 if (key.startsWith("draft-resolved:") && ++prechecks === 2) bothChecked();
512 return value;
513 };
514 let claimPuts = 0;
515 kv.beforePut = async (key, value) => {
516 const isClaim = key.startsWith("draft-claim:") || (key.startsWith("draft-resolved:") && value.includes('"claim"'));
517 if (!isClaim) return;
518 // A discard only ever overlaps a post already at GitHub. Gate it on
519 // that directly so the test does not depend on which request the
520 // scheduler lets claim first (a discard claiming first would park the
521 // post forever waiting for a GitHub call that never happens).
522 if (value.startsWith("discard:") || value.includes('"discard')) {
523 await firstAtGitHubP;
524 return;
525 }
526 claimPuts += 1;
527 await (claimPuts === 1 ? bothCheckedP : firstAtGitHubP);
528 };
529 const posts: string[] = [];
530 vi.stubGlobal("fetch", vi.fn(async (input: string | URL | Request) => {
531 posts.push(inputUrl(input));
532 firstAtGitHub();
533 // Let the second request finish its claim while this post is in flight.
534 await new Promise((resolve) => setTimeout(resolve, 20));
535 return jsonResponse({ id: 1 }, 201);
536 }));
537 return posts;
538 }
539
540 it("refuses a second post whose claim lands while the first is at GitHub", async () => {
541 const kv = new FakeKv();
542 await saveDraft(kv.draftStores, draft());
543 kv.yieldEachOp = true;
544 stubAdminEnv(kv);
545 const posts = raceAfterAbsenceChecks(kv);
546
547 const results = await Promise.all([
548 act(kv, { action: "post", draftKey: "draft:linkcheck:42" }),
549 act(kv, { action: "post", draftKey: "draft:linkcheck:42" }),
550 ]);
551
552 expect(results.map((r) => r.status).sort()).toEqual([200, 409]);
553 expect(posts).toHaveLength(1);
554 });
555
556 it("refuses a discard that overlaps an in-flight post of the same draft", async () => {
557 const kv = new FakeKv();
558 await saveDraft(kv.draftStores, draft());
559 kv.yieldEachOp = true;
560 stubAdminEnv(kv);
561 const posts = raceAfterAbsenceChecks(kv);
562
563 const [post, discard] = await Promise.all([
564 act(kv, { action: "post", draftKey: "draft:linkcheck:42" }),
565 act(kv, { action: "discard", draftKey: "draft:linkcheck:42" }),
566 ]);
567
568 expect(post.status).toBe(200);
569 expect(discard.status).toBe(409);
570 expect(posts).toHaveLength(1);
571 expect(JSON.parse(kv.values.get("draft-resolved:linkcheck:42")!)).toMatchObject({ state: "posted" });
572 expect(JSON.parse(kv.values.get("draft:linkcheck:42")!)).toMatchObject({ posted: true });
573 });
574
575 it("claims without KV list, whose results can lag writes by up to a minute", async () => {
576 const kv = new FakeKv();
577 await saveDraft(kv.draftStores, draft());
578 stubAdminEnv(kv);
579 const posts = stubGitHub();
580 // A stale listing that never shows claim keys must not affect the claim.
581 const realList = kv.list.bind(kv);
582 kv.list = async (options) => {
583 if (options?.prefix?.startsWith("draft-claim:")) throw new Error("claim must not list");
584 return realList(options);
585 };
586
587 const res = await act(kv, { action: "post", draftKey: "draft:linkcheck:42" });
588 expect(res.status).toBe(200);
589 expect(posts).toHaveLength(1);
590 expect([...kv.values.keys()].filter((k) => k.startsWith("draft-claim:"))).toEqual([]);
591 });
592
593 it("answers a claim it cannot read back as retryable, not as a lost race, and the retry posts", async () => {
594 const kv = new FakeKv();
595 await saveDraft(kv.draftStores, draft());
596 stubAdminEnv(kv);
597 const posts = stubGitHub();
598 // The first read-back of the request's own claim misses the write.
599 const realGet = kv.get.bind(kv);
600 let claimReads = 0;
601 kv.get = async (key: string) => {
602 if (key.startsWith("draft-claim:") && ++claimReads === 2) return null;
603 return realGet(key);
604 };
605
606 const first = await act(kv, { action: "post", draftKey: "draft:linkcheck:42" });
607 expect(first.status).toBe(503);
608 expect(posts).toEqual([]);
609 expect([...kv.values.keys()].filter((k) => k.startsWith("draft-claim:") || k.startsWith("draft-resolved:"))).toEqual([]);
610
611 const retry = await act(kv, { action: "post", draftKey: "draft:linkcheck:42" });
612 expect(retry.status).toBe(200);
613 expect(posts).toHaveLength(1);
614 });
615
616 it("refuses a post while another request's claim is visible, and leaves that claim alone", async () => {
617 const kv = new FakeKv();
618 await saveDraft(kv.draftStores, draft());
619 stubAdminEnv(kv);
620 const posts = stubGitHub();
621 kv.values.set("draft-claim:linkcheck:42", "other-request");
622
623 for (const action of ["post", "discard"]) {
624 const res = await act(kv, { action, draftKey: "draft:linkcheck:42" });
625 expect(res.status).toBe(409);
626 }
627 expect(posts).toEqual([]);
628 expect(kv.values.get("draft-claim:linkcheck:42")).toBe("other-request");
629 });
630
631 it("treats a repeated discard as a no-op, including one that sees the marker only at claim time", async () => {
632 const kv = new FakeKv();
633 await saveDraft(kv.draftStores, draft());
634 stubAdminEnv(kv);
635 stubGitHub();
636
637 const first = await act(kv, { action: "discard", draftKey: "draft:linkcheck:42" });
638 expect(first.status).toBe(200);
639 // A double click whose request still reads the draft (its delete not yet
640 // visible), first past the marker, then with the marker missed by the
641 // route's own check and seen only by the claim.
642 const staleDraft = JSON.stringify(draft());
643 kv.values.set("draft:linkcheck:42", staleDraft);
644 const again = await act(kv, { action: "discard", draftKey: "draft:linkcheck:42" });
645 expect(again.status).toBe(200);
646 await expect(again.json()).resolves.toEqual({ ok: true, action: "discarded" });
647
648 kv.values.set("draft:linkcheck:42", staleDraft);
649 const realGet = kv.get.bind(kv);
650 let markerReads = 0;
651 kv.get = async (key: string) => {
652 if (key.startsWith("draft-resolved:") && ++markerReads === 1) return null;
653 return realGet(key);
654 };
655 const racing = await act(kv, { action: "discard", draftKey: "draft:linkcheck:42" });
656 expect(racing.status).toBe(200);
657 expect(JSON.parse(kv.values.get("draft-resolved:linkcheck:42")!)).toMatchObject({ state: "discarded" });
658 expect([...kv.values.keys()].filter((k) => k.startsWith("draft-claim:"))).toEqual([]);
659 });
660
661 it("refuses an action on a draft regenerated after the page loaded, before calling GitHub", async () => {
662 const kv = new FakeKv();
663 await saveDraft(kv.draftStores, draft({ bodyEn: "reviewed A" }));
664 stubAdminEnv(kv);
665 const shownA = await reviewedBodyHash("reviewed A");
666 // The cron regenerates the pending draft while the admin page shows A.
667 await saveDraft(kv.draftStores, draft({ bodyEn: "unseen B", generatedAt: "2026-01-02T00:00:00.000Z" }));
668 const posts = stubGitHub();
669
670 for (const action of ["post", "discard"]) {
671 const res = await act(kv, { action, draftKey: "draft:linkcheck:42", lang: "en", reviewedSha256: shownA });
672 expect(res.status).toBe(409);
673 await expect(res.json()).resolves.toMatchObject({ error: expect.stringContaining("changed") });
674 }
675 expect(posts).toEqual([]);
676 expect(JSON.parse(kv.values.get("draft:linkcheck:42")!)).toMatchObject({ bodyEn: "unseen B", posted: false });
677 expect([...kv.values.keys()].filter((k) => k.startsWith("draft-resolved:") || k.startsWith("draft-claim:"))).toEqual([]);
678 });
679
680 it("requires the reviewed-text hash", async () => {
681 const kv = new FakeKv();
682 await saveDraft(kv.draftStores, draft());
683 stubAdminEnv(kv);
684 const posts = stubGitHub();
685
686 const res = await adminPost(adminRequest(postBody({ action: "post", draftKey: "draft:linkcheck:42" })));
687 expect(res.status).toBe(400);
688 expect(posts).toEqual([]);
689 });
690
691 it("answers malformed JSON with a JSON 400", async () => {
692 const kv = new FakeKv();
693 stubAdminEnv(kv);
694
695 const res = await adminPost(adminRequest("{not json"));
696 expect(res.status).toBe(400);
697 await expect(res.json()).resolves.toEqual({ error: "invalid JSON body" });
698 });
699
700 it("counts streamed body bytes instead of trusting a missing Content-Length", async () => {
701 const kv = new FakeKv();
702 stubAdminEnv(kv);
703 const chunk = new TextEncoder().encode("x".repeat(40_000));
704 const stream = new ReadableStream<Uint8Array>({
705 start(controller) {
706 controller.enqueue(chunk);
707 controller.enqueue(chunk);
708 controller.close();
709 },
710 });
711
712 const res = await adminPost(adminRequest(stream));
713 expect(res.status).toBe(413);
714 });
715 });
716
717 describe("admin claims with the DRAFT_CLAIM_LOCK Durable Object bound", () => {
718 const KEY = "draft:linkcheck:42";
719
720 async function lockedAdmin(status = 201) {
721 const kv = new FakeKv();
722 await saveDraft(kv.draftStores, draft());
723 kv.yieldEachOp = true;
724 const lock = new FakeDraftClaimLock();
725 stubAdminEnv(kv, lock);
726 const claimKeysWritten: string[] = [];
727 kv.beforePut = async (key) => {
728 if (key.startsWith("draft-claim:")) claimKeysWritten.push(key);
729 };
730 const posts = stubGitHub(status);
731 return { kv, lock, posts, claimKeysWritten };
732 }
733
734 /** What a location whose KV has not yet seen the first request's writes reads. */
735 function forgetDecision(kv: FakeKv) {
736 kv.values.set(KEY, JSON.stringify(draft()));
737 kv.values.delete("draft-resolved:linkcheck:42");
738 }
739
740 it("lets exactly one of several concurrent posts through, without KV claim keys", async () => {
741 const { kv, lock, posts, claimKeysWritten } = await lockedAdmin();
742
743 const results = await Promise.all(
744 Array.from({ length: 4 }, () => act(kv, { action: "post", draftKey: KEY }))
745 );
746
747 expect(results.map((r) => r.status).sort()).toEqual([200, 409, 409, 409]);
748 expect(posts).toHaveLength(1);
749 expect(claimKeysWritten).toEqual([]);
750 expect(lock.calls.filter((c) => c.op === "claim")).toHaveLength(4);
751 });
752
753 it("refuses a retry that reads stale KV after a recorded post, until the hold ends", async () => {
754 const { kv, lock, posts } = await lockedAdmin();
755 expect((await act(kv, { action: "post", draftKey: KEY })).status).toBe(200);
756
757 forgetDecision(kv);
758 expect((await act(kv, { action: "post", draftKey: KEY })).status).toBe(409);
759 expect(posts).toHaveLength(1);
760
761 // Past the hold the KV marker has propagated; a location that really
762 // lacks it (a reopened draft) may act again.
763 lock.now += 2 * 60 * 1000;
764 forgetDecision(kv);
765 expect((await act(kv, { action: "post", draftKey: KEY })).status).toBe(200);
766 expect(posts).toHaveLength(2);
767 });
768
769 it("keeps the lease after an unknown GitHub outcome, and lets it expire", async () => {
770 const { kv, lock, posts } = await lockedAdmin(502);
771 expect((await act(kv, { action: "post", draftKey: KEY })).status).toBe(502);
772 stubGitHub();
773
774 // Even without the KV "posting" marker, the lease refuses a retry...
775 kv.values.delete("draft-resolved:linkcheck:42");
776 expect((await act(kv, { action: "post", draftKey: KEY })).status).toBe(409);
777 expect(posts).toHaveLength(1);
778
779 // ...until it expires, so the draft is not wedged for good.
780 lock.now += 15 * 60 * 1000;
781 const retryPosts = stubGitHub();
782 expect((await act(kv, { action: "post", draftKey: KEY })).status).toBe(200);
783 expect(retryPosts).toHaveLength(1);
784 });
785
786 it("looks for the earlier attempt's comment after an unknown outcome instead of posting it twice", async () => {
787 const { kv, lock } = await lockedAdmin(502);
788 expect((await act(kv, { action: "post", draftKey: KEY })).status).toBe(502);
789 lock.now += 15 * 60 * 1000;
790 kv.values.delete("draft-resolved:linkcheck:42");
791
792 // GitHub did create it: the late retry records it and posts nothing.
793 const posts = stubGitHub(201, [{ id: 7, body: "English body" }]);
794 const retry = await act(kv, { action: "post", draftKey: KEY });
795 expect(retry.status).toBe(200);
796 await expect(retry.json()).resolves.toMatchObject({ ok: true, action: "posted", warning: expect.stringContaining("not posted again") });
797 expect(posts).toEqual([]);
798 expect(JSON.parse(kv.values.get("draft-resolved:linkcheck:42")!).state).toBe("posted");
799 expect(kv.values.has("draft-post-unknown:linkcheck:42")).toBe(false);
800 });
801
802 it("posts nothing when the lookup for an earlier attempt fails, and frees the draft", async () => {
803 const { kv, lock } = await lockedAdmin(502);
804 expect((await act(kv, { action: "post", draftKey: KEY })).status).toBe(502);
805 lock.now += 15 * 60 * 1000;
806 kv.values.delete("draft-resolved:linkcheck:42");
807
808 const posts: string[] = [];
809 vi.stubGlobal("fetch", vi.fn(async (input: string | URL | Request, init?: RequestInit) => {
810 if ((init?.method ?? "GET") === "GET") return jsonResponse({ message: "down" }, 503);
811 posts.push(inputUrl(input));
812 return jsonResponse({ id: 1 }, 201);
813 }));
814 const blocked = await act(kv, { action: "post", draftKey: KEY });
815 expect(blocked.status).toBe(502);
816 await expect(blocked.json()).resolves.toMatchObject({ error: expect.stringContaining("nothing was posted") });
817 expect(posts).toEqual([]);
818
819 // Once GitHub answers and has no such comment, the retry posts once.
820 const retryPosts = stubGitHub();
821 expect((await act(kv, { action: "post", draftKey: KEY })).status).toBe(200);
822 expect(retryPosts).toHaveLength(1);
823 });
824
825 it("frees the draft at once when GitHub definitely rejected the post", async () => {
826 const { kv } = await lockedAdmin(422);
827 expect((await act(kv, { action: "post", draftKey: KEY })).status).toBe(502);
828 const posts = stubGitHub();
829 expect((await act(kv, { action: "post", draftKey: KEY })).status).toBe(200);
830 expect(posts).toHaveLength(1);
831 });
832
833 it("treats a double-clicked discard as one discard, concurrent or repeated", async () => {
834 const { kv, posts } = await lockedAdmin();
835
836 const both = await Promise.all([
837 act(kv, { action: "discard", draftKey: KEY }),
838 act(kv, { action: "discard", draftKey: KEY }),
839 ]);
840 expect(both.map((r) => r.status)).toEqual([200, 200]);
841 for (const res of both) await expect(res.json()).resolves.toEqual({ ok: true, action: "discarded" });
842 expect(JSON.parse(kv.values.get("draft-resolved:linkcheck:42")!)).toMatchObject({ state: "discarded" });
843
844 // A third click served from stale KV hits the post-discard hold.
845 forgetDecision(kv);
846 expect((await act(kv, { action: "discard", draftKey: KEY })).status).toBe(200);
847 expect(posts).toEqual([]);
848 });
849
850 it("refuses a discard while a post holds the draft, and a post after a discard", async () => {
851 const { kv, posts } = await lockedAdmin();
852 // Send the discard only once the post holds the draft (it has reached
853 // GitHub), so the outcome does not depend on which request the
854 // scheduler delivers to the lock first.
855 const postP = act(kv, { action: "post", draftKey: KEY });
856 await vi.waitFor(() => expect(posts).toHaveLength(1));
857 const discard = await act(kv, { action: "discard", draftKey: KEY });
858 const post = await postP;
859 expect([post.status, discard.status]).toEqual([200, 409]);
860 expect(posts).toHaveLength(1);
861
862 const other = await lockedAdmin();
863 expect((await act(other.kv, { action: "discard", draftKey: KEY })).status).toBe(200);
864 forgetDecision(other.kv);
865 expect((await act(other.kv, { action: "post", draftKey: KEY })).status).toBe(409);
866 expect(other.posts).toEqual([]);
867 });
868
869 it("fails closed when the lock cannot be reached", async () => {
870 const { kv, lock, posts } = await lockedAdmin();
871 lock.get = () => ({ act: async () => { throw new Error("DO unavailable"); } }) as never;
872 const res = await act(kv, { action: "post", draftKey: KEY });
873 expect(res.status).toBe(500);
874 expect(posts).toEqual([]);
875 expect(kv.values.get("draft-resolved:linkcheck:42")).toBeUndefined();
876 });
877 });
878
879 describe("admin draft queue", () => {
880 function fill(kv: FakeKv, count: number) {
881 for (let i = 1; i <= count; i++) {
882 kv.values.set(`draft:linkcheck:${i}`, JSON.stringify(draft({ id: String(i), targetNumber: i })));
883 }
884 }
885
886 it("follows the KV list cursor past the first page", async () => {
887 const kv = new FakeKv();
888 kv.pageSize = 100;
889 fill(kv, 250);
890
891 await expect(listDrafts(kv)).resolves.toHaveLength(250);
892 });
893
894 it("reads at most MAX_LISTED_DRAFTS drafts in one request", async () => {
895 const kv = new FakeKv();
896 fill(kv, MAX_LISTED_DRAFTS + 1_000);
897 const get = vi.spyOn(kv, "get");
898
899 await expect(listDrafts(kv)).resolves.toHaveLength(MAX_LISTED_DRAFTS);
900 expect(get).toHaveBeenCalledTimes(MAX_LISTED_DRAFTS);
901 });
902
903 it("keeps the drafts already read when a later list page fails", async () => {
904 const kv = new FakeKv();
905 kv.pageSize = 100;
906 kv.failListAtCursor = "200";
907 fill(kv, 250);
908 vi.spyOn(console, "error").mockImplementation(() => {});
909
910 await expect(listDrafts(kv)).resolves.toHaveLength(200);
911 });
912 });
913
914 describe("post retry durability and generation admission", () => {
915 const KEY = "draft:linkcheck:42";
916 async function prepared() {
917 const kv = new FakeKv();
918 await saveDraft(kv.draftStores, draft());
919 const lock = new FakeDraftClaimLock();
920 stubAdminEnv(kv, lock);
921 return { kv, lock };
922 }
923 it("posts nothing when an earlier receipt cannot be read", async () => {
924 const { kv } = await prepared();
925 const originalGet = kv.get.bind(kv);
926 kv.get = async (key) => { if (key.startsWith("draft-post-unknown:")) throw new Error("unavailable"); return originalGet(key); };
927 const posts = stubGitHub();
928 expect((await act(kv, { action: "post", draftKey: KEY })).status).toBe(503);
929 expect(posts).toEqual([]);
930 });
931 it("writes the attempt before dispatch and refuses an unavailable receipt write", async () => {
932 const { kv } = await prepared();
933 kv.failPutsMatching = /^draft-post-unknown:/;
934 const posts = stubGitHub();
935 expect((await act(kv, { action: "post", draftKey: KEY })).status).toBe(502);
936 expect(posts).toEqual([]);
937 });
938 it("finds an earlier post past page one even when KV lost the receipt", async () => {
939 const { kv, lock } = await prepared();
940 stubGitHub(504);
941 expect((await act(kv, { action: "post", draftKey: KEY })).status).toBe(502);
942 lock.now += 15 * 60 * 1000;
943 kv.values.delete("draft-resolved:linkcheck:42");
944 kv.values.delete("draft-post-unknown:linkcheck:42");
945 const posts: string[] = [], pages: string[] = [];
946 vi.stubGlobal("fetch", vi.fn(async (input: string | URL | Request, init?: RequestInit) => {
947 const url = inputUrl(input);
948 if (init?.method === "POST") { posts.push(url); return jsonResponse({ id: 2 }, 201); }
949 const page = new URL(url).searchParams.get("page"); pages.push(page!);
950 return jsonResponse(page === "1" ? Array.from({ length: 100 }, () => ({ body: "another body" })) : [{ id: 7, body: "English body" }]);
951 }));
952 expect((await act(kv, { action: "post", draftKey: KEY })).status).toBe(200);
953 expect(pages).toEqual(["1", "2"]);
954 expect(posts).toEqual([]);
955 });
956 it("a bounded incomplete reconciliation never licenses another post", async () => {
957 const { kv, lock } = await prepared();
958 stubGitHub(504);
959 await act(kv, { action: "post", draftKey: KEY });
960 lock.now += 15 * 60 * 1000;
961 kv.values.delete("draft-resolved:linkcheck:42");
962 const posts: string[] = [];
963 vi.stubGlobal("fetch", vi.fn(async (input: string | URL | Request, init?: RequestInit) => {
964 if (init?.method === "POST") posts.push(inputUrl(input));
965 return jsonResponse(Array.from({ length: 100 }, () => ({ body: "another body" })));
966 }));
967 expect((await act(kv, { action: "post", draftKey: KEY })).status).toBe(502);
968 expect(posts).toEqual([]);
969 });
970 it("refuses changed retry text while the earlier attempt is unresolved", async () => {
971 const { kv, lock } = await prepared();
972 stubGitHub(504);
973 await act(kv, { action: "post", draftKey: KEY });
974 lock.now += 15 * 60 * 1000;
975 kv.values.delete("draft-resolved:linkcheck:42");
976 const posts = stubGitHub();
977 expect((await act(kv, { action: "post", draftKey: KEY, editedBody: "different body" })).status).toBe(409);
978 expect(posts).toEqual([]);
979 });
980 it("missing or failed durable generation admission starts no provider call", async () => {
981 const kv = new FakeKv();
982 const reads = vi.fn(); vi.stubGlobal("fetch", reads);
983 expect(await runDigest({ CURATED_KV: kv, DEEPSEEK_API_KEY: "k" })).toMatchObject({ skipped: true });
984 const broken = { idFromName: () => ({ toString: () => "x" }), get: () => ({ act: async () => { throw new Error("down"); } }) };
985 expect(await runDigest({ CURATED_KV: kv, DRAFT_CLAIM_LOCK: broken, DEEPSEEK_API_KEY: "k" })).toMatchObject({ skipped: true });
986 expect(reads).not.toHaveBeenCalled(); expect(mocks.agentChat).not.toHaveBeenCalled();
987 });
988 it("admits one overlapping digest generation and spends once", async () => {
989 const kv = new FakeKv();
990 const env = { CURATED_KV: kv, DRAFT_CLAIM_LOCK: new FakeDraftClaimLock(), DEEPSEEK_API_KEY: "k" };
991 stubDigestSources();
992 const output = { content: JSON.stringify(DIGEST_MODEL_OUTPUT), usage: { input: 1, output: 1 } };
993 let finish!: (value: unknown) => void;
994 mocks.agentChat.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; })).mockResolvedValue(output);
995 const first = runDigest(env);
996 await vi.waitFor(() => expect(mocks.agentChat).toHaveBeenCalledOnce());
997 expect(await runDigest(env)).toMatchObject({ processed: 0, skipped: 1 });
998 finish(output);
999 await first;
1000 expect(mocks.agentChat).toHaveBeenCalledOnce();
1001 });
1002 });
1003
1003 lines TYPESCRIPT