-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmain.js
More file actions
6940 lines (6341 loc) · 340 KB
/
Copy pathmain.js
File metadata and controls
6940 lines (6341 loc) · 340 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/main|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'>",
"source_quote": "<the passage from the source text, copied word for word>",
"comments": "<brief explanation, without repeating the quote>"
}
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.
The "source_quote" field:
- Copy the passage EXACTLY as it appears in the source text, character for character. Do not paraphrase, summarize, correct spelling or punctuation, translate, or fill in ellipses. It is checked automatically against the source, and a quote that does not appear there verbatim is discarded.
- Quote the passage that decides the verdict: the one that supports the claim (SUPPORTED, PARTIALLY SUPPORTED) or the one that conflicts with it (NOT SUPPORTED with reason_type "contradiction").
- Keep it short — normally one sentence, at most two, and never more than about 50 words. Do not quote the whole paragraph.
- To join two non-adjacent passages, separate them with " ... ". Each part must still be copied verbatim, in the order they appear in the source.
- Use "" (empty string) when there is nothing to quote: SOURCE UNAVAILABLE, and NOT SUPPORTED with reason_type "omission" (the source says nothing about the claim, so no passage can be quoted).
- Never quote from the claim, and never write a passage the source does not contain. If you cannot find a passage worth quoting, use "".
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"
{"confidence": 0, "verdict": "SOURCE UNAVAILABLE", "source_quote": "", "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", "source_quote": "The bridge was finally opened to traffic in August 2002, four years behind schedule.", "comments": "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", "source_quote": "Acme Corp was established in 1985. Its founder, John Smith, served as CEO until 2001.", "comments": "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", "source_quote": "The treaty, finalized in March, was signed by over 30 nations, though the exact number remains disputed.", "comments": "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", "source_quote": "It is believed the treaty was signed in Paris, though some historians dispute this.", "comments": "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", "source_quote": "Census data shows significant population growth in the region during the 2010s.", "comments": "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", "source_quote": "The president remained in office throughout March.", "comments": "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", "source_quote": "", "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'>",
"source_quote": "<the passage from one of the sources, copied word for word>",
"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.
The "source_quote" field:
- Copy the passage EXACTLY as it appears in the source text, character for character. Do not paraphrase, summarize, correct spelling or punctuation, translate, or fill in ellipses. It is checked automatically against the sources, and a quote that does not appear in them verbatim is discarded.
- Quote the single most decisive passage across all the sources: the one that best supports the claim (SUPPORTED, PARTIALLY SUPPORTED) or the one that conflicts with it (NOT SUPPORTED with reason_type "contradiction"). Name the source it came from in "comments", not inside the quote itself — do not prefix the quote with "[2]" or a URL.
- Keep it short — normally one sentence, at most two, and never more than about 50 words.
- To join two non-adjacent passages, separate them with " ... ". Each part must still be copied verbatim.
- Use "" (empty string) when there is nothing to quote: SOURCE UNAVAILABLE, and NOT SUPPORTED with reason_type "omission".
- Never quote from the claim, and never write a passage the sources do not contain. If you cannot find a passage worth quoting, use "".
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", "source_quote": "John Smith founded Acme Corp and served as its chief executive until 2001.", "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", "source_quote": "The accord was signed in the French capital in the spring of 1990.", "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", "source_quote": "The bridge opened to traffic in 1998 after four years of construction.", "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;
}
// Supported-vs-rest equivalence: SUPPORTED and SOURCE_UNAVAILABLE must match
// exactly; PARTIALLY_SUPPORTED and NOT_SUPPORTED are forgiven as mutual
// near-misses, since both mean "an editor has to go look further." This is
// the grouping docs/llm-benchmarking-overview.md's "Lenient Accuracy" section
// describes, and the one WiCE's own claim-level binary task uses (see
// docs/wice-benchmark.md) — SUPPORTED vs. everything else.
//
// Defined here, exported, rather than inline in analyze_results.js (its only
// current caller): this exact grouping was hand-computed into that doc on
// 2026-01-23 and never implemented in the benchmark scripts, so for months
// the doc and the code disagreed under the same metric name ("Lenient
// Accuracy") without anyone noticing — see analyze_results.js's
// `lenientAccuracy` field, which forgives the *opposite* pair (SUPPORTED <->
// PARTIALLY). Keeping the definition here, rather than as a private helper in
// the script that happens to use it first, means a second caller (e.g.
// compare_results.js, if it ever wants this grouping) imports the same
// predicate instead of writing a fresh version that could quietly diverge
// from either the doc or this one.
function equalSupportedVsRest(a, b) {
const ca = canonicalizeVerdict(a);
const cb = canonicalizeVerdict(b);
if (ca === null || cb === null) return false;
if (ca === cb) return true;
const isProblem = v => v === VERDICTS.PARTIALLY_SUPPORTED || v === VERDICTS.NOT_SUPPORTED;
return isProblem(ca) && isProblem(cb);
}
// --- 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,
// Field-name aliases: models occasionally camelCase the key or
// shorten it to "quote". Always a string — an absent quote is ''
// (expected for omission/unavailable), never null, so callers can
// treat it uniformly. Whether the quote is real is decided by
// core/quote.js, not here.
source_quote: typeof (result.source_quote ?? result.sourceQuote ?? result.quote) === 'string'
? (result.source_quote ?? result.sourceQuote ?? result.quote).trim()
: ''
};
} 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>', source_quote: '' };
}
}
return {
verdict: 'PARSE_ERROR',
confidence: null,
comments: `Failed to parse AI response: ${response.substring(0, 200)}`,
source_quote: ''
};
}
// --- core/quote.js ---
// Verifies that a model-supplied `source_quote` actually occurs in the source
// text, so the UI can present it as evidence rather than as more model prose.
//
// The LLM is asked to copy a passage verbatim, but models paraphrase, "fix"
// punctuation, or occasionally invent a plausible-sounding sentence. Rather
// than trusting the field, we look it up. A quote we cannot locate is never
// shown as a confirmed quote — the design is deliberately conservative: it is
// better to fall back to the plain rationale than to display a passage the
// source may not contain.
//
// Matching is normalized (case, curly quotes, dashes, whitespace, ligature-ish
// unicode) because near-universal reformatting would otherwise sink almost
// every real quote. It is NOT fuzzy: no edit distance, no token overlap. A
// passage either occurs in the source under normalization or it doesn't.
//
// Non-contiguous quotes joined by an ellipsis ("A ... B") are supported: each
// segment must occur, in order.
// The complete set of values verifyQuote can put in `status`. Mirrors the
// VERDICTS / VERDICT_LIST pattern in core/verdicts.js.
//
// These strings leave the client: they are written to the `quote_status`
// column via POST /log, and the Cloudflare Worker
// (alex-o-748/public-ai-proxy, src/index.js) validates the incoming value
// against its own hardcoded copy of this list, storing NULL for anything it
// does not recognize. Cross-repo, that copy cannot be imported — so adding a
// status here is a two-repo change, and skipping the second half loses the new
// status silently. tests/quote.test.js pins the list to make that deliberate.
const QUOTE_STATUSES = Object.freeze({
EXACT: 'exact',
NORMALIZED: 'normalized',
PARTIAL: 'partial',
NOT_FOUND: 'not-found',
TOO_SHORT: 'too-short',
EMPTY: 'empty',
NO_SOURCE: 'no-source',
});
const QUOTE_STATUS_LIST = Object.freeze(Object.values(QUOTE_STATUSES));
// The two statuses that mean "found in the source". `verified` is exactly
// membership of this set.
const VERIFIED_STATUSES = Object.freeze([
QUOTE_STATUSES.EXACT,
QUOTE_STATUSES.NORMALIZED,
]);
// A quote shorter than this (after normalization) is not evidence — "1985" or
// "the bridge" would match almost any source by accident.
const MIN_QUOTE_CHARS = 12;
// Ellipsis forms models use to join non-contiguous fragments.
const ELLIPSIS_SPLIT = /\s*(?:\[\s*(?:\.\.\.|…)\s*\]|\.\.\.\.?|…)\s*/g;
// Punctuation entities that survive upstream extraction. The Worker's
// extractText() decodes only & < >, so a WordPress source
// reaches the model as "the mall’s amusement park" — and the model,
// reading that as an apostrophe, quotes it back decoded. Comparing the raw
// entity against the character it denotes is a false mismatch: they are the
// same character, differently encoded, exactly like the NFKC and curly-quote
// folds below. Numeric forms cover everything else a page is likely to emit.
const NAMED_ENTITIES = {
quot: '"', apos: "'", amp: '&', lt: '<', gt: '>', nbsp: ' ',
lsquo: '‘', rsquo: '’', sbquo: '‚', ldquo: '“', rdquo: '”', bdquo: '„',
ndash: '–', mdash: '—', minus: '−', shy: '', hellip: '…',
prime: '′', Prime: '″', laquo: '«', raquo: '»',
ensp: ' ', emsp: ' ', thinsp: ' ', middot: '·', bull: '•', deg: '°',
};
// The Latin-1 letter entities, which older CMSes emit for any accented name —
// é for José, ü for Müller. U+00C0..U+00FF is exactly this
// sequence, so the table is generated from it rather than typed out, which is
// both shorter and impossible to get subtly wrong.
(
'Agrave Aacute Acirc Atilde Auml Aring AElig Ccedil Egrave Eacute Ecirc Euml '
+ 'Igrave Iacute Icirc Iuml ETH Ntilde Ograve Oacute Ocirc Otilde Ouml times '
+ 'Oslash Ugrave Uacute Ucirc Uuml Yacute THORN szlig agrave aacute acirc '
+ 'atilde auml aring aelig ccedil egrave eacute ecirc euml igrave iacute '
+ 'icirc iuml eth ntilde ograve oacute ocirc otilde ouml divide oslash '
+ 'ugrave uacute ucirc uuml yacute thorn yuml'
).split(' ').forEach((name, i) => {
NAMED_ENTITIES[name] = String.fromCharCode(0xc0 + i);
});
function decodeEntities(text) {
return text.replace(/&(#[0-9]+|#[xX][0-9a-fA-F]+|[a-zA-Z][a-zA-Z0-9]{1,10});/g, (whole, body) => {
if (body[0] === '#') {
const code = body[1] === 'x' || body[1] === 'X'
? parseInt(body.slice(2), 16)
: parseInt(body.slice(1), 10);
// Surrogates and out-of-range values would throw; leave them be.
if (!Number.isFinite(code) || code < 0 || code > 0x10ffff) return whole;
if (code >= 0xd800 && code <= 0xdfff) return whole;
try {
return String.fromCodePoint(code);
} catch (e) {
return whole;
}
}
return Object.prototype.hasOwnProperty.call(NAMED_ENTITIES, body)
? NAMED_ENTITIES[body]
: whole;
});
}
const CHAR_FOLD = [
// All quotation marks fold to one character: models routinely swap ' for "
// when copying, and the distinction carries no evidentiary weight here.
[/[‘’‚‛′´`'ʻʼ“”„‟″«»"]/g, '"'],
[/[‐-―−]/g, '-'], // hyphens, dashes, minus
[//g, ''], // soft hyphen
[/[ - ]/g, ' '], // exotic spaces
[/[-]/g, ''], // zero-width junk
];
/**
* Canonical form used for substring comparison. Lossy by design — it throws
* away exactly the differences (case, quote style, dash style, whitespace
* runs, line breaks) that a model routinely introduces when copying.
* @param {string} text
* @returns {string}
*/
function normalizeForMatch(text) {
if (text == null) return '';
let out = String(text);
try {
out = out.normalize('NFKC');
} catch (e) {
// Environments without full Unicode data: normalization is an
// optimization here, not a requirement.
}
// Before the character folds, so ’ becomes ’ and then folds with
// every other apostrophe. Applied to both sides, so it can only make a
// genuine quote match.
out = decodeEntities(out);
for (const [pattern, replacement] of CHAR_FOLD) {
out = out.replace(pattern, replacement);
}
// Close up a hyphen followed by whitespace. PDF and OCR text layers break
// words across lines and leave the hyphen behind ("school-\nlike"), and a
// model copying that passage repairs some of them and not others — within
// a single quote. Folding both sides to "school-like" makes the two agree
// however the model chose to render it. Applied symmetrically, so the only
// thing it can do is make a real quote match; a spaced dash used as
// punctuation ("1994 - 1998") folds the same way on both sides.
out = out.replace(/-\s+/g, '-');
return out.replace(/\s+/g, ' ').trim().toLowerCase();
}
// Models often wrap the quote in quotation marks even when told not to, and
// sometimes trail a citation marker or a stray period. Strip the wrapper only
// when it is balanced, so a quote that legitimately opens with a quoted phrase
// survives intact.
function unwrap(quote) {
let q = String(quote).trim();
const pairs = [['"', '"'], ["'", "'"], ['“', '”'], ['‘', '’'], ['«', '»']];
let changed = true;
while (changed) {
changed = false;
for (const [open, close] of pairs) {
if (q.length > 2 && q.startsWith(open) && q.endsWith(close)) {
q = q.slice(open.length, q.length - close.length).trim();
changed = true;
}
}
}
return q;
}
/**
* Checks whether `quote` occurs in `sourceText`.
*
* @param {string} sourceText - The source body the model was shown (already
* unwrapped from its "Source Content:" framing by extractSourceText).
* @param {string} quote - The model's `source_quote` field.
* @returns {{verified: boolean, status: string, verifiedText: string,
* segments: Array<{text: string, found: boolean, located: boolean}>}}
* `verifiedText` is the part of the quote actually located in the source,
* ellipsis-joined — the whole quote when verified, the surviving fragments
* when partial, '' when nothing was found. Every character of it came from
* the source, so it is safe to display; `quote` as returned by the model is
* not. `found` counts toward the verdict, `located` records whether the
* fragment was really seen (they differ only for fragments too short to
* judge, which are forgiven but never shown).
* status is one of QUOTE_STATUS_LIST:
* 'empty' - no quote was offered (expected for omission / unavailable)
* 'no-source' - we have no source text to check against (e.g. cached
* result restored without its source); quote is unproven
* 'too-short' - quote too short to be meaningful evidence
* 'exact' - occurs verbatim, byte for byte
* 'normalized' - occurs after whitespace/punctuation/case normalization
* 'partial' - some ellipsis-joined segments found, others not
* 'not-found' - does not occur in the source
* `verified` is true exactly for the VERIFIED_STATUSES ('exact', 'normalized').
*/
function verifyQuote(sourceText, quote) {
const raw = quote == null ? '' : String(quote).trim();
if (!raw) return { verified: false, status: QUOTE_STATUSES.EMPTY, verifiedText: '', segments: [] };
const cleaned = unwrap(raw);
const source = sourceText == null ? '' : String(sourceText);
if (!source.trim()) return { verified: false, status: QUOTE_STATUSES.NO_SOURCE, verifiedText: '', segments: [] };
if (normalizeForMatch(cleaned).length < MIN_QUOTE_CHARS) {
return { verified: false, status: QUOTE_STATUSES.TOO_SHORT, verifiedText: '', segments: [] };
}
if (source.includes(cleaned)) {
return {
verified: true,
status: QUOTE_STATUSES.EXACT,
verifiedText: cleaned,
segments: [{ text: cleaned, found: true, located: true }],
};
}
const haystack = normalizeForMatch(source);
// String.split with a /g regex is safe (split resets lastIndex), but the
// regex is recreated per call anyway to avoid any shared-state surprise.
const rawSegments = cleaned.split(new RegExp(ELLIPSIS_SPLIT.source, 'g'))
.map(s => s.trim())
.filter(Boolean);
let cursor = 0;
const segments = [];
for (const segment of rawSegments) {
const needle = normalizeForMatch(segment);
const at = needle ? haystack.indexOf(needle, cursor) : -1;
// Fragments too short to carry meaning (a dangling "in 1985" after an
// ellipsis) neither confirm nor refute the match, so they are forgiven
// rather than failed — but they never advance the cursor, and they are
// only shown if they really were located.
if (needle.length < MIN_QUOTE_CHARS && rawSegments.length > 1) {
segments.push({ text: segment, found: true, located: at !== -1 });
continue;
}
if (at !== -1) {
segments.push({ text: segment, found: true, located: true });
cursor = at + needle.length;
continue;
}
// Models routinely close a quotation with a full stop the source does
// not have. Retry without it — and if that is what matched, display
// the trimmed form, so every character shown is still one the source
// contains.
const trimmed = segment.replace(/[.,;:]+$/, '');
const trimmedNeedle = normalizeForMatch(trimmed);
const trimmedAt = trimmedNeedle && trimmedNeedle !== needle
? haystack.indexOf(trimmedNeedle, cursor)
: -1;
if (trimmedAt !== -1) {
segments.push({ text: trimmed, found: true, located: true });
cursor = trimmedAt + trimmedNeedle.length;
} else {
segments.push({ text: segment, found: false, located: false });
}
}
const verifiedText = segments.filter(s => s.located).map(s => s.text).join(' … ');
const foundCount = segments.filter(s => s.found).length;
if (foundCount === segments.length && segments.length > 0) {
return { verified: true, status: QUOTE_STATUSES.NORMALIZED, verifiedText, segments };
}
if (foundCount > 0) {
return { verified: false, status: QUOTE_STATUSES.PARTIAL, verifiedText, segments };
}
return { verified: false, status: QUOTE_STATUSES.NOT_FOUND, verifiedText: '', segments };
}
// Verdicts for which a supporting/contradicting passage should exist in the
// source. Omission and unavailable verdicts have nothing to quote by
// definition, so a missing quote there is correct, not a failure.
const QUOTE_EXPECTED = new Set(['SUPPORTED', 'PARTIALLY SUPPORTED']);
/**
* Whether a quote is expected for this verdict — used to decide if a missing
* quote is worth surfacing to the user or is simply not applicable.
* @param {string} verdict - Canonical UPPERCASE verdict.
* @param {string|null} reasonType - 'contradiction' | 'omission' | null.
* @returns {boolean}
*/
function quoteExpectedFor(verdict, reasonType) {
if (QUOTE_EXPECTED.has(verdict)) return true;
return verdict === 'NOT SUPPORTED' && reasonType === 'contradiction';
}
// --- 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.
// Matches both the "HTTP <status>" shape (e.g. main.js's CORS-proxy fetch
// errors) and the "[<Label> ]API request failed (<status>): ..." shape thrown
// by every provider call in core/providers.js. The two families used to
// diverge silently: this regex only ever matched the former, so 429/5xx from
// a real LLM call (the actual withRetry-wrapped call path) never retried at
// all — see the 2026-08-16 keyless-HF-benchmark investigation.
//
// Both alternatives are anchored, and the optional label is `[^:()]*` rather
// than `.*` on purpose. The status must come from the message *we* format, not
// from the upstream response body interpolated after "): " — a permanent 400
// whose body happens to mention a 5xx ("...failed (400): upstream failed
// (503)") must stay non-retryable. `[^:()]*` cannot cross the first "(" or
// ":", so only the real status can satisfy the group. Labels are caller-side
// constants and may contain spaces ('Lift Wing'), hence not `\S+`.
const RETRYABLE_STATUS = /^(?:HTTP |[^:()]*API request failed \()(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);
}
// Wikimedia-family internal wikilinks (a[href^="http"] resolves to an absolute
// URL, so blue wikilinks like the "ISBN (identifier)" article, and the
// Special:BookSources bookseller-list page that ISBN magic links point to, can
// slip through the http filter). These are never genuine citation sources —
// verifying a claim against a wikilink is meaningless — so exclude them.
const WIKIMEDIA_INTERNAL_PATTERN = /^https?:\/\/[a-z0-9-]+\.(?:wikipedia|wikimedia|wiktionary|wikidata|wikisource|wikiquote|wikibooks|wikinews|wikiversity|wikivoyage)\.org\/wiki\//i;
function isInternalWikiLink(href) {
if (!href) return false;
// Special:BookSources is the page ISBN magic links target; match it
// directly so localized/mirrored hosts are covered too.
if (/Special:BookSources/i.test(href)) return true;
return WIKIMEDIA_INTERNAL_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;
// Skip internal wikilinks (ISBN article, Special:BookSources, etc.) — a
// book-only citation whose sole links are these would otherwise be
// "verified" against a Wikipedia navigation page rather than a real source.
const links = Array.from(element.querySelectorAll('a[href^="http"]'))
.filter(link => !isInternalWikiLink(link.href));
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