-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmatch.js
More file actions
1392 lines (1298 loc) · 59.8 KB
/
Copy pathmatch.js
File metadata and controls
1392 lines (1298 loc) · 59.8 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
// match.js (revised)
// ---------------------------------------------------------------------------
// Match — standalone name-comparison primitives + person<->mention scoring.
//
// CHANGES IN THIS REVISION (see design notes):
// 1. Household (Lever C) is now a NOISY-OR *boost* on the residual gap to
// certainty, not an averaged lever. It can only raise a score, never drag
// it, so an absent or weak roster is no longer a penalty.
// S0 = weighted(name, birth) // base identity evidence
// H = 1 - prod(1 - h_k) // noisy-OR over matched relatives
// S = S0 + beta * H * (1 - S0) // residual-gap boost (beta default 0.6)
// 2. Birth profile default sigma loosened 2.0 -> 3.0 and knockout 10 -> 12,
// to fit the age-report noise of 1850/1860 self/enumerator-reported ages.
// 3. Race knockout uses _raceClass(), which collapses Black<->Mulatto into one
// class so routine B<->M reclassification across enumerations does not veto.
// 4. Calibration features are now [name, birth, H] (H is the family feature).
//
// PRECISION REVISION (validated on a 500-pair human-reviewed sample; strict
// auto-accept precision was 52.6%). Four changes:
// A. Surname-distance guard (_surnameMatch): a phonetic / NYSIIS / bridged
// surname tier only stands if the raw surnames are also close under
// Jaro-Winkler (>= surnameFuzzyFloor, default 0.85). Stops double-metaphone
// collisions (Price/Boyers, Carrier/Crow) from counting as a full surname
// while sparing genuine spelling variants (Snyder/Snider, Kline/Cline).
// B. Nickname demotion (matchNameDetail): base 1.00 (EXACT_FIRST_SURNAME) is
// reserved for LITERALLY identical given names. Nickname-table equivalence
// (Fannie/Frances) and fuzzy matches drop to NICKNAME_FIRST_SURNAME (0.85)
// and are marked needsCorroboration.
// C. Corroboration gate (MatchPerson combiner): needsCorroboration is no longer
// diagnostic-only. A needsCorroboration rung with NO corroborating evidence
// (no household, no birthplace-agree, no occupation-agree) takes a subtractive
// corroborationPenalty (default 0.15). Second downward soft signal, alongside
// birthplace disagreement. Set corroborationPenalty=0 to restore old behavior.
// D. Calibration features are now [name, birth, H, surnameReliability]; the new
// scalar lets probability see how trustworthy the surname match is. Margin is
// a caller-level signal and stays out of this per-pair vector.
//
// Unchanged: name cascade (MatchName), Jaro-Winkler, rarity, nickname table,
// logistic calibration machinery.
//
// No external dependencies. Tunables via the constructor / per-call ctx.
// ---------------------------------------------------------------------------
class Match {
static DEFAULT_RARITY = {
veryRareMax: 5,
uncommonMax: 20,
averageMax: 100,
commonMax: 500,
modVeryRare: 15,
modUncommon: 5,
modAverage: 0,
modCommon: -5,
modExtremelyCommon: -15,
};
// Given-name fuzzy pass. Lowered from 0.85 to 0.84 so that truncations
// sitting just under the old bar are caught - ARCHIBALD/ARCHY is 0.8489,
// WASHINGTON/WASHT 0.8457 - without carrying a curated nickname table for
// them. This is a deliberate recall-for-precision trade: measured against
// the AUG corpus it admits roughly 660 additional cross-name equivalences,
// of which only a small fraction are true (ARCHIBALD/ARCHY, SOPHRONIA/SOPHY,
// CASSANDRA/CASSY) and the rest are not (HENRY/HENRIETTA, EDWARD/STEWARD,
// CHARLES/HARLEY, ELIJAH/DELILAH, LUCINDA/LUCIUS, WILLIS/WILLARD).
//
// Two things contain the damage, and both matter:
// - a fuzzy given-name hit yields rung NICKNAME_FIRST_SURNAME at base 0.85
// with needsCorroboration set, not an exact-name score; and
// - it still requires the SURNAME to have fired, so these are not loose
// matches on the given name alone.
// Raise back to 0.85 via config { jwFuzzyPassThreshold: 0.85 } if false merges show
// up in review.
static DEFAULT_JW_FUZZY_PASS = 0.84;
// Surname-distance guard: floor on raw-surname Jaro-Winkler below which a
// phonetic / NYSIIS / bridged code match is rejected (falls through to
// NO_MATCH). Exact full-/last-name tiers are exempt (they are identical).
static DEFAULT_SURNAME_FUZZY_FLOOR = 0.85;
// surnameReliability: how much to trust the surname match, fed to calibration
// (feature D). Higher = more trustworthy. Keyed by surnameKind.
static SURNAME_RELIABILITY = {
EXACT_FULLNAME: 1.0,
EXACT_LASTNAME: 1.0,
BRIDGED: 0.85,
FUZZY_STRONG: 0.75,
NYSIIS: 0.70,
PHONETIC_STRONG: 0.70,
PHONETIC_MODERATE: 0.50,
FUZZY_MODERATE: 0.45,
PHONETIC_WEAK: 0.35,
NO_MATCH: 0.0,
};
static DEFAULT_NICKNAMES = {
// William
"WM": "WILLIAM", "BILL": "WILLIAM", "BILLY": "WILLIAM",
"WILL": "WILLIAM", "WILLY": "WILLIAM", "WILLIE": "WILLIAM",
// Robert
"ROBT": "ROBERT", "ROB": "ROBERT", "BOB": "ROBERT",
"BOBBY": "ROBERT", "ROBBIE": "ROBERT",
// James
"JAS": "JAMES", "JIM": "JAMES", "JIMMY": "JAMES", "JAMIE": "JAMES",
// Charles
"CHAS": "CHARLES", "CHARLIE": "CHARLES", "CHUCK": "CHARLES", "CARL": "CHARLES",
// Thomas
"THOS": "THOMAS", "TOM": "THOMAS", "TOMMY": "THOMAS",
// John
"JNO": "JOHN", "JON": "JOHN", "JACK": "JOHN", "JACKIE": "JOHN",
"JONNY": "JOHN", "JOHNNY": "JOHN",
// Daniel
"DAN": "DANIEL", "DANNY": "DANIEL",
// Edward
"ED": "EDWARD", "EDDIE": "EDWARD", "NED": "EDWARD", "TED": "EDWARD", "TEDDY": "EDWARD",
// George
"GEO": "GEORGE",
// Joseph
"JOS": "JOSEPH", "JOE": "JOSEPH", "JOEY": "JOSEPH",
// Samuel
"SAM": "SAMUEL", "SAMMY": "SAMUEL",
// Alexander
"ALEX": "ALEXANDER", "ALECK": "ALEXANDER", "ALEC": "ALEXANDER",
"SANDY": "ALEXANDER",
// Patrick
"PAT": "PATRICK", "PADDY": "PATRICK",
// Matthew
"MATT": "MATTHEW", "MAT": "MATTHEW",
// Michael
"MIKE": "MICHAEL", "MICK": "MICHAEL", "MICKEY": "MICHAEL",
"MICH": "MICHAEL",
// David
"DAVE": "DAVID", "DAVEY": "DAVID", "DAVY": "DAVID",
// Christopher
"CHRIS": "CHRISTOPHER", "KIT": "CHRISTOPHER",
// Richard
"RICH": "RICHARD", "RICK": "RICHARD", "DICK": "RICHARD",
"RICHD": "RICHARD", "DICKY": "RICHARD",
// Henry
"HARRY": "HENRY", "HAL": "HENRY", "HEN": "HENRY",
// Benjamin
"BEN": "BENJAMIN", "BENNY": "BENJAMIN", "BENJ": "BENJAMIN",
// Frederick
"FRED": "FREDERICK", "FREDDY": "FREDERICK", "FREDK": "FREDERICK",
// Francis
"FRANK": "FRANCIS", "FRAN": "FRANCIS", "FRAS": "FRANCIS",
// Andrew
"ANDY": "ANDREW",
// Anthony
"TONY": "ANTHONY", "ANT": "ANTHONY",
// Arthur
"ART": "ARTHUR", "ARTIE": "ARTHUR",
// Albert
"AL": "ALBERT", "ALB": "ALBERT",
// Alfred
"ALF": "ALFRED", "ALFIE": "ALFRED",
// Walter
"WALT": "WALTER", "WALLY": "WALTER",
// Peter
"PETE": "PETER",
// Stephen/Steven
"STEVE": "STEPHEN", "STEPH": "STEPHEN",
// Nicholas
"NICK": "NICHOLAS", "NICKY": "NICHOLAS",
// Nathaniel
"NAT": "NATHANIEL", "NATE": "NATHANIEL", "NATHL": "NATHANIEL",
// Abraham
"ABE": "ABRAHAM",
// Isaac
"IKE": "ISAAC",
// Elijah
"LI": "ELIJAH", "LIJE": "ELIJAH",
// Emanuel / Emmanuel
"MANNY": "EMANUEL", "MANUEL": "EMANUEL",
// Harvey
"HARV": "HARVEY",
// Lewis / Louis
"LEW": "LEWIS",
// Moses
"MOSE": "MOSES",
// Solomon
"SOL": "SOLOMON",
// Tobias
"TOBY": "TOBIAS",
// Jeremiah
"JERRY": "JEREMIAH", "JER": "JEREMIAH",
// Ezekiel
"ZEKE": "EZEKIEL",
// Cornelius
"NEIL": "CORNELIUS", "CORN": "CORNELIUS",
// Bartholomew
"BART": "BARTHOLOMEW",
// Edmund
"ED": "EDMUND",
// Archibald
"ARCH": "ARCHIBALD", "ARCHIE": "ARCHIBALD",
// Augustus
"GUS": "AUGUSTUS",
// Ambrose
"AMB": "AMBROSE",
// Zachariah / Zachary
"ZACH": "ZACHARIAH", "ZACK": "ZACHARIAH",
// ---------- Female names ----------
// Elizabeth
"LIZ": "ELIZABETH", "LIZZIE": "ELIZABETH", "LIZZY": "ELIZABETH",
"BETH": "ELIZABETH", "BETTY": "ELIZABETH", "BETTE": "ELIZABETH",
"BESS": "ELIZABETH", "BESSIE": "ELIZABETH", "ELIZA": "ELIZABETH",
"ELIZ": "ELIZABETH", "LIBBY": "ELIZABETH",
// Mary
"MOLLY": "MARY", "POLLY": "MARY", "MAE": "MARY", "MAMIE": "MARY",
// Margaret
"MAG": "MARGARET", "MAGGIE": "MARGARET", "MEG": "MARGARET",
"PEGGY": "MARGARET", "MARG": "MARGARET", "MARGT": "MARGARET",
"RITA": "MARGARET",
// Catherine / Katherine
"KATE": "CATHERINE", "KATIE": "CATHERINE", "KIT": "CATHERINE",
"KITTY": "CATHERINE", "KATH": "CATHERINE",
// Sarah
"SARA": "SARAH", "SALLY": "SARAH", "SAL": "SARAH",
// Susan / Susannah
"SUE": "SUSAN", "SUSIE": "SUSAN", "SUSY": "SUSAN",
"SUSY_": "SUSANNAH", "SUSA": "SUSANNAH",
"SUSY": "SUSANNAH",
// Ann / Anne / Hannah
"ANNIE": "ANN", "ANNA": "ANN", "NAN": "ANN", "NANNY": "ANN",
"HANNA": "HANNAH",
// Martha
"MART": "MARTHA", "MATTIE": "MARTHA",
// Rebecca
"BECCA": "REBECCA", "BECKY": "REBECCA",
// Caroline / Carolina
"CARRIE": "CAROLINE", "CAROL": "CAROLINE",
// Eleanor
"NELL": "ELEANOR", "NELLIE": "ELEANOR", "NORA": "ELEANOR",
// Frances
"FANNY": "FRANCES",
// Harriet
"HATTIE": "HARRIET",
// Louisa
"LOU": "LOUISA", "LULA": "LOUISA",
// Matilda
"TILLY": "MATILDA", "TILLIE": "MATILDA",
// Virginia
"GINNY": "VIRGINIA",
// Lavinia
"VINA": "LAVINIA", "VINEY": "LAVINIA",
// Priscilla
"PRISSY": "PRISCILLA", "CILLA": "PRISCILLA",
// Delilah
"DELIA": "DELILAH", "LILA": "DELILAH",
// Lucinda
"LUCY": "LUCINDA",
// Phillis / Phyllis
"PHILLIS": "PHYLLIS",
// Minerva
"MINNIE": "MINERVA",
// ---- additions mined from mentions.csv ----
"SAML": "SAMUEL", "ALEXR": "ALEXANDER", "ANDW": "ANDREW",
"EDWD": "EDWARD", "JOSH": "JOSHUA",
"ELISABETH": "ELIZABETH", "BETTIE": "ELIZABETH", "BETSY": "ELIZABETH",
"BETSEY": "ELIZABETH", "LIZA": "ELIZABETH",
"SALLIE": "SARAH", "SADIE": "SARAH", "SADY": "SARAH",
"FANNIE": "FRANCES", "FRANKIE": "FRANCES",
"NANNIE": "ANN",
"MOLLIE": "MARY",
"MARGIE": "MARGARET", "MAGGY": "MARGARET",
"CATHARINE": "CATHERINE", "KATY": "CATHERINE",
"RACHAEL": "RACHEL",
"SUSANNA": "SUSANNAH", "SUSANAH": "SUSANNAH",
"JOHNNIE": "JOHN", "JIMMIE": "JAMES", "TOMMIE": "THOMAS",
"BILLIE": "WILLIAM", "GEORGIE": "GEORGE", "CHARLEY": "CHARLES",
"FREDDIE": "FREDERICK",
"NETTIE": "HENRIETTA", "HETTIE": "HESTER", "MILLIE": "MILDRED",
"MAY": "MARY", "ABRAM": "ABRAHAM",
};
// --- small self-contained helpers ---
static isPresent(v) {
return v !== null && v !== undefined && String(v).trim() !== "" && String(v).trim().toLowerCase() !== "null";
}
static normUpper(s) {
return Match.isPresent(s) ? String(s).trim().toUpperCase().replace(/[^A-Z]/g, "") : "";
}
static clamp(x, lo, hi) {
return Math.max(lo, Math.min(hi, x));
}
static jaro(s1, s2) {
if (!s1 || !s2) return 0.0;
s1 = String(s1).toUpperCase();
s2 = String(s2).toUpperCase();
if (s1 === s2) return 1.0;
const len1 = s1.length, len2 = s2.length;
const matchDistance = Math.max(0, Math.floor(Math.max(len1, len2) / 2) - 1);
const s1Matches = new Array(len1).fill(false);
const s2Matches = new Array(len2).fill(false);
let matches = 0;
for (let i = 0; i < len1; i++) {
const start = Math.max(0, i - matchDistance);
const end = Math.min(i + matchDistance + 1, len2);
for (let j = start; j < end; j++) {
if (s2Matches[j]) continue;
if (s1[i] !== s2[j]) continue;
s1Matches[i] = true; s2Matches[j] = true; matches++; break;
}
}
if (matches === 0) return 0.0;
let transpositions = 0, k = 0;
for (let i = 0; i < len1; i++) {
if (!s1Matches[i]) continue;
while (!s2Matches[k]) k++;
if (s1[i] !== s2[k]) transpositions++;
k++;
}
transpositions /= 2;
return (matches / len1 + matches / len2 + (matches - transpositions) / matches) / 3;
}
static jaroWinkler(s1, s2, prefixScale = 0.1, boostThreshold = 0.7) {
if (!s1 || !s2) return 0.0;
s1 = String(s1).toUpperCase();
s2 = String(s2).toUpperCase();
if (s1 === s2) return 1.0;
const j = Match.jaro(s1, s2);
if (j < boostThreshold) return j;
const maxPrefix = Math.min(4, s1.length, s2.length);
let prefix = 0;
while (prefix < maxPrefix && s1[prefix] === s2[prefix]) prefix++;
return j + prefix * prefixScale * (1 - j);
}
static doubleMetaphoneScore(codeA, codeB) {
if (!Match.isPresent(codeA) || !Match.isPresent(codeB)) return null;
const parse = (c) => {
const parts = String(c).toUpperCase().split(':').map((x) => x.trim().replace(/[^A-Z]/g, ''));
const primary = parts[0] || '';
const secondary = parts[1] || primary;
return { primary, secondary };
};
const A = parse(codeA);
const B = parse(codeB);
if (!A.primary || !B.primary) return 0.0;
if (A.primary === B.primary) return 1.0;
if (A.primary === B.secondary || A.secondary === B.primary) return 0.8;
if (A.secondary && A.secondary === B.secondary) return 0.6;
return 0.0;
}
static buildNameFrequencies(mentions) {
const firstNameFreq = new Map();
const lastNameFreq = new Map();
if (Array.isArray(mentions)) {
for (const m of mentions) {
if (!m) continue;
const fk = Match.normUpper(m.first_name || m.norm_first_name);
if (fk) firstNameFreq.set(fk, (firstNameFreq.get(fk) || 0) + 1);
const lk = Match.normUpper(m.last_name);
if (lk) lastNameFreq.set(lk, (lastNameFreq.get(lk) || 0) + 1);
}
}
return { firstNameFreq, lastNameFreq };
}
static nameWeightModifier(value, freqMap, rarityConfig = Match.DEFAULT_RARITY) {
const r = rarityConfig || Match.DEFAULT_RARITY;
const key = Match.normUpper(value);
if (!key || !freqMap || typeof freqMap.get !== 'function' || !freqMap.has(key)) return 0;
const count = freqMap.get(key) || 0;
if (count <= r.veryRareMax) return r.modVeryRare;
if (count <= r.uncommonMax) return r.modUncommon;
if (count <= r.averageMax) return r.modAverage;
if (count <= r.commonMax) return r.modCommon;
return r.modExtremelyCommon;
}
static nickname(name) {
if (!Match._defaultInstance) Match._defaultInstance = new Match();
return Match._defaultInstance.nickname(name);
}
static canonical(name) {
return Match.nickname(name);
}
constructor(config = {}) {
this.rarity = { ...Match.DEFAULT_RARITY, ...(config.rarity || {}) };
this.jwFuzzyPassThreshold = (config.jwFuzzyPassThreshold != null)
? config.jwFuzzyPassThreshold
: Match.DEFAULT_JW_FUZZY_PASS;
this.surnameFuzzyFloor = (config.surnameFuzzyFloor != null)
? config.surnameFuzzyFloor
: Match.DEFAULT_SURNAME_FUZZY_FLOOR;
this._nickToCanon = new Map();
const tables = [Match.DEFAULT_NICKNAMES, config.nicknames || {}];
for (const table of tables) {
for (const nickRaw of Object.keys(table)) {
const nick = Match.normUpper(nickRaw);
const canon = Match.normUpper(table[nickRaw]);
if (!nick || !canon) continue;
this._nickToCanon.set(nick, canon);
if (!this._nickToCanon.has(canon)) this._nickToCanon.set(canon, canon);
}
}
}
// -----------------------------------------------------------------------
// 1. NICKNAME & PHONETICS
// -----------------------------------------------------------------------
nickname(name) {
const key = Match.normUpper(name);
if (!key) return "";
return this._nickToCanon.get(key) || key;
}
canonical(name) { return this.nickname(name); }
sameNickname(a, b) {
const ca = this.nickname(a);
const cb = this.nickname(b);
return !!ca && ca === cb;
}
getNYSIIS(name) {
return Match.normUpper(name);
}
getMetaphone(name) {
return Match.normUpper(name);
}
doubleMetaphoneMatchScore(codeA, codeB) {
return Match.doubleMetaphoneScore(codeA, codeB);
}
// -----------------------------------------------------------------------
// 2. JARO-WINKLER
// -----------------------------------------------------------------------
jaro(s1, s2) {
if (!s1 || !s2) return 0.0;
s1 = String(s1).toUpperCase();
s2 = String(s2).toUpperCase();
if (s1 === s2) return 1.0;
const len1 = s1.length, len2 = s2.length;
const matchDistance = Math.max(0, Math.floor(Math.max(len1, len2) / 2) - 1);
const s1Matches = new Array(len1).fill(false);
const s2Matches = new Array(len2).fill(false);
let matches = 0;
for (let i = 0; i < len1; i++) {
const start = Math.max(0, i - matchDistance);
const end = Math.min(i + matchDistance + 1, len2);
for (let j = start; j < end; j++) {
if (s2Matches[j]) continue;
if (s1[i] !== s2[j]) continue;
s1Matches[i] = true; s2Matches[j] = true; matches++; break;
}
}
if (matches === 0) return 0.0;
let transpositions = 0, k = 0;
for (let i = 0; i < len1; i++) {
if (!s1Matches[i]) continue;
while (!s2Matches[k]) k++;
if (s1[i] !== s2[k]) transpositions++;
k++;
}
transpositions /= 2;
return (matches / len1 + matches / len2 + (matches - transpositions) / matches) / 3;
}
jaroWinkler(s1, s2, prefixScale = 0.1, boostThreshold = 0.7) {
if (!s1 || !s2) return 0.0;
s1 = String(s1).toUpperCase();
s2 = String(s2).toUpperCase();
if (s1 === s2) return 1.0;
const j = this.jaro(s1, s2);
if (j < boostThreshold) return j;
const maxPrefix = Math.min(4, s1.length, s2.length);
let prefix = 0;
while (prefix < maxPrefix && s1[prefix] === s2[prefix]) prefix++;
return j + prefix * prefixScale * (1 - j);
}
// -----------------------------------------------------------------------
// 3. RARITY
// -----------------------------------------------------------------------
buildNameFrequencies(mentions) {
const firstNameFreq = new Map();
const lastNameFreq = new Map();
if (Array.isArray(mentions)) {
for (const m of mentions) {
if (!m) continue;
const fk = Match.normUpper(m.first_name || m.norm_first_name);
if (fk) firstNameFreq.set(fk, (firstNameFreq.get(fk) || 0) + 1);
const lk = Match.normUpper(m.last_name);
if (lk) lastNameFreq.set(lk, (lastNameFreq.get(lk) || 0) + 1);
}
}
return { firstNameFreq, lastNameFreq };
}
nameWeightModifier(value, freqMap) {
const r = this.rarity;
const key = Match.normUpper(value);
if (!key || !freqMap || typeof freqMap.get !== 'function' || !freqMap.has(key)) return 0;
const count = freqMap.get(key) || 0;
if (count <= r.veryRareMax) return r.modVeryRare;
if (count <= r.uncommonMax) return r.modUncommon;
if (count <= r.averageMax) return r.modAverage;
if (count <= r.commonMax) return r.modCommon;
return r.modExtremelyCommon;
}
applyRarity(base, value, freqMap) {
if (!(base > 0)) return base;
const modifier = this.nameWeightModifier(value, freqMap) / 100;
return Match.clamp(base + modifier, 0, 1);
}
// =======================================================================
// LEVER A — NAME AGREEMENT
// =======================================================================
usePool(mentions) {
const { firstNameFreq, lastNameFreq } = this.buildNameFrequencies(mentions);
return this.useFrequencies(firstNameFreq, lastNameFreq);
}
useFrequencies(firstNameFreq, lastNameFreq) {
this._firstNameFreq = firstNameFreq || null;
this._lastNameFreq = lastNameFreq || null;
this._initialFreq = null;
return this;
}
setSurnameBridge(fn) {
this._surnameBridge = (typeof fn === 'function') ? fn : null;
return this;
}
MatchName(objA, objB) { return this.matchNameDetail(objA, objB).score; }
matchNameDetail(objA, objB) {
objA = objA || {};
objB = objB || {};
const sm = this._surnameMatch(objA, objB);
const firedSurname = sm.strength >= 0.8;
const gA = this._classifyGiven(objA);
const gB = this._classifyGiven(objB);
let rung = 'NONE';
let base = 0.0;
let needsCorroboration = false;
let usedFirstNameAgreement = false;
let usedInitial = false;
let initialLetter = '';
if (gA.cls === 'ABSENT' || gB.cls === 'ABSENT') {
if (firedSurname) { rung = 'SURNAME_ONLY'; base = 0.3; needsCorroboration = true; }
} else if (gA.cls === 'FULL' && gB.cls === 'FULL') {
// Three levels of given-name agreement, strongest first:
// givenIdentical - literally the same string after normUpper (base 1.0)
// givenExact - same canonical form via the nickname table, but NOT
// identical (Fannie/Frances) -> 0.85, needsCorroboration
// givenNickname - fuzzy Jaro-Winkler match -> 0.85, needsCorroboration
// A same-name-family, same-surname, close-birth pair is common among
// siblings and neighbors in a county census, so anything short of a
// literal match now wants corroboration.
const canonA = this.nickname(gA.norm);
const canonB = this.nickname(gB.norm);
const givenIdentical = gA.norm === gB.norm;
const givenExact = !givenIdentical && !!canonA && canonA === canonB;
const jw = this.jaroWinkler(gA.norm, gB.norm);
const givenNickname = jw >= this.jwFuzzyPassThreshold;
const givenAgree = givenIdentical || givenExact || givenNickname;
if (givenIdentical && firedSurname) {
rung = 'EXACT_FIRST_SURNAME'; base = 1.0; usedFirstNameAgreement = true;
} else if ((givenExact || givenNickname) && firedSurname) {
rung = 'NICKNAME_FIRST_SURNAME'; base = 0.85; needsCorroboration = true; usedFirstNameAgreement = true;
} else if (givenAgree && sm.strength >= 0.6 && sm.strength < 0.8) {
rung = 'PHONETIC_MODERATE_SURNAME'; base = 0.7; needsCorroboration = true; usedFirstNameAgreement = true;
} else if (givenAgree && sm.strength === 0.0) {
rung = 'GIVEN_NAME_ONLY'; base = 0.4; needsCorroboration = true; usedFirstNameAgreement = true;
} else if (firedSurname) {
rung = 'SURNAME_ONLY'; base = 0.3; needsCorroboration = true;
}
} else {
const bothInitials = gA.cls === 'INITIAL' && gB.cls === 'INITIAL';
const consistent = gA.initial === gB.initial;
initialLetter = gA.initial || gB.initial;
if (!consistent) {
if (firedSurname) { rung = 'SURNAME_ONLY'; base = 0.3; needsCorroboration = true; }
} else if (bothInitials) {
if (firedSurname) { rung = 'BOTH_INITIALS_SURNAME'; base = 0.35; needsCorroboration = true; usedInitial = true; }
} else {
if (firedSurname) { rung = 'INITIAL_CONSISTENT_SURNAME'; base = 0.55; needsCorroboration = true; usedInitial = true; }
}
}
let rarityFirst = 0;
let raritySurname = 0;
if (base > 0) {
if (firedSurname && this._lastNameFreq) {
const surname = this._resolveSurname(objA) || this._resolveSurname(objB);
raritySurname = this.nameWeightModifier(surname, this._lastNameFreq) / 100;
}
if (usedFirstNameAgreement && this._firstNameFreq) {
const fn = Match.isPresent(objA.norm_first_name) ? objA.norm_first_name : objA.first_name;
rarityFirst = this.nameWeightModifier(fn, this._firstNameFreq) / 100;
} else if (usedInitial && this._firstNameFreq) {
rarityFirst = this._initialLetterModifier(initialLetter) / 100;
}
}
const score = base > 0 ? Match.clamp(base + rarityFirst + raritySurname, 0, 1) : 0;
return {
score, rung,
surnameStrength: sm.strength, surnameKind: sm.kind,
weakSurnameHint: !!sm.weakHint, needsCorroboration,
givenClass: gA.cls + '/' + gB.cls,
rarityFirst, raritySurname,
middleTiebreak: this._middleTiebreak(objA, objB),
};
}
_surnameMatch(a, b) {
const fa = this._normFullName(a.full_name);
const fb = this._normFullName(b.full_name);
if (fa && fb && fa === fb) return { strength: 1.0, kind: 'EXACT_FULLNAME' };
const la = this._normLast(a.last_name);
const lb = this._normLast(b.last_name);
if (la && lb && la === lb) return { strength: 1.0, kind: 'EXACT_LASTNAME' };
// Surname-distance guard. The phonetic / NYSIIS / bridged tiers below match
// on CODES, not spellings, and double-metaphone primaries collide for
// genuinely different surnames (Bell/Bull, Price/Boyers, Carrier/Crow). A
// code match only stands if the raw surnames are also close under
// Jaro-Winkler (>= surnameFuzzyFloor). Exact full-/last-name matched above
// and are exempt. When a surname string is missing on either side we cannot
// verify spelling, so the guard is a no-op (evidence excluded, not penalized).
const surnameJw = (la && lb) ? this.jaroWinkler(la, lb) : null;
const guardOk = (surnameJw == null) || (surnameJw >= this.surnameFuzzyFloor);
if (guardOk && this._surnameBridge && this._surnameBridge(a, b)) return { strength: 0.9, kind: 'BRIDGED' };
const dm = this._doubleMetaphoneScore(a.metaphone_last_name, b.metaphone_last_name);
if (guardOk && dm === 1.0) return { strength: 1.0, kind: 'PHONETIC_STRONG' };
if (guardOk && dm === 0.8) return { strength: 0.8, kind: 'PHONETIC_MODERATE' };
// Check NYSIIS phonetic match
const na = Match.normUpper(a.nysiis_last_name);
const nb = Match.normUpper(b.nysiis_last_name);
if (guardOk && na && nb && na === nb) return { strength: 0.85, kind: 'NYSIIS' };
if (guardOk && dm === 0.6) return { strength: 0.6, kind: 'PHONETIC_WEAK', weakHint: true };
// Fuzzy Jaro-Winkler similarity on surnames (already distance-based, so it
// carries its own guard - no separate floor needed).
if (la && lb) {
const jw = surnameJw != null ? surnameJw : this.jaroWinkler(la, lb);
if (jw >= 0.90) return { strength: 0.80, kind: 'FUZZY_STRONG' };
if (jw >= 0.85) return { strength: 0.65, kind: 'FUZZY_MODERATE', weakHint: true };
}
return { strength: 0.0, kind: 'NO_MATCH' };
}
// surnameReliability scalar for calibration (feature D). Unknown kinds get a
// neutral 0.5 so a new tier never silently reads as fully trustworthy.
_surnameReliability(kind) {
const R = Match.SURNAME_RELIABILITY;
return (kind && R[kind] != null) ? R[kind] : 0.5;
}
_doubleMetaphoneScore(codeA, codeB) {
return Match.doubleMetaphoneScore(codeA, codeB);
}
// A compound given name ("MARY FRANCIS", "JAMES F", "WILLIAM ANDERSON")
// must compare on its FIRST token. normUpper strips whitespace, so
// "MARTHA J" collapses to "MARTHAJ" and never equals "MARTHA" - not on the
// nickname table, not on Jaro-Winkler, not on the blocking key. 1,378 AUG
// mentions (~1% of the corpus) carry a multi-token norm_first_name, and
// 1,343 of them have a first token that already exists as a simple form,
// so nearly all of them are silently unreachable today.
//
// The trailing tokens are not discarded: a single-letter tail is returned
// as a middle initial, which the caller can use as corroboration rather
// than letting it destroy the given-name comparison.
_classifyGiven(o) {
const raw = Match.isPresent(o.norm_first_name) ? o.norm_first_name : o.first_name;
const parts = String(raw == null ? '' : raw).trim().split(/[\s.]+/).filter(Boolean);
const n = Match.normUpper(parts.length ? parts[0] : '');
const tail = parts.slice(1).map(t => Match.normUpper(t)).filter(Boolean);
const extraInitial = tail.length === 1 && tail[0].length === 1 ? tail[0] : '';
if (!n) return { cls: 'ABSENT', norm: '', initial: '', tail: tail, extraInitial: '' };
if (n.length === 1) return { cls: 'INITIAL', norm: n, initial: n, tail: tail, extraInitial: extraInitial };
return { cls: 'FULL', norm: n, initial: n[0], tail: tail, extraInitial: extraInitial };
}
_normFullName(s) {
if (!Match.isPresent(s)) return '';
return String(s).toUpperCase().replace(/[^A-Z0-9]+/g, ' ').replace(/\s+/g, ' ').trim();
}
_normLast(s) { return Match.normUpper(s); }
_resolveSurname(o) {
if (Match.isPresent(o.last_name)) return Match.normUpper(o.last_name);
const full = this._normFullName(o.full_name);
if (full) { const t = full.split(' '); return Match.normUpper(t[t.length - 1]); }
return '';
}
_initialLetterModifier(letter) {
const L = Match.normUpper(letter);
if (!L || !this._firstNameFreq) return 0;
if (!this._initialFreq) {
const m = new Map();
let total = 0;
for (const [name, cnt] of this._firstNameFreq.entries()) {
const c = name && name[0];
if (!c) continue;
m.set(c, (m.get(c) || 0) + cnt);
total += cnt;
}
m.set('__total__', total || 1);
this._initialFreq = m;
}
const total = this._initialFreq.get('__total__') || 1;
const share = (this._initialFreq.get(L) || 0) / total;
if (share >= 0.09) return -15;
if (share >= 0.06) return -5;
if (share >= 0.03) return 0;
if (share >= 0.01) return 5;
return 15;
}
_middleTiebreak(a, b) {
const ma = Match.normUpper(a.middle_name);
const mb = Match.normUpper(b.middle_name);
if (!ma || !mb) return 'NO_DATA';
if (ma === mb) return 'MATCH';
if (ma[0] === mb[0] && (ma.length === 1 || mb.length === 1)) return 'MATCH';
return 'MISMATCH';
}
// A non-head whose surname differs from the household head's is living in
// someone else's household - boarder, servant, farm laborer. Kin absence
// from that roster carries no information about identity, so the
// corroboration gate must not treat it as a missing corroboration.
// Conservative by design: when headship or either surname is unknown it
// returns false, leaving the gate's previous behavior in place.
// Multiplier on Lever B sigma for a possibly-heaped age. Returns 1 when the
// age cannot be computed, is under 20, or does not land on a multiple of 5.
static _heapFactor(birthRange, censusYear) {
if (!birthRange || !censusYear) return 1;
const age = censusYear - Math.round((birthRange[0] + birthRange[1]) / 2);
if (!(age >= 20)) return 1;
if (age % 10 === 0) return 1.35; // strongest pile-up
if (age % 5 === 0) return 1.20;
return 1;
}
// Does the candidate's household have its spouse slot occupied by someone
// who is clearly NOT the person's known spouse? ctx.personKin entries may
// carry a _predicate ('isSpouseOf'); without it nothing fires, so callers
// that do not label kin are unaffected.
_spouseContradiction(ctx, censusYear) {
const none = { fired: false, strength: 0 };
const kin = Array.isArray(ctx.personKin) ? ctx.personKin : [];
const roster = Array.isArray(ctx.candidateHousehold) ? ctx.candidateHousehold : [];
if (!kin.length || !roster.length) return none;
const spouses = kin.filter(k => k && String(k._predicate || '') === 'isSpouseOf');
if (!spouses.length) return none;
// A spouse already dead by this year cannot be expected in the roster,
// and remarriage is then the expected outcome rather than a red flag.
const alive = spouses.filter(sp => {
const d = parseInt(String(sp.death_year || '').match(/\d{4}/) || [], 10);
return !(Number.isFinite(d) && censusYear && d < censusYear);
});
if (!alive.length) return none;
// The roster's spouse slot: a co-resident adult of the opposite gender
// to the candidate, close in age. Relationship-to-head is not in the
// data, so this is inferred.
let worst = none;
for (const sp of alive) {
const spg = this._gender(sp), spy = this._birthYear(sp);
if (!spg) continue;
for (const r of roster) {
if (this._gender(r) !== spg) continue;
const ry = this._birthYear(r);
if (ry == null || censusYear == null) continue;
if (censusYear - ry < 16) continue; // not an adult
if (spy != null && Math.abs(ry - spy) > 15) continue; // wrong generation
const ns = this.MatchName(sp, r);
if (ns >= 0.6) return none; // the slot IS our spouse: no contradiction
const ageOff = spy != null ? Math.min(1, Math.abs(ry - spy) / 12) : 0.5;
const strength = Match.clamp((1 - ns) * (0.5 + 0.5 * ageOff), 0, 1);
if (strength > worst.strength) {
worst = { fired: true, strength, occupant: r, expected: sp, nameScore: +ns.toFixed(3) };
}
}
}
return worst;
}
// 'AGREE' | 'DISAGREE' | 'NA'. Reads an explicit middle_name and the tail of
// a compound given name, so "Martha J Crawford" and "Martha Crawford" with
// middle_name "J" both yield J.
_middleInitial(o) {
if (!o) return '';
const mid = Match.normUpper(o.middle_name);
if (mid) return mid[0];
const g = this._classifyGiven(o);
return g && g.extraInitial ? g.extraInitial[0] : '';
}
_middleInitialState(a, b) {
const x = this._middleInitial(a), y = this._middleInitial(b);
if (!x || !y) return 'NA';
return x === y ? 'AGREE' : 'DISAGREE';
}
_sourceYear(o, fallbackSource) {
if (!o) return null;
const direct = parseInt(o.source_year, 10);
if (Number.isFinite(direct)) return direct;
const m = String(o.source || fallbackSource || '').match(/(1[6-9]\d{2}|20\d{2})/);
return m ? parseInt(m[1], 10) : null;
}
static isBoarder(mention, roster) {
if (!mention || !Array.isArray(roster) || !roster.length) return false;
const isHead = h => h === true || String(h).trim().toLowerCase() === 't' ||
String(h).trim().toLowerCase() === 'true';
if (isHead(mention.head)) return false;
let head = null;
for (const r of roster) { if (isHead(r.head)) { head = r; break; } }
if (!head) return false;
const a = Match.normUpper(mention.last_name), b = Match.normUpper(head.last_name);
if (!a || !b) return false;
return a !== b;
}
_hasName(o) {
if (!o) return false;
return Match.isPresent(o.first_name) || Match.isPresent(o.norm_first_name) ||
Match.isPresent(o.last_name) || Match.isPresent(o.full_name);
}
// =======================================================================
// CROSS-CENSUS PERSON MATCHING helpers
// =======================================================================
_gender(o) {
const g = String((o && o.gender) || '').split(':')[0].trim().toUpperCase();
return (g === 'M' || g === 'MALE') ? 'M' : (g === 'F' || g === 'FEMALE') ? 'F' : '';
}
_race(o) {
return String((o && (o.norm_race || o.race)) || '').split(':')[0].trim().toUpperCase();
}
// Race CLASS for knockout purposes. Collapses Black<->Mulatto (and common
// synonyms) into a single non-white class, because B<->M reclassification
// across enumerations is routine and must not veto a true match. White stays
// separate; other codes (I, C, Y, ...) compare as-is.
_raceClass(o) {
const r = String((o && (o.norm_race || o.race)) || '').split(':')[0].trim().toUpperCase().replace(/[^A-Z]/g, '');
if (!r) return '';
if (r === 'W' || r === 'WHITE') return 'W';
if (r === 'B' || r === 'BLACK' || r === 'M' || r === 'MU' || r === 'MULATTO' || r === 'NEGRO' || r === 'COLORED') return 'BLACK';
return r;
}
_birthYear(o) {
const v = String((o && o.birth_year != null) ? o.birth_year : '').split(':')[0].trim();
const n = parseInt(v, 10);
return Number.isFinite(n) ? n : null;
}
// Normalized birth place for EXACT matching. Prefers a norm_birth_place
// column if present, else birth_place. Case/whitespace-insensitive, trailing
// punctuation dropped; otherwise compared verbatim. Returns '' when absent.
_birthPlace(o) {
const raw = (o && (o.norm_birth_place != null && String(o.norm_birth_place).trim() !== '')) ? o.norm_birth_place
: (o && o.birth_place != null) ? o.birth_place : '';
let s = String(raw).split(':')[0].trim();
if (!s || s.toLowerCase() === 'null') return '';
return s.toUpperCase().replace(/\s+/g, ' ').replace(/[.\s]+$/, '').trim();
}
// Normalized occupation CATEGORY for boost-only agreement. norm_occupation
// holds coarse categories (DOMESTIC, AGRICULTURE, LABORER, ...). Blank / null
// / configured boilerplate => '' (neutral). Compared verbatim after
// case/whitespace normalization.
_normOccupation(o, boilerplate) {
const raw = (o && (o.norm_occupation != null && String(o.norm_occupation).trim() !== '')) ? o.norm_occupation
: (o && o.occupation != null) ? o.occupation : '';
let s = String(raw).split(':')[0].trim();
if (!s || s.toLowerCase() === 'null') return '';
s = s.toUpperCase().replace(/\s+/g, ' ').trim();
if (boilerplate && boilerplate.has(s)) return '';
return s;
}
// --- Lever C — household / family continuity (noisy-OR support) ---------
// Matches each anchor member to at most one candidate member by name
// (>= nameThreshold) + birth-year gap + non-disagreeing gender. Each matched
// relative yields a quality h_k in [0,1]; support is aggregated as a noisy-OR
// H = 1 - prod(1 - h_k)
// so one strong corroborating relative already moves H substantially, with
// diminishing returns and saturation toward 1. The legacy linear `score`
// (+0.5/member, cap 2.0) is retained for backward compatibility only.
scoreHousehold(anchorMembers, candidateMembers, opts = {}) {
const maxGap = opts.birthGap != null ? opts.birthGap : 3;
const nameThreshold = opts.nameThreshold != null ? opts.nameThreshold : 0.6;
const aM = (anchorMembers || []).filter(Boolean);
const cM = (candidateMembers || []).filter(Boolean);
const used = new Set();
const matched = [];
const qualities = [];
for (const am of aM) {
let best = null, bestRank = 0, bestIdx = -1, bestQ = 0;
for (let i = 0; i < cM.length; i++) {
if (used.has(i)) continue;
const cm = cM[i];
const ga = this._gender(am), gc = this._gender(cm);
if (ga && gc && ga !== gc) continue;
const ay = this._birthYear(am), cy = this._birthYear(cm);
const gap = (ay != null && cy != null) ? Math.abs(ay - cy) : null;
if (gap != null && gap > maxGap) continue;
const ns = this.MatchName(am, cm);
if (ns < nameThreshold) continue;
const birthAgree = (gap != null) ? (1 - gap / (maxGap + 1)) : 0.5;
const rank = ns + birthAgree; // 0..2, ranking only
if (rank > bestRank) {
bestRank = rank; best = cm; bestIdx = i;
bestQ = Match.clamp(0.5 * ns + 0.5 * birthAgree, 0, 1);
}
}
if (best) { used.add(bestIdx); matched.push({ anchor: am, candidate: best }); qualities.push(bestQ); }
}
let prod = 1;
for (const q of qualities) prod *= (1 - q);
const H = 1 - prod;
const score = Math.min(2.0, matched.length * 0.5);
return { score, H, qualities, matched, count: matched.length, fired: matched.length >= 1 };
}
// --- rank a later-census pool against one anchor ----------------------
rankCensusCandidates(anchor, pool, opts = {}) {
const window = opts.birthWindow != null ? opts.birthWindow : 10;
const ay = this._birthYear(anchor);
const ag = this._gender(anchor);
const ar = this._raceClass(anchor);
const anchorHH = opts.anchorHousehold || [];
const households = opts.households || null;
const out = [];
for (const cand of pool) {
if (cand === anchor) continue;
if (ag) { const cg = this._gender(cand); if (cg && cg !== ag) continue; }
if (ar) { const cr = this._raceClass(cand); if (cr && ar && cr !== ar) continue; }
if (ay != null) { const cy = this._birthYear(cand); if (cy != null && Math.abs(cy - ay) > window) continue; }
let candHH = [];
if (households) {
const h = String(cand.household_id || '').trim();
if (h && households.has(h)) candHH = households.get(h).filter((m) => m !== cand);
}
const censusYear = opts.censusYear != null ? opts.censusYear : (parseInt(cand.source_year, 10) || null);
const res = this.MatchPerson(anchor, cand, {
censusYear,
personKin: anchorHH,
candidateHousehold: candHH,
householdOpts: opts.householdOpts,
householdBoost: opts.householdBoost,
weights: opts.weights,
birthProfiles: opts.birthProfiles,
targetSource: opts.targetSource,
candidateSource: opts.candidateSource,
});
if (res.tier === 'KNOCKOUT') continue;
out.push(Object.assign({ candidate: cand }, res));
}
out.sort((x, y) => y.score - x.score);
return out;
}
// =======================================================================
// PROBABILITY CALIBRATION (features = [name, birth, H, surnameReliability])
// surnameReliability lets probability see how trustworthy the surname match
// is - the signal the old [name, birth, H] vector was blind to. Margin
// (winner - runner-up) is a CALLER-level signal (it needs the full candidate
// set) and is deliberately NOT in this per-pair vector; put it in the caller's
// MATCH/MAYBE bucketing instead. When you change this list, update the
// caller's labeled-pair export in the same commit or every fitted model
// silently misaligns (probability() throws on length mismatch, swallowed).
// =======================================================================
_calibFeatures(res) {
if (Array.isArray(res)) return res.slice();