Repository navigation
Expand file tree
/
Copy pathmain.js
More file actions
4490 lines (4068 loc) · 205 KB
/
Copy pathmain.js
File metadata and controls
4490 lines (4068 loc) · 205 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// {{Wikipedia:USync |repo=https://github.com/alex-o-748/citation-checker-script |ref=refs/heads/dev|path=main.js}}
//Inspired by User:Polygnotus/Scripts/AI_Source_Verification.js
//Inspired by User:Phlsph7/SourceVerificationAIAssistant.js
(function() {
'use strict';
// <core-injected>
// --- core/prompts.js ---
// Pure prompt-generation logic. Imported by core/ consumers (CLI, benchmark).
// Also injected byte-identically into main.js between <core-injected> markers.
function generateSystemPrompt() {
return `You are a fact-checking assistant for Wikipedia. Analyze whether claims are supported by the provided source text.
Rules:
- ONLY use the provided source text. Never use outside knowledge.
- First identify what the claim asserts, then look for information that supports or contradicts it.
- Accept paraphrasing and straightforward implications, but not speculative inferences or logical leaps.
- Distinguish between definitive statements and uncertain/hedged language. Claims stated as facts require sources that make definitive statements, not speculation or tentative assertions.
- Names from languages using non-Latin scripts (Arabic, Chinese, Japanese, Korean, Russian, Hindi, etc.) may have multiple valid romanizations/transliterations. For example, "Yasmin" and "Yazmeen," or "Chekhov" and "Tchekhov," are variant spellings of the same name. Do not treat transliteration differences as factual errors.
Source text evaluation:
Before analyzing, check if the provided "source text" is actually usable content.
It IS usable if it's:
- Article text from any website, including archive.org snapshots
- News articles, blog posts, press releases
- Actual content from the original source, even if it includes navigation, boilerplate, or Internet Archive/Wayback Machine framing
It is NOT usable if it's:
- A library catalog, database record, or book metadata (e.g., WorldCat, Google Books, JSTOR preview pages)
- Google Books, also Google Books in Internet Archive
- A paywall, login page, or access denied message
- A cookie consent notice or JavaScript error
- A 404 page or redirect notice
- Just bibliographic information without the actual content being cited
IMPORTANT: If the source text contains actual article content (paragraphs of text, quotes, factual statements), it IS usable even if it also contains archive navigation, headers, footers, or other page chrome. Only return SOURCE UNAVAILABLE when there is genuinely no article content to analyze.
If the source text is not usable, you MUST return verdict SOURCE UNAVAILABLE with confidence 0. Do not attempt to verify the claim - if you cannot find actual article or book content to quote, the source is unavailable.
Respond in JSON format:
{
"confidence": <number 0-100>,
"verdict": "<verdict>",
"reason_type": "<only for NOT SUPPORTED: 'contradiction' or 'omission'>",
"comments": "<relevant quote and brief explanation>"
}
For NOT SUPPORTED verdicts, include a "reason_type" field: use "contradiction" when the source explicitly states something incompatible with the claim, or "omission" when the source simply does not mention or address the claim. If both apply (source contradicts one part and omits another), use "contradiction". Do not include reason_type for other verdicts.
Confidence guide:
- 80-100: SUPPORTED
- 50-79: PARTIALLY SUPPORTED
- 1-49: NOT SUPPORTED
- 0: SOURCE UNAVAILABLE
<example>
Claim: "The committee published its findings in 1932."
Source text: "History of Modern Economics - Economic Research Council - Google Books Sign in Hidden fields Books Try the new Google Books Check out the new look and enjoy easier access to your favorite features Try it now No thanks My library Help Advanced Book Search Download EPUB Download PDF Plain text Read eBook Get this book in print AbeBooks On Demand Books Amazon Find in a library All sellers About this book Terms of Service Plain text PDF EPUB"
{"source_quote": "", "confidence": 0, "verdict": "SOURCE UNAVAILABLE", "comments": "Google Books interface with no actual book content, only navigation and metadata."}
</example>
<example>
Claim: "The bridge was completed in 1998."
Source text: "Skip to main content Web Archive toolbar... Capture date: 2015-03-12 ... City Tribune - Local News ... The Morrison Bridge project broke ground in 1994 after years of planning. Construction faced multiple delays due to funding shortages. The bridge was finally opened to traffic in August 2002, four years behind schedule. Mayor Davis called it 'a triumph of persistence.'"
{"confidence": 15, "verdict": "NOT SUPPORTED", "reason_type": "contradiction", "comments": "\"finally opened to traffic in August 2002, four years behind schedule\" - Source says the bridge opened in 2002, not 1998. The article is accessible despite being an Internet Archive capture."}
</example>
<example>
Claim: "The company was founded in 1985 by John Smith."
Source text: "Acme Corp was established in 1985. Its founder, John Smith, served as CEO until 2001."
{"confidence": 95, "verdict": "SUPPORTED", "comments": "\"Acme Corp was established in 1985. Its founder, John Smith\" - Definitive match with paraphrasing."}
</example>
<example>
Claim: "The treaty was signed by 45 countries."
Source text: "The treaty, finalized in March, was signed by over 30 nations, though the exact number remains disputed."
{"confidence": 20, "verdict": "NOT SUPPORTED", "reason_type": "contradiction", "comments": "\"signed by over 30 nations\" - Source says \"over 30,\" not 45."}
</example>
<example>
Claim: "The treaty was signed in Paris."
Source text: "It is believed the treaty was signed in Paris, though some historians dispute this."
{"confidence": 60, "verdict": "PARTIALLY SUPPORTED", "comments": "\"It is believed... though some historians dispute this\" - Source hedges this as uncertain; Wikipedia states it as fact."}
</example>
<example>
Claim: "The population increased by 12% between 2010 and 2020."
Source text: "Census data shows significant population growth in the region during the 2010s."
{"confidence": 55, "verdict": "PARTIALLY SUPPORTED", "comments": "\"significant population growth\" - Source confirms growth but doesn't specify 12%."}
</example>
<example>
Claim: "The president resigned on March 3."
Source text: "The president remained in office throughout March."
{"confidence": 5, "verdict": "NOT SUPPORTED", "reason_type": "contradiction", "comments": "\"remained in office throughout March\" - Source directly contradicts the claim."}
</example>
<example>
Claim: "She received the Nobel Prize in Chemistry in 2015."
Source text: "Professor Martin completed her PhD at Oxford in 1998 and joined the faculty at Cambridge in 2003. Her research focuses on organic synthesis and catalysis. She has published over 200 papers and received several university teaching awards."
{"confidence": 10, "verdict": "NOT SUPPORTED", "reason_type": "omission", "comments": "The source discusses her academic career and publications but makes no mention of a Nobel Prize."}
</example>`;
}
// Strips the "Source URL: ... Source Content:\n" / "Manual source text:\n"
// framing that fetchSourceContent and the manual-paste path wrap around the
// actual source body, returning just the body. Shared by the single-source
// user prompt and the multi-source group assembler so both see identical text.
function extractSourceText(sourceInfo) {
if (sourceInfo.startsWith('Manual source text:')) {
return sourceInfo.replace(/^Manual source text:\s*\n\s*/, '');
}
if (sourceInfo.includes('Source Content:')) {
const contentMatch = sourceInfo.match(/Source Content:\n([\s\S]*)/);
return contentMatch ? contentMatch[1] : sourceInfo;
}
return sourceInfo;
}
/**
* Parses source info and generates the user message
* @param {string} claim - The claim to verify
* @param {string} sourceInfo - The source information
* @returns {string} The user message content
*/
function generateUserPrompt(claim, sourceInfo) {
const sourceText = extractSourceText(sourceInfo);
console.log('[Verifier] Source text (first 2000 chars):', sourceText.substring(0, 2000));
return `Claim: "${claim}"
Source text:
${sourceText}`;
}
// System prompt for the "adjacent citations" / collective-verification path:
// one claim is cited by several adjacent sources, and we judge whether the
// sources TOGETHER support it. Kept deliberately close to generateSystemPrompt
// (same JSON schema, verdict vocabulary, confidence scale, reason_type rules)
// so verdicts stay comparable; the differences are the "collective" framing and
// the handling of partially-unavailable source sets. This is a NEW prompt — the
// single-source benchmark, which uses generateSystemPrompt, is unaffected.
function generateGroupSystemPrompt() {
return `You are a fact-checking assistant for Wikipedia. A single claim is cited by MULTIPLE sources, provided below and each labeled with its citation number(s). Analyze whether the claim is supported by the sources taken TOGETHER.
Rules:
- ONLY use the provided source texts. Never use outside knowledge.
- First identify what the claim asserts, then look across ALL the sources for information that supports or contradicts each part.
- The claim is SUPPORTED if the sources COLLECTIVELY support it. No single source needs to support the whole claim on its own — one source may support one part and a different source another part.
- Return PARTIALLY SUPPORTED if the sources together back only some of the claim, and NOT SUPPORTED if the sources together contradict it or address none of it.
- Accept paraphrasing and straightforward implications, but not speculative inferences or logical leaps.
- Distinguish between definitive statements and uncertain/hedged language. Claims stated as facts require sources that make definitive statements, not speculation or tentative assertions.
- Names from languages using non-Latin scripts (Arabic, Chinese, Japanese, Korean, Russian, Hindi, etc.) may have multiple valid romanizations/transliterations. For example, "Yasmin" and "Yazmeen," or "Chekhov" and "Tchekhov," are variant spellings of the same name. Do not treat transliteration differences as factual errors.
Source text evaluation:
Some of the provided sources may be unusable — a paywall, login page, library catalog/metadata page (e.g. WorldCat, Google Books, JSTOR preview), cookie/JavaScript notice, 404/redirect, or an explicit "[This source could not be retrieved: ...]" note. Ignore unusable sources and judge the claim against the sources that DO contain usable article/book content.
Only return verdict SOURCE UNAVAILABLE with confidence 0 if NONE of the provided sources contain usable content.
Respond in JSON format:
{
"confidence": <number 0-100>,
"verdict": "<verdict>",
"reason_type": "<only for NOT SUPPORTED: 'contradiction' or 'omission'>",
"comments": "<note which source(s) support or contradict which part of the claim>"
}
For NOT SUPPORTED verdicts, include a "reason_type" field: use "contradiction" when a source explicitly states something incompatible with the claim, or "omission" when the sources simply do not mention or address the claim. If both apply, use "contradiction". Do not include reason_type for other verdicts.
Confidence guide:
- 80-100: SUPPORTED
- 50-79: PARTIALLY SUPPORTED
- 1-49: NOT SUPPORTED
- 0: SOURCE UNAVAILABLE
<example>
Claim: "The company was founded in 1985 by John Smith, who led it until 2001."
Source [1] (https://example.com/a): "Acme Corp was established in 1985 in Ohio."
Source [2] (https://example.com/b): "John Smith founded Acme Corp and served as its chief executive until 2001."
{"confidence": 92, "verdict": "SUPPORTED", "comments": "Source [1] gives the 1985 founding year; source [2] confirms John Smith as founder and his tenure until 2001. Together they support the whole claim."}
</example>
<example>
Claim: "The treaty was signed in Paris in 1990."
Source [1] (https://example.com/a): [This source could not be retrieved: HTTP 403]
Source [2] (https://example.com/b): "The accord was signed in the French capital in the spring of 1990."
{"confidence": 88, "verdict": "SUPPORTED", "comments": "Source [1] was unavailable, but source [2] states the accord was signed in the French capital (Paris) in 1990, which supports the claim."}
</example>
<example>
Claim: "The bridge, built in 1998, cost $200 million."
Source [1] (https://example.com/a): "The bridge opened to traffic in 1998 after four years of construction."
Source [2] (https://example.com/b): "Funding for the project came from a mix of state and federal grants."
{"confidence": 55, "verdict": "PARTIALLY SUPPORTED", "comments": "Source [1] supports the 1998 date. Neither source states the $200 million cost, so that part is unverified."}
</example>`;
}
/**
* Builds the user message for the collective (multi-source) verification path.
* @param {string} claim - The claim cited by the group.
* @param {string} assembledText - Labeled source blocks from assembleGroupSources().
* @returns {string} The user message content.
*/
function generateGroupUserPrompt(claim, assembledText) {
return `Claim: "${claim}"
The following sources are all cited for this claim. Evaluate whether they support it together.
${assembledText}`;
}
/**
* Assembles the per-source fetch results of an adjacent-citation group into a
* single labeled blob for the collective prompt. Unavailable sources are kept
* (labeled) rather than dropped, so the model can reason about partial coverage.
*
* @param {Array<{citationNumbers: string[], url?: string, content?: string|null,
* error?: string|null, status?: number|null}>} entries - one per distinct
* source (callers should dedupe sources shared by named refs, merging their
* citation numbers into citationNumbers).
* @returns {{text: string, anyAvailable: boolean}} Combined text and whether at
* least one source contributed usable content.
*/
function assembleGroupSources(entries) {
const blocks = [];
let anyAvailable = false;
for (const e of entries) {
const nums = (e.citationNumbers || []).map(n => `[${n}]`).join('');
const label = `Source ${nums}${e.url ? ` (${e.url})` : ''}:`;
const text = e.content ? extractSourceText(e.content).trim() : '';
if (text) {
anyAvailable = true;
blocks.push(`${label}\n${text}`);
} else {
const reason = e.status != null ? `HTTP ${e.status}` : (e.error || 'could not be retrieved');
blocks.push(`${label}\n[This source could not be retrieved: ${reason}]`);
}
}
return { text: blocks.join('\n\n'), anyAvailable };
}
// --- core/verdicts.js ---
// Single source of truth for the four canonical verdict categories and
// the case/short-form conversions that the userscript, CLI, and benchmark
// pipeline each consume. Pre-consolidation, normalizeVerdict was
// reimplemented separately in run_benchmark.js, analyze_results.js,
// compare_results.js, and extract_dataset.js — each with a different
// return-value shape and a different fallback for unrecognized input.
// This module centralizes the recognition logic; callers compose it with
// the presenter that matches their downstream schema.
// Canonical UPPERCASE form. Matches the prompt's verdict spec and the
// userscript's existing inline comparisons.
const VERDICTS = Object.freeze({
SUPPORTED: 'SUPPORTED',
PARTIALLY_SUPPORTED: 'PARTIALLY SUPPORTED',
NOT_SUPPORTED: 'NOT SUPPORTED',
SOURCE_UNAVAILABLE: 'SOURCE UNAVAILABLE',
});
// Ordered by the confidence guide in core/prompts.js. Confusion-matrix
// rows/columns in analyze_results.js iterate this list.
const VERDICT_LIST = Object.freeze([
VERDICTS.SUPPORTED,
VERDICTS.PARTIALLY_SUPPORTED,
VERDICTS.NOT_SUPPORTED,
VERDICTS.SOURCE_UNAVAILABLE,
]);
// Map any reasonable variant ('not_supported', 'Not Supported', 'PARTIALLY',
// 'unavailable', 'partial', ...) to one of the four canonical UPPERCASE
// values. Returns null for unrecognized input — callers decide whether to
// substitute a sentinel, pass through, or treat as 'Unknown'.
function canonicalizeVerdict(raw) {
if (raw == null) return null;
const v = String(raw).toUpperCase().replace(/_/g, ' ').replace(/\s+/g, ' ').trim();
if (!v) return null;
// NOT-prefix matches both 'NOT' (compare_results short code) and
// 'NOT SUPPORTED'. Order doesn't matter for correctness here because
// the canonical forms start with distinct letters; the ordering below
// mirrors the historical order in run_benchmark.js for readability.
if (v.startsWith('NOT')) return VERDICTS.NOT_SUPPORTED;
if (v.startsWith('PARTIAL')) return VERDICTS.PARTIALLY_SUPPORTED;
if (v.startsWith('UNAVAIL')) return VERDICTS.SOURCE_UNAVAILABLE;
if (v.startsWith('SOURCE')) return VERDICTS.SOURCE_UNAVAILABLE;
if (v.startsWith('SUPPORT')) return VERDICTS.SUPPORTED;
return null;
}
// Presenter: canonical UPPERCASE -> title case ('Supported', 'Not supported', ...).
// Used by benchmark results.json schema and analyze_results.js's confusion matrix.
const TITLE_CASE = Object.freeze({
[VERDICTS.SUPPORTED]: 'Supported',
[VERDICTS.PARTIALLY_SUPPORTED]: 'Partially supported',
[VERDICTS.NOT_SUPPORTED]: 'Not supported',
[VERDICTS.SOURCE_UNAVAILABLE]: 'Source unavailable',
});
function toTitleCase(canonical) {
return TITLE_CASE[canonical] ?? canonical;
}
// Presenter: canonical UPPERCASE -> short lowercase code ('support', 'not', ...).
// Used by compare_results.js for run-vs-run comparison.
const SHORT_CODE = Object.freeze({
[VERDICTS.SUPPORTED]: 'support',
[VERDICTS.PARTIALLY_SUPPORTED]: 'partial',
[VERDICTS.NOT_SUPPORTED]: 'not',
[VERDICTS.SOURCE_UNAVAILABLE]: 'unavailable',
});
function toShortCode(canonical) {
return SHORT_CODE[canonical] ?? canonical;
}
// --- core/parsing.js ---
// Parses raw LLM response text into a structured verdict object.
//
// Happy path: JSON, optionally inside a ```json code fence or surrounded by
// prose. Falls back to a markdown-emphasis recovery regex for small
// open-weight models (e.g. Granite 4.1 8B) that occasionally emit
// "**Verdict:** SUPPORTED" prose instead of the requested JSON. On total
// failure, returns the 'PARSE_ERROR' sentinel — chosen to match what the
// benchmark already records for unrecoverable responses.
function parseVerificationResult(response) {
const trimmed = response.trim();
try {
let jsonStr = trimmed;
const codeBlockMatch = jsonStr.match(/```(?:json)?\s*([\s\S]*?)\s*```/);
if (codeBlockMatch) {
jsonStr = codeBlockMatch[1].trim();
} else {
const jsonMatch = jsonStr.match(/\{[\s\S]*\}/);
if (jsonMatch) jsonStr = jsonMatch[0];
}
const result = JSON.parse(jsonStr);
return {
verdict: result.verdict || 'UNKNOWN',
confidence: result.confidence ?? null,
comments: result.comments || '',
reason_type: result.reason_type || null
};
} catch (e) {
// fall through to the markdown-emphasis recovery
}
// Strip "**" and "__"-style emphasis so e.g. "**Verdict:** SUPPORTED"
// becomes "Verdict: SUPPORTED", then capture the canonical word(s).
const stripped = trimmed.replace(/\*+|__+/g, '');
const match = stripped.match(/verdict[\s:"']+([A-Z][A-Z _]*)/i);
if (match) {
const verdict = canonicalizeVerdict(match[1]);
if (verdict) {
return { verdict, confidence: null, comments: '<extracted from non-JSON response>' };
}
}
return {
verdict: 'PARSE_ERROR',
confidence: null,
comments: `Failed to parse AI response: ${response.substring(0, 200)}`
};
}
// --- core/retry.js ---
// Retry-with-backoff helper shared by the benchmark runner and the
// userscript's batch verify-all-citations path. Pre-consolidation, the
// benchmark used `withRetry` (5 attempts, exponential backoff, retries
// on 429 / 500 / 502 / 503 / 504 / network errors) while main.js's batch
// path had its own inline loop (3 attempts, fixed linear backoff,
// retries only on 429). The userscript's narrower trigger meant a single
// 503 during a batch run errored out the whole citation; the benchmark
// would have recovered. Sharing the impl widens the userscript to the
// benchmark's retry set.
//
// Defaults match the benchmark (1s base, exponential, ≤30s cap, 5
// attempts) — callers tune via options.
const RETRYABLE_STATUS = /^HTTP (429|500|502|503|504)\b/;
const RETRYABLE_NETWORK = /timeout|ECONNRESET|ETIMEDOUT|ENOTFOUND|EAI_AGAIN|socket hang up/i;
function defaultSleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function isRetryableError(error) {
const msg = error?.message ?? '';
return RETRYABLE_STATUS.test(msg) || RETRYABLE_NETWORK.test(msg);
}
/**
* Retry `fn` on transient failures (429, 5xx, network) with exponential
* backoff + jitter.
*
* Options:
* maxRetries Total attempt budget incl. the initial call (default 5).
* minBackoffMs Base for the exponential curve (default 1000).
* maxBackoffMs Cap on a single sleep (default 30000).
* jitterMs Upper bound of additive random jitter (default 500).
* sleepFn Injectable sleep — tests pass a no-op so they run instantly.
* shouldAbort Optional callback; truthy return short-circuits the loop
* (e.g. user cancellation in the userscript's batch path).
* onAttemptFailed Optional callback invoked after each failed attempt with
* { error, attempt, backoff, willRetry } — for progress UI.
* `backoff` is the sleep duration about to elapse (0 if no retry).
*
* Throws the last error if every attempt fails or the failure isn't retryable.
*/
async function withRetry(fn, {
maxRetries = 5,
minBackoffMs = 1000,
maxBackoffMs = 30000,
jitterMs = 500,
sleepFn = defaultSleep,
shouldAbort,
onAttemptFailed,
} = {}) {
let lastError = null;
for (let attempt = 0; attempt < maxRetries; attempt++) {
if (shouldAbort && shouldAbort()) break;
try {
return await fn();
} catch (error) {
lastError = error;
const retryable = isRetryableError(error);
const willRetry = retryable && attempt < maxRetries - 1
&& !(shouldAbort && shouldAbort());
const backoff = willRetry
? Math.min(maxBackoffMs, minBackoffMs * Math.pow(2, attempt))
+ Math.random() * jitterMs
: 0;
if (onAttemptFailed) onAttemptFailed({ error, attempt, backoff, willRetry });
if (!willRetry) break;
await sleepFn(backoff);
}
}
throw lastError;
}
// --- core/urls.js ---
// URL extraction helpers for Wikipedia reference elements.
// extractReferenceUrl and extractPageNumber accept a `document` parameter
// for Node callers (CLI, tests). They fall back to `globalThis.document`
// when called without one — that's the userscript path, where the browser
// supplies the global.
const ARCHIVE_HOST_PATTERN = /web\.archive\.org|archive\.today|archive\.is|archive\.ph|webcitation\.org/i;
function isArchiveUrl(href) {
return ARCHIVE_HOST_PATTERN.test(href);
}
function parseArchiveOrgUrl(url) {
const match = url.match(/^https?:\/\/web\.archive\.org\/web\/(\d+)(?:id_)?\/(https?:\/\/.+)$/);
if (!match) return null;
return { timestamp: match[1], originalUrl: match[2] };
}
function extractHttpUrl(element) {
if (!element) return null;
const links = element.querySelectorAll('a[href^="http"]');
if (links.length === 0) return null;
// Prefer Internet Archive URLs — we fetch via the Wayback raw endpoint
// (id_) which returns clean original content without toolbar framing.
for (const link of links) {
if (/web\.archive\.org/.test(link.href)) return link.href;
}
// Then any live URL; other archive services (archive.today etc.) last.
for (const link of links) {
if (!isArchiveUrl(link.href)) return link.href;
}
return links[0].href;
}
function extractReferenceUrl(refElement, doc = globalThis.document) {
let href = refElement.getAttribute('href');
if (!href) {
console.log('[CitationVerifier] No href on refElement');
return null;
}
// Handle Wikipedia REST API HTML which uses relative URLs with fragments
// like "./Page#cite_note-1". Extract just the fragment part.
const fragmentIndex = href.indexOf('#');
if (fragmentIndex === -1) {
console.log('[CitationVerifier] No fragment in href:', href);
return null;
}
const refId = href.substring(fragmentIndex + 1);
const refTarget = doc.getElementById(refId);
if (!refTarget) {
console.log('[CitationVerifier] No element found for refId:', refId);
return null;
}
// Try to extract a direct HTTP URL from the footnote
const directUrl = extractHttpUrl(refTarget);
if (directUrl) return directUrl;
// Harvard/sfn citation support: the footnote may contain only a
// short-cite linking to the full citation via a #CITEREF anchor.
// Follow that link to resolve the actual source URL.
const citerefLink = refTarget.querySelector('a[href^="#CITEREF"]');
if (citerefLink) {
const citerefId = citerefLink.getAttribute('href').substring(1);
const fullCitation = doc.getElementById(citerefId);
if (fullCitation) {
const resolvedUrl = extractHttpUrl(fullCitation);
if (resolvedUrl) {
console.log('[CitationVerifier] Resolved Harvard/sfn citation via', citerefId);
return resolvedUrl;
}
}
// Also try the parent <li> or <cite> element in case the anchor
// is on a child element within the full citation list item
const fullCitationLi = fullCitation && fullCitation.closest('li');
if (fullCitationLi && fullCitationLi !== fullCitation) {
const resolvedUrl = extractHttpUrl(fullCitationLi);
if (resolvedUrl) {
console.log('[CitationVerifier] Resolved Harvard/sfn citation via parent li of', citerefId);
return resolvedUrl;
}
}
console.log('[CitationVerifier] Harvard/sfn citation found but no URL in full citation:', citerefId);
return null;
}
console.log('[CitationVerifier] No http links in refTarget. innerHTML:', refTarget.innerHTML.substring(0, 500));
return null;
}
function extractPageNumber(refElement, doc = globalThis.document) {
const href = refElement.getAttribute('href');
if (!href) return null;
const fragmentIndex = href.indexOf('#');
if (fragmentIndex === -1) return null;
const refTarget = doc.getElementById(href.substring(fragmentIndex + 1));
if (!refTarget) return null;
const text = refTarget.textContent;
// Match patterns like "p. 42", "pp. 42-43", "p.42", "page 42", "pages 42–43"
const match = text.match(/\bp(?:p|ages?)?\.?\s*(\d+)/i);
if (match) {
console.log('[CitationVerifier] Extracted page number:', match[1]);
return parseInt(match[1], 10);
}
return null;
}
function isGoogleBooksUrl(url) {
return /books\.google\./.test(url);
}
// --- core/claim.js ---
// Extracts the prose claim text bearing a given citation from a parsed
// Wikipedia Document. Works with both browser DOM and JSDOM.
const MAINTENANCE_MARKER_RE = /\[(failed verification|verification needed|citation needed|better source[^\]]*|dubious[^\]]*|unreliable source[^\]]*|clarification needed|disputed[^\]]*|page needed|when\??|where\??|who\??|why\??|by whom\??|according to whom\??|original research[^\]]*|specify[^\]]*|vague|opinion|fact)\]/gi;
// True iff the DOM range strictly between two .reference wrapper elements (in
// document order: refA before refB) contains no non-whitespace text. This is
// the rule that defines whether two adjacent citations attach to the same
// claim — a comma or any other punctuation between them counts as text and
// breaks the group.
function hasTextBetween(refA, refB) {
const document = refA.ownerDocument;
const range = document.createRange();
range.setStartAfter(refA);
range.setEndBefore(refB);
const between = range.toString().replace(/\s+/g, '').trim();
return between.length > 0;
}
// Returns the contiguous run of .reference wrapper elements (in DOM order)
// that all attach to the same claim as refElement — i.e. consecutive siblings
// in the same container with no text between adjacent members. Always returns
// at least the wrapper of refElement; an isolated citation yields a single-
// element array.
function getCitationGroup(refElement) {
const currentRef = refElement.closest('.reference');
if (!currentRef) return [];
const container = currentRef.closest('p, li, td, div, section');
if (!container) return [currentRef];
const refsInContainer = Array.from(container.querySelectorAll('.reference'));
const idx = refsInContainer.indexOf(currentRef);
if (idx === -1) return [currentRef];
let start = idx;
while (start > 0 && !hasTextBetween(refsInContainer[start - 1], refsInContainer[start])) {
start--;
}
let end = idx;
while (end < refsInContainer.length - 1 && !hasTextBetween(refsInContainer[end], refsInContainer[end + 1])) {
end++;
}
return refsInContainer.slice(start, end + 1);
}
function extractClaimText(refElement) {
const document = refElement.ownerDocument;
const container = refElement.closest('p, li, td, div, section');
if (!container) {
return '';
}
// Get the current reference wrapper element
const currentRef = refElement.closest('.reference');
if (!currentRef) {
// Fallback: return container text
return container.textContent
.replace(/\[\d+\]/g, '')
.replace(/\s+/g, ' ')
.trim();
}
// Find all references in the same container
const refsInContainer = Array.from(container.querySelectorAll('.reference'));
const currentIndexInContainer = refsInContainer.indexOf(currentRef);
let claimStartNode = null;
if (currentIndexInContainer > 0) {
// Walk backwards through the consecutive same-claim run; the boundary
// is the first previous ref that has actual text between it and its
// successor (i.e. it cites a different claim).
for (let i = currentIndexInContainer - 1; i >= 0; i--) {
const prevRef = refsInContainer[i];
const nextRef = refsInContainer[i + 1] || currentRef;
if (hasTextBetween(prevRef, nextRef)) {
claimStartNode = prevRef;
break;
}
}
}
// Extract the text from the boundary to the current reference
const extractionRange = document.createRange();
if (claimStartNode) {
extractionRange.setStartAfter(claimStartNode);
} else {
// No previous ref boundary - start from beginning of container
extractionRange.setStart(container, 0);
}
extractionRange.setEndBefore(currentRef);
// Get the text content
let claimText = extractionRange.toString();
// Clean up the text. Whitespace must be normalized BEFORE the marker
// strip (Wikipedia's {{failed verification}} et al. use white-space:nowrap
// and emit U+00A0 between the words, which the literal-space alternatives
// in MAINTENANCE_MARKER_RE would otherwise fail to match) AND AFTER the
// strip (removing a marker that had a leading/trailing space leaves a
// double space behind).
claimText = claimText
.replace(/\[\d+\]/g, '') // Remove reference numbers like [1], [2]
.replace(/\s+/g, ' ') // Normalize whitespace (incl. NBSP) so the marker regex matches
.replace(MAINTENANCE_MARKER_RE, '') // Remove maintenance markers like [failed verification]
.replace(/\s+/g, ' ') // Collapse the gap left by the marker strip
.trim();
// If we got nothing meaningful, fall back to the container text
if (!claimText || claimText.length < 10) {
claimText = container.textContent
.replace(/\[\d+\]/g, '')
.replace(/\s+/g, ' ')
.replace(MAINTENANCE_MARKER_RE, '')
.replace(/\s+/g, ' ')
.trim();
}
return claimText;
}
// --- core/providers.js ---
// LLM provider dispatch. Pure HTTP routing — callers build the prompt.
// Shared call shape for OpenAI-compatible chat-completion upstreams.
// Used by PublicAI/HF (proxy-routed; key injected upstream), HF when the
// caller supplies their own bearer token (direct call to the HF router),
// OpenRouter (which adds attribution headers and surfaces per-call cost),
// and the benchmark runner (which calls direct PublicAI/OpenAI endpoints
// with bearer auth from environment variables).
// `responseFormat` is OpenAI-compatible structured-output: pass
// `{ type: 'json_object' }` to force JSON-only output, or a JSON-schema
// object on backends that support it. OpenRouter passes the param
// through to the underlying model; backends that don't recognise it
// generally ignore it rather than error. Small / weaker instruction-tuned
// models benefit most — Granite 4.1 8B in particular regressed from
// ~0.5% to 13% JSON-parse failures under terser prompts until this
// hint was supplied, after which parse failures returned to 0.
async function callOpenAICompatibleChat({ url, apiKey, model, systemPrompt, userContent, label, extraHeaders, extraBody, maxTokens = 2048, temperature = 0.1, responseFormat }) {
const requestBody = {
model: model,
messages: [
{ role: "system", content: systemPrompt },
{ role: "user", content: userContent }
],
max_tokens: maxTokens,
temperature: temperature
};
if (extraBody) Object.assign(requestBody, extraBody);
if (responseFormat) requestBody.response_format = responseFormat;
const headers = { 'Content-Type': 'application/json' };
if (apiKey) headers['Authorization'] = `Bearer ${apiKey}`;
if (extraHeaders) Object.assign(headers, extraHeaders);
const response = await fetch(url, {
method: 'POST',
headers,
body: JSON.stringify(requestBody)
});
if (!response.ok) {
const errorText = await response.text();
let errorMessage;
try {
const errorData = JSON.parse(errorText);
errorMessage = errorData.error?.message || errorText;
} catch {
errorMessage = errorText;
}
throw new Error(`${label} API request failed (${response.status}): ${errorMessage}`);
}
const data = await response.json();
if (!data.choices?.[0]?.message?.content) {
throw new Error('Invalid API response format');
}
return {
text: data.choices[0].message.content,
usage: {
input: data.usage?.prompt_tokens || 0,
output: data.usage?.completion_tokens || 0,
cost_usd: data.usage?.cost ?? null
}
};
}
async function callPublicAIAPI({ apiKey, model, systemPrompt, userContent, workerBase = 'https://publicai-proxy.alaexis.workers.dev', maxTokens, temperature }) {
return callOpenAICompatibleChat({
url: workerBase,
apiKey,
model, systemPrompt, userContent, maxTokens, temperature,
label: 'PublicAI',
});
}
// HF direct router endpoint, used when the caller supplies an apiKey.
// Without one, the call falls back to the worker proxy's /hf path, which
// injects an upstream key on the user's behalf.
const HF_DIRECT_URL = 'https://router.huggingface.co/v1/chat/completions';
async function callHuggingFaceAPI({ apiKey, model, systemPrompt, userContent, workerBase = 'https://publicai-proxy.alaexis.workers.dev', maxTokens, temperature }) {
const direct = Boolean(apiKey);
return callOpenAICompatibleChat({
url: direct ? HF_DIRECT_URL : `${workerBase}/hf`,
apiKey: direct ? apiKey : undefined,
model, systemPrompt, userContent, maxTokens, temperature,
label: 'HuggingFace',
});
}
// OpenRouter routes OpenAI-compatible requests across many open-weight backends.
// Per-call USD cost is surfaced on response.usage.cost (no opt-in flag required
// as of 2026; the older `usage: { include: true }` parameter is deprecated).
// Attribution headers (HTTP-Referer + X-Title) are recommended by OpenRouter
// for analytics; they don't affect routing.
async function callOpenRouterAPI({ apiKey, model, systemPrompt, userContent, maxTokens, temperature, extraBody, responseFormat }) {
return callOpenAICompatibleChat({
url: 'https://openrouter.ai/api/v1/chat/completions',
apiKey,
model, systemPrompt, userContent, maxTokens, temperature, extraBody, responseFormat,
label: 'OpenRouter',
extraHeaders: {
'HTTP-Referer': 'https://github.com/alex-o-748/citation-checker-script',
'X-Title': 'citation-checker-script',
},
});
}
async function callClaudeAPI({ apiKey, model, systemPrompt, userContent, maxTokens = 3000 }) {
const requestBody = {
model: model,
max_tokens: maxTokens,
system: systemPrompt,
messages: [{ role: "user", content: userContent }]
};
const response = await fetch('https://api.anthropic.com/v1/messages', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': apiKey,
'anthropic-version': '2023-06-01',
'anthropic-dangerous-direct-browser-access': 'true'
},
body: JSON.stringify(requestBody)
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`API request failed (${response.status}): ${errorText}`);
}
const data = await response.json();
return {
text: data.content[0].text,
usage: {
input: data.usage?.input_tokens || 0,
output: data.usage?.output_tokens || 0,
cost_usd: null
}
};
}
async function callGeminiAPI({ apiKey, model, systemPrompt, userContent, maxTokens = 2048, temperature = 0.1, useStructuredPrompt = true }) {
const API_URL = `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${apiKey}`;
// useStructuredPrompt:true (default) uses Gemini's proper systemInstruction
// + contents shape; the userscript and CLI have always used this.
// useStructuredPrompt:false concatenates `${systemPrompt}\n\n${userContent}`
// into a single user turn — the historical benchmark-runner shape, kept
// available so past benchmark numbers stay reproducible until a deliberate
// re-baselining run picks the canonical shape.
const requestBody = useStructuredPrompt
? {
contents: [{ parts: [{ text: userContent }] }],
systemInstruction: { parts: [{ text: systemPrompt }] },
}
: {
contents: [{ parts: [{ text: `${systemPrompt}\n\n${userContent}` }] }],
};
requestBody.generationConfig = {
maxOutputTokens: maxTokens,
temperature: temperature,
// responseMimeType: 'application/json' constrains Gemini to emit
// syntactically valid JSON only. Without it, Gemini occasionally
// wraps output in markdown fences or emits prose, both of which
// the verdict parser fails on. See issue #75.
responseMimeType: 'application/json'
};
const response = await fetch(API_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(requestBody)
});
const responseData = await response.json();
if (!response.ok) {
const errorDetail = responseData.error?.message || response.statusText;
throw new Error(`API request failed (${response.status}): ${errorDetail}`);
}
if (!responseData.candidates?.[0]?.content?.parts?.[0]?.text) {
throw new Error('Invalid API response format or no content generated.');
}
return {
text: responseData.candidates[0].content.parts[0].text,
usage: {
input: responseData.usageMetadata?.promptTokenCount || 0,
output: responseData.usageMetadata?.candidatesTokenCount || 0,
cost_usd: null
}
};
}
async function callOpenAIAPI({ apiKey, model, systemPrompt, userContent, maxTokens = 2000, temperature = 0.1 }) {
const requestBody = {
model: model,
max_tokens: maxTokens,
messages: [
{ role: "system", content: systemPrompt },
{ role: "user", content: userContent }
],
temperature: temperature
};
const response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
},
body: JSON.stringify(requestBody)
});
if (!response.ok) {
const errorText = await response.text();
let errorMessage;
try {
const errorData = JSON.parse(errorText);
errorMessage = errorData.error?.message || errorText;
} catch {
errorMessage = errorText;
}
throw new Error(`API request failed (${response.status}): ${errorMessage}`);
}
const data = await response.json();
if (!data.choices?.[0]?.message?.content) {
throw new Error('Invalid API response format');
}
return {
text: data.choices[0].message.content,
usage: {
input: data.usage?.prompt_tokens || 0,
output: data.usage?.completion_tokens || 0,
cost_usd: null
}
};
}
async function callProviderAPI(name, config) {
switch (name) {
case 'publicai': return await callPublicAIAPI(config);
case 'huggingface': return await callHuggingFaceAPI(config);
case 'openrouter': return await callOpenRouterAPI(config);
case 'claude': return await callClaudeAPI(config);
case 'gemini': return await callGeminiAPI(config);
case 'openai': return await callOpenAIAPI(config);
default: throw new Error(`Unknown provider: ${name}`);
}
}
// --- core/worker.js ---
// Calls to the Cloudflare Worker proxy: source fetching and verification logging.
async function fetchViaProxy(fetchUrl, pageNum, workerBase, sourceUrl) {
try {
let proxyUrl = `${workerBase}/?fetch=${encodeURIComponent(fetchUrl)}`;
if (pageNum) {
proxyUrl += `&page=${pageNum}`;
}
const response = await fetch(proxyUrl);
const proxyStatus = response.status;
let data = null;
try {
data = await response.json();
} catch (_) {
return { content: null, error: `Proxy returned non-JSON response (HTTP ${proxyStatus})`, status: proxyStatus };
}
const status = (data && typeof data.status === 'number') ? data.status : proxyStatus;
if (data.error) {
console.warn('[CitationVerifier] Proxy error:', data.error);
return { content: null, error: data.error, status };
}
if (data.content && data.content.length > 100) {
const isTruncated = data.truncated === true || data.content.length >= 12000;
let meta = `Source URL: ${sourceUrl}`;
if (data.pdf) {
meta += `\nPDF: ${data.totalPages} pages`;
if (data.page) {
meta += ` (extracted page ${data.page})`;
}
}
if (isTruncated) {
meta += `\nTruncated: true`;
}
return { content: `${meta}\n\nSource Content:\n${data.content}`, error: null, status };
}
if (data.pdf && !pageNum && data.totalPages > 15) {
console.log('[CitationVerifier] Large PDF without page param, content may be truncated');
}
return { content: null, error: 'Source content was empty or too short to verify', status };
} catch (error) {