返回 CodeWhale
content-watch.ts
根目录 / web / lib / content-watch.ts
1 /**
2 * content-watch.ts — two daily watchers that catch site drift the mechanical
3 * facts pipeline misses:
4 *
5 * runLinkCheck — pings every external URL referenced in the site copy,
6 * writes a draft per broken link (4xx/5xx). Stores a
7 * `linkcheck:last` summary so /admin can show last status.
8 *
9 * runSemanticDrift — reads recent CHANGELOG / commits, asks deepseek-flash
10 * whether any specific claims on the site look out of
11 * date, writes review-required drafts.
12 *
13 * Both surface as drafts in CURATED_KV under `draft:linkcheck:<...>` and
14 * `draft:semantic-drift:<...>`, picked up by the existing /admin listing.
15 */
16 import { fetchBoundedText } from "./bounded-body";
17 import { agentChat, draftStorageKey, getDraft, saveDraft, type AgentDraft, type DeepSeekEnv, type DraftClaimStores, VOICE_CONSTRAINTS } from "./community-agent";
18
19 // --- Canonical draft identities ---
20 //
21 // Watcher draft IDs are deterministic: a readable slug plus a ~64-bit
22 // SHA-256 suffix over the finding's full identity, capped at 80 characters.
23 // Re-running a watcher over an unchanged finding reproduces the same key (so
24 // the open-draft dedup check skips it); any change to the finding's identity
25 // produces a new key (so changed findings are drafted again instead of being
26 // silently swallowed by a truncated-prefix collision).
27 const WATCH_DRAFT_ID_MAX = 80;
28 const WATCH_DRAFT_HASH_HEX = 16; // 64 bits of SHA-256
29
30 async function sha256Hex(input: string): Promise<string> {
31 const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(input));
32 return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");
33 }
34
35 function slugify(input: string): string {
36 return input.replace(/[^a-z0-9]+/gi, "-").replace(/^-+|-+$/g, "").toLowerCase();
37 }
38
39 export async function watchDraftId(slugSource: string, identity: string): Promise<string> {
40 const hash = (await sha256Hex(identity)).slice(0, WATCH_DRAFT_HASH_HEX);
41 const slug = slugify(slugSource).slice(0, WATCH_DRAFT_ID_MAX - WATCH_DRAFT_HASH_HEX - 1);
42 return `${slug}-${hash}`;
43 }
44
45 interface WatchEnv extends DraftClaimStores {
46 DEEPSEEK_API_KEY?: string;
47 DEEPSEEK_BASE_URL?: string;
48 DEEPSEEK_MODEL?: string;
49 GITHUB_TOKEN?: string;
50 }
51
52 function dsEnv(env: WatchEnv): DeepSeekEnv {
53 return {
54 baseUrl: env.DEEPSEEK_BASE_URL ?? process.env.DEEPSEEK_BASE_URL,
55 model: env.DEEPSEEK_MODEL ?? process.env.DEEPSEEK_MODEL,
56 };
57 }
58
59 // --- Link checker ---
60
61 // Targets to probe daily. For registries that block bot HEAD/GET (npm, crates.io)
62 // we hit the public JSON API instead — same upstream, doesn't 403.
63 const LINK_TARGETS: { url: string; label: string }[] = [
64 { url: "https://github.com/codewhale-hq/CodeWhale", label: "Main repo" },
65 { url: "https://github.com/codewhale-hq/CodeWhale/issues", label: "Issues" },
66 { url: "https://github.com/codewhale-hq/CodeWhale/issues?q=is%3Aissue+is%3Aopen+label%3Acontribution", label: "Contributions" },
67 { url: "https://github.com/codewhale-hq/CodeWhale/discussions", label: "Discussions" },
68 { url: "https://github.com/codewhale-hq/CodeWhale/releases", label: "Releases" },
69 { url: "https://github.com/codewhale-hq/CodeWhale/blob/main/LICENSE", label: "License file" },
70 { url: "https://github.com/codewhale-hq/CodeWhale/blob/main/.github/CODE_OF_CONDUCT.md", label: "Code of Conduct" },
71 { url: "https://github.com/codewhale-hq/CodeWhale/blob/main/.github/SECURITY.md", label: "Security policy" },
72 { url: "https://github.com/codewhale-hq/CodeWhale/blob/main/CONTRIBUTING.md", label: "Contributing guide" },
73 { url: "https://github.com/codewhale-hq/CodeWhale/blob/main/.github/PULL_REQUEST_TEMPLATE.md", label: "PR template" },
74 { url: "https://github.com/Hmbown/homebrew-deepseek-tui", label: "Homebrew tap" },
75 { url: "https://github.com/sponsors/Hmbown", label: "Support link (GitHub Sponsors)" },
76 { url: "https://buymeacoffee.com/hmbown", label: "Support link (BMC)" },
77 { url: "https://registry.npmjs.org/codewhale", label: "npm package (registry API)" },
78 // crates.io intentionally not in this list — both their HTML and JSON API return 403 to
79 // Cloudflare Workers, so the check produces false positives. The crate links on the site
80 // still work for human users.
81 ];
82
83 export interface LinkCheckResult {
84 url: string;
85 label: string;
86 status: number | "error";
87 ok: boolean;
88 ms: number;
89 }
90
91 const PROBE_TIMEOUT_MS = 10_000;
92
93 async function probe(target: { url: string; label: string }): Promise<LinkCheckResult> {
94 const start = Date.now();
95 try {
96 // Use HEAD where possible; fall back to GET on 405/403 since some hosts
97 // (e.g. Cloudflare-protected) reject HEAD.
98 // Each request has its own deadline; only the status matters, so a GET
99 // body is discarded unread.
100 let r = await fetch(target.url, { method: "HEAD", redirect: "follow", signal: AbortSignal.timeout(PROBE_TIMEOUT_MS) });
101 if (r.status === 405 || r.status === 403 || r.status === 404) {
102 // Some sites return 404 to HEAD but 200 to GET (e.g. NPM)
103 r = await fetch(target.url, { method: "GET", redirect: "follow", signal: AbortSignal.timeout(PROBE_TIMEOUT_MS) });
104 await r.body?.cancel().catch(() => undefined);
105 }
106 return { url: target.url, label: target.label, status: r.status, ok: r.ok, ms: Date.now() - start };
107 } catch {
108 return { url: target.url, label: target.label, status: "error", ok: false, ms: Date.now() - start };
109 }
110 }
111
112 export async function runLinkCheck(env: WatchEnv): Promise<{ ok: boolean; checked: number; broken: number; results?: LinkCheckResult[] }> {
113 if (!env.CURATED_KV || !env.DRAFT_CLAIM_LOCK) return { ok: false, checked: 0, broken: 0 };
114
115 const results = await Promise.all(LINK_TARGETS.map(probe));
116 const broken = results.filter((r) => !r.ok);
117
118 await env.CURATED_KV.put("linkcheck:last", JSON.stringify({
119 at: new Date().toISOString(),
120 checked: results.length,
121 broken: broken.length,
122 results,
123 }), { expirationTtl: 60 * 60 * 24 * 14 });
124
125 // Write drafts ONLY for new breakages — dedup on the canonical draft key,
126 // derived from the full URL identity (the hash suffix keeps long URLs with
127 // identical slug prefixes distinct).
128 for (const b of broken) {
129 const id = await watchDraftId(b.url, `linkcheck\n${b.url}`);
130 const draft: AgentDraft = {
131 id,
132 type: "linkcheck",
133 targetUrl: b.url,
134 bodyEn: `**Broken link** (auto-detected by daily watch cron)\n\n- Label: **${b.label}**\n- URL: ${b.url}\n- HTTP status: ${b.status}\n- Latency: ${b.ms}ms\n\nThis URL is referenced in codewhale.net copy. Update the source page or fix the destination.\n\n— drafted by community assistant, pending maintainer review`,
135 bodyZh: `**链接失效**(每日巡检自动发现)\n\n- 名称:**${b.label}**\n- 地址:${b.url}\n- HTTP 状态:${b.status}\n- 延迟:${b.ms}ms\n\n该地址被 codewhale.net 文案引用,请更新源页面或修复目标。\n\n— 由社区助理草拟,待维护者审阅`,
136 generatedAt: new Date().toISOString(),
137 posted: false,
138 };
139 const existing = await getDraft(env.CURATED_KV, draftStorageKey(draft));
140 if (existing) continue; // already flagged; don't churn
141
142 await saveDraft(env, draft);
143 }
144
145 return { ok: true, checked: results.length, broken: broken.length, results: broken };
146 }
147
148 // --- Semantic drift ---
149
150 const SEMANTIC_DRIFT_PROMPT = `You are reviewing copy on a community website (codewhale.net) for the open-source Codewhale project.
151
152 Given:
153 1. The CHANGELOG entries below (most recent first)
154 2. The current homepage and docs page text below
155 3. Recent commit messages
156
157 Identify any factual claims on the site that are CONTRADICTED by recent changes. Be conservative — only flag claims you can directly tie to a CHANGELOG line or commit. Don't speculate.
158
159 Return ONLY this JSON shape (no prose, no markdown fences):
160 {
161 "drifts": [
162 {
163 "page": "homepage" | "docs" | "install" | "contribute" | "roadmap",
164 "claim": "exact text on the site that is now inaccurate",
165 "evidence": "the CHANGELOG line or commit hash that contradicts it",
166 "suggested_replacement": "what the site should say instead"
167 }
168 ]
169 }
170
171 If nothing is drifted, return { "drifts": [] }.
172
173 ${VOICE_CONSTRAINTS}`;
174
175 function startsWithAsciiCI(input: string, index: number, needle: string): boolean {
176 if (index + needle.length > input.length) return false;
177 return input.slice(index, index + needle.length).toLowerCase() === needle;
178 }
179
180 function isWhitespace(c: string | undefined): boolean {
181 return c === " " || c === "\n" || c === "\r" || c === "\t" || c === "\f";
182 }
183
184 function tagNameBoundary(input: string, index: number): boolean {
185 const c = input[index];
186 return c === undefined || c === ">" || c === "/" || isWhitespace(c);
187 }
188
189 function findClosingRawTextTag(input: string, from: number, tagName: "script" | "style"): number {
190 const closePrefix = `</${tagName}`;
191 for (let i = from; i < input.length; i += 1) {
192 if (startsWithAsciiCI(input, i, closePrefix) && tagNameBoundary(input, i + closePrefix.length)) {
193 const close = input.indexOf(">", i + closePrefix.length);
194 return close === -1 ? input.length : close + 1;
195 }
196 }
197 return input.length;
198 }
199
200 function collapseWhitespace(input: string): string {
201 let out = "";
202 let pendingSpace = false;
203 for (const c of input) {
204 if (isWhitespace(c)) {
205 pendingSpace = out.length > 0;
206 continue;
207 }
208 if (pendingSpace) out += " ";
209 out += c;
210 pendingSpace = false;
211 }
212 return out.trim();
213 }
214
215 function stripHtmlForPrompt(input: string): string {
216 let out = "";
217 for (let i = 0; i < input.length;) {
218 if (input[i] !== "<") {
219 out += input[i];
220 i += 1;
221 continue;
222 }
223
224 if (startsWithAsciiCI(input, i, "<script") && tagNameBoundary(input, i + "<script".length)) {
225 out += " ";
226 const openEnd = input.indexOf(">", i + 1);
227 i = openEnd === -1 ? input.length : findClosingRawTextTag(input, openEnd + 1, "script");
228 continue;
229 }
230 if (startsWithAsciiCI(input, i, "<style") && tagNameBoundary(input, i + "<style".length)) {
231 out += " ";
232 const openEnd = input.indexOf(">", i + 1);
233 i = openEnd === -1 ? input.length : findClosingRawTextTag(input, openEnd + 1, "style");
234 continue;
235 }
236
237 out += " ";
238 const tagEnd = input.indexOf(">", i + 1);
239 i = tagEnd === -1 ? input.length : tagEnd + 1;
240 }
241 return collapseWhitespace(out).slice(0, 8000);
242 }
243
244 // The model's drift list is untrusted input: bound it before any KV fanout so
245 // a runaway or hostile response cannot flood the draft queue, and drop entries
246 // whose shape does not match the prompt's contract.
247 const MAX_DRIFT_DRAFTS_PER_RUN = 10;
248 const DRIFT_FIELD_MAX = 2_000;
249 const DRIFT_PAGES = new Set(["homepage", "docs", "install", "contribute", "roadmap"]);
250
251 interface DriftFinding {
252 page: string;
253 claim: string;
254 evidence: string;
255 suggested_replacement: string;
256 }
257
258 function validateDriftFindings(raw: unknown): DriftFinding[] {
259 if (!Array.isArray(raw)) return [];
260 const findings: DriftFinding[] = [];
261 for (const entry of raw) {
262 if (findings.length >= MAX_DRIFT_DRAFTS_PER_RUN) break;
263 if (typeof entry !== "object" || entry === null) continue;
264 const { page, claim, evidence, suggested_replacement } = entry as Record<string, unknown>;
265 if (typeof page !== "string" || !DRIFT_PAGES.has(page)) continue;
266 if (typeof claim !== "string" || !claim.trim()) continue;
267 if (typeof evidence !== "string" || !evidence.trim()) continue;
268 if (typeof suggested_replacement !== "string" || !suggested_replacement.trim()) continue;
269 findings.push({
270 page,
271 claim: claim.slice(0, DRIFT_FIELD_MAX),
272 evidence: evidence.slice(0, DRIFT_FIELD_MAX),
273 suggested_replacement: suggested_replacement.slice(0, DRIFT_FIELD_MAX),
274 });
275 }
276 return findings;
277 }
278
279 export async function runSemanticDrift(env: WatchEnv): Promise<{ ok: boolean; drafted: number; reason?: string }> {
280 if (!env.CURATED_KV || !env.DRAFT_CLAIM_LOCK || !env.DEEPSEEK_API_KEY) {
281 return { ok: false, drafted: 0, reason: "missing CURATED_KV, DRAFT_CLAIM_LOCK or DEEPSEEK_API_KEY" };
282 }
283
284 const ghHeaders: Record<string, string> = {
285 Accept: "application/vnd.github+json",
286 "User-Agent": "codewhale-web-semantic-drift",
287 };
288 if (env.GITHUB_TOKEN) ghHeaders["Authorization"] = `Bearer ${env.GITHUB_TOKEN}`;
289
290 // Fetch CHANGELOG (truncated), recent commits, and live homepage HTML.
291 const [changelog, commits, homepageHtml, docsHtml] = await Promise.all([
292 fetchBoundedText("https://raw.githubusercontent.com/codewhale-hq/CodeWhale/main/CHANGELOG.md", { headers: ghHeaders }).then((r) => r.text).catch(() => ""),
293 fetchBoundedText("https://api.github.com/repos/codewhale-hq/CodeWhale/commits?per_page=30", { headers: ghHeaders }).then((r) => r.ok ? JSON.parse(r.text) as { commit: { message: string }; sha: string }[] : []).catch(() => []),
294 fetchBoundedText("https://codewhale.net/en", { headers: { "User-Agent": "codewhale-watch" } }).then((r) => r.text).catch(() => ""),
295 fetchBoundedText("https://codewhale.net/en/docs", { headers: { "User-Agent": "codewhale-watch" } }).then((r) => r.text).catch(() => ""),
296 ]);
297
298 if (!changelog && (!commits || commits.length === 0)) {
299 return { ok: false, drafted: 0, reason: "no changelog or commits available" };
300 }
301
302 const homepageText = stripHtmlForPrompt(homepageHtml);
303 const docsText = stripHtmlForPrompt(docsHtml);
304 const changelogHead = changelog.slice(0, 4000);
305 const commitMsgs = commits.slice(0, 30).map((c) => `- ${c.sha.slice(0, 7)}: ${c.commit.message.split("\n")[0]}`).join("\n");
306
307 const userMessage = `## Recent CHANGELOG entries
308 ${changelogHead || "(no CHANGELOG.md fetched)"}
309
310 ## Last 30 commits
311 ${commitMsgs || "(no commits fetched)"}
312
313 ## Homepage text (HTML stripped)
314 ${homepageText}
315
316 ## Docs page text (HTML stripped)
317 ${docsText}`;
318
319 let response: { content: string; usage: { input: number; output: number } };
320 try {
321 response = await agentChat(
322 [
323 { role: "system", content: SEMANTIC_DRIFT_PROMPT },
324 { role: "user", content: userMessage },
325 ],
326 env.DEEPSEEK_API_KEY,
327 true,
328 dsEnv(env),
329 );
330 } catch (e) {
331 return { ok: false, drafted: 0, reason: `LLM call failed: ${e}` };
332 }
333
334 // Extract JSON (jsonMode usually returns clean JSON, but defend against fences)
335 let parsed: { drifts?: unknown };
336 try {
337 const trimmed = response.content.replace(/^```(?:json)?\s*/i, "").replace(/\s*```\s*$/i, "").trim();
338 parsed = JSON.parse(trimmed);
339 } catch {
340 return { ok: false, drafted: 0, reason: "LLM returned non-JSON" };
341 }
342
343 const drifts = validateDriftFindings(parsed.drifts);
344 let drafted = 0;
345 for (const d of drifts) {
346 // Identity covers the full finding — page, claim, evidence, and
347 // replacement — so a re-run over an unchanged finding dedups, while a
348 // changed finding lands under a new key as a fresh draft.
349 const identity = [d.page, d.claim, d.evidence, d.suggested_replacement].join("\n");
350 const id = await watchDraftId(`${d.page}-${d.claim.slice(0, 40)}`, `semantic-drift\n${identity}`);
351 const body = `Page: **${d.page}**\n\nClaim that may be drifted:\n> ${d.claim}\n\nEvidence:\n> ${d.evidence}\n\nSuggested replacement:\n> ${d.suggested_replacement}\n\n— drafted by community assistant, pending maintainer review`;
352 const draft: AgentDraft = {
353 id,
354 type: "semantic-drift",
355 targetUrl: `https://codewhale.net/en/${d.page === "homepage" ? "" : d.page}`,
356 bodyEn: body,
357 bodyZh: body,
358 generatedAt: new Date().toISOString(),
359 posted: false,
360 };
361 const existing = await getDraft(env.CURATED_KV, draftStorageKey(draft));
362 if (existing) continue;
363
364 // saveDraft refuses findings the maintainer already discarded.
365 if (await saveDraft(env, draft)) drafted++;
366 }
367
368 return { ok: true, drafted };
369 }
370
370 lines TYPESCRIPT