@mailwoman/registry 5.8.0 → 5.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/out/address-key.d.ts +1 -1
  2. package/out/geocode-handler.d.ts +2 -2
  3. package/out/geojson.d.ts +1 -1
  4. package/out/index.d.ts +10 -10
  5. package/out/ingest.d.ts +1 -1
  6. package/out/learned-scorer.d.ts +2 -2
  7. package/out/learned-scorer.js +1 -1
  8. package/out/map-html.d.ts +1 -1
  9. package/out/reconcile.d.ts +2 -2
  10. package/out/reconcile.js +1 -1
  11. package/out/resolve.d.ts +1 -1
  12. package/out/tools/coverage-reconciliation.d.ts +51 -0
  13. package/out/tools/coverage-reconciliation.d.ts.map +1 -0
  14. package/out/tools/coverage-reconciliation.js +166 -0
  15. package/out/tools/coverage-reconciliation.js.map +1 -0
  16. package/out/tools/cross-dataset-correlation.d.ts +49 -0
  17. package/out/tools/cross-dataset-correlation.d.ts.map +1 -0
  18. package/out/tools/cross-dataset-correlation.js +340 -0
  19. package/out/tools/cross-dataset-correlation.js.map +1 -0
  20. package/out/tools/cross-source-threshold-sweep.d.ts +52 -0
  21. package/out/tools/cross-source-threshold-sweep.d.ts.map +1 -0
  22. package/out/tools/cross-source-threshold-sweep.js +328 -0
  23. package/out/tools/cross-source-threshold-sweep.js.map +1 -0
  24. package/out/tools/dedup-ceiling.d.ts +21 -3
  25. package/out/tools/dedup-ceiling.d.ts.map +1 -1
  26. package/out/tools/dedup-ceiling.js +16 -30
  27. package/out/tools/dedup-ceiling.js.map +1 -1
  28. package/out/tools/eval-geocoder.d.ts +45 -0
  29. package/out/tools/eval-geocoder.d.ts.map +1 -0
  30. package/out/tools/eval-geocoder.js +14 -0
  31. package/out/tools/eval-geocoder.js.map +1 -0
  32. package/out/tools/geocoder-namesake-probe.d.ts +26 -0
  33. package/out/tools/geocoder-namesake-probe.d.ts.map +1 -0
  34. package/out/tools/geocoder-namesake-probe.js +59 -0
  35. package/out/tools/geocoder-namesake-probe.js.map +1 -0
  36. package/out/tools/geocoder-vs-provided-coords.d.ts +38 -0
  37. package/out/tools/geocoder-vs-provided-coords.d.ts.map +1 -0
  38. package/out/tools/geocoder-vs-provided-coords.js +132 -0
  39. package/out/tools/geocoder-vs-provided-coords.js.map +1 -0
  40. package/out/tools/gold-set-sample.d.ts +22 -3
  41. package/out/tools/gold-set-sample.d.ts.map +1 -1
  42. package/out/tools/gold-set-sample.js +17 -32
  43. package/out/tools/gold-set-sample.js.map +1 -1
  44. package/out/tools/index.d.ts +36 -0
  45. package/out/tools/index.d.ts.map +1 -0
  46. package/out/tools/index.js +36 -0
  47. package/out/tools/index.js.map +1 -0
  48. package/out/tools/learned-scorer-clustering-eval.d.ts +54 -0
  49. package/out/tools/learned-scorer-clustering-eval.d.ts.map +1 -0
  50. package/out/tools/learned-scorer-clustering-eval.js +368 -0
  51. package/out/tools/learned-scorer-clustering-eval.js.map +1 -0
  52. package/out/tools/learned-scorer-crossstate-eval.d.ts +43 -0
  53. package/out/tools/learned-scorer-crossstate-eval.d.ts.map +1 -0
  54. package/out/tools/learned-scorer-crossstate-eval.js +305 -0
  55. package/out/tools/learned-scorer-crossstate-eval.js.map +1 -0
  56. package/out/tools/learned-scorer-eval.d.ts +59 -0
  57. package/out/tools/learned-scorer-eval.d.ts.map +1 -0
  58. package/out/tools/learned-scorer-eval.js +450 -0
  59. package/out/tools/learned-scorer-eval.js.map +1 -0
  60. package/out/tools/matcher-scale.d.ts +17 -3
  61. package/out/tools/matcher-scale.d.ts.map +1 -1
  62. package/out/tools/matcher-scale.js +14 -30
  63. package/out/tools/matcher-scale.js.map +1 -1
  64. package/out/tools/nppes-dedup-benchmark.d.ts +75 -0
  65. package/out/tools/nppes-dedup-benchmark.d.ts.map +1 -0
  66. package/out/tools/nppes-dedup-benchmark.js +846 -0
  67. package/out/tools/nppes-dedup-benchmark.js.map +1 -0
  68. package/out/tools/train-cross-gbt.d.ts +58 -0
  69. package/out/tools/train-cross-gbt.d.ts.map +1 -0
  70. package/out/tools/train-cross-gbt.js +324 -0
  71. package/out/tools/train-cross-gbt.js.map +1 -0
  72. package/out/tools/train-gbt.d.ts +51 -0
  73. package/out/tools/train-gbt.d.ts.map +1 -0
  74. package/out/tools/train-gbt.js +268 -0
  75. package/out/tools/train-gbt.js.map +1 -0
  76. package/out/tools/train-org-cross-gbt.d.ts +51 -0
  77. package/out/tools/train-org-cross-gbt.d.ts.map +1 -0
  78. package/out/tools/train-org-cross-gbt.js +296 -0
  79. package/out/tools/train-org-cross-gbt.js.map +1 -0
  80. package/out/tools/txhhsc-to-oarow.d.ts +14 -3
  81. package/out/tools/txhhsc-to-oarow.d.ts.map +1 -1
  82. package/out/tools/txhhsc-to-oarow.js +44 -52
  83. package/out/tools/txhhsc-to-oarow.js.map +1 -1
  84. package/out/tools/viz/cross-dataset-map.d.ts +23 -4
  85. package/out/tools/viz/cross-dataset-map.d.ts.map +1 -1
  86. package/out/tools/viz/cross-dataset-map.js +42 -46
  87. package/out/tools/viz/cross-dataset-map.js.map +1 -1
  88. package/out/tools/viz/geocode-first-surface.d.ts +17 -4
  89. package/out/tools/viz/geocode-first-surface.d.ts.map +1 -1
  90. package/out/tools/viz/geocode-first-surface.js +71 -78
  91. package/out/tools/viz/geocode-first-surface.js.map +1 -1
  92. package/out/tools/viz/render-map.d.ts +17 -3
  93. package/out/tools/viz/render-map.d.ts.map +1 -1
  94. package/out/tools/viz/render-map.js +26 -26
  95. package/out/tools/viz/render-map.js.map +1 -1
  96. package/out/tools/viz/render.d.ts +21 -3
  97. package/out/tools/viz/render.d.ts.map +1 -1
  98. package/out/tools/viz/render.js +43 -39
  99. package/out/tools/viz/render.js.map +1 -1
  100. package/out/tools/viz/source-provenance-map.d.ts +24 -5
  101. package/out/tools/viz/source-provenance-map.d.ts.map +1 -1
  102. package/out/tools/viz/source-provenance-map.js +53 -62
  103. package/out/tools/viz/source-provenance-map.js.map +1 -1
  104. package/out/tools/viz/yardstick-figure.d.ts +11 -3
  105. package/out/tools/viz/yardstick-figure.d.ts.map +1 -1
  106. package/out/tools/viz/yardstick-figure.js +68 -73
  107. package/out/tools/viz/yardstick-figure.js.map +1 -1
  108. package/package.json +50 -10
@@ -0,0 +1,846 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * The #617 NPPES dedup benchmark — the measurable proof of the record-matcher hypothesis.
7
+ *
8
+ * NPPES is NPI-keyed, so the NPI is a ground-truth entity id. We build a deliberately varied
9
+ * multi-record set per NPI from REAL data — the registry's primary record, each alternate
10
+ * organization name (`nppes_other-names`, NAME drift at the same place), and the mailing address
11
+ * where it differs from the practice location (ADDRESS variation) — then run the matcher BLIND to
12
+ * the NPI (geocode → block → Fellegi-Sunter + EM → cluster) and score the recovered clusters
13
+ * against the NPI grouping (pairwise P/R/F1 + adjusted Rand).
14
+ *
15
+ * Honest reading (per the epic): NPI-as-truth is CONSERVATIVE. A cluster that merges two NPIs is a
16
+ * candidate "same entity, two NPIs" surfaced for review, not an error we adjudicate; and a single
17
+ * NPI split across two genuinely-distant addresses is geo-first behaving correctly, counted here
18
+ * as a recall miss. We resolve and report; interpretation is the consumer's.
19
+ *
20
+ * Sample: a tractable, variation-rich cut — providers in one state (default TX) that have ≥1
21
+ * alternate name, so every entity has ≥2 records and the dedup is non-trivial. Streams the 4.8 GB
22
+ * registry via `streamRows` (#616), so nothing loads whole.
23
+ *
24
+ * Run: `mailwoman registry scorer-eval nppes-benchmark [--state TX] [--max-npis 300]
25
+ * [--wof <admin.db>] [--data-root <dir>] [--no-train-em]
26
+ * [--out-md docs/articles/evals/<date>-nppes-dedup-benchmark.md]`
27
+ */
28
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
29
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
30
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
31
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
32
+ });
33
+ }
34
+ return path;
35
+ };
36
+ import { writeFileSync } from "node:fs";
37
+ import { resolve as resolvePath } from "node:path";
38
+ import { pathToFileURL } from "node:url";
39
+ import { dataRootPath } from "@mailwoman/core/utils";
40
+ import { haversineKm } from "@mailwoman/match";
41
+ import { addressFrequencyKey, ingestRows, resolveEntities, streamRows, } from "@mailwoman/registry";
42
+ import { latLngToCell } from "h3-js";
43
+ // NPPES column names (verbatim from the file headers).
44
+ const C = {
45
+ npi: "NPI",
46
+ entityType: "Entity Type Code",
47
+ orgLegal: "Provider Organization Name (Legal Business Name)",
48
+ last: "Provider Last Name (Legal Name)",
49
+ first: "Provider First Name",
50
+ pAddr: "Provider First Line Business Practice Location Address",
51
+ pCity: "Provider Business Practice Location Address City Name",
52
+ pState: "Provider Business Practice Location Address State Name",
53
+ pZip: "Provider Business Practice Location Address Postal Code",
54
+ mAddr: "Provider First Line Business Mailing Address",
55
+ mCity: "Provider Business Mailing Address City Name",
56
+ mState: "Provider Business Mailing Address State Name",
57
+ mZip: "Provider Business Mailing Address Postal Code",
58
+ otherOrg: "Provider Other Organization Name",
59
+ authLast: "Authorized Official Last Name",
60
+ authFirst: "Authorized Official First Name",
61
+ isSubpart: "Is Organization Subpart",
62
+ parentLBN: "Parent Organization LBN",
63
+ parentTIN: "Parent Organization TIN",
64
+ // #625 taxonomy discriminator: the 15 taxonomy slots; collected as a set (any shared code = agreement).
65
+ taxonomy: Array.from({ length: 15 }, (_, i) => `Healthcare Provider Taxonomy Code_${i + 1}`),
66
+ };
67
+ const norm = (s) => (s ?? "").trim();
68
+ const addr = (line, city, st, zip) => [norm(line), norm(city), norm(st), norm(zip)].filter(Boolean).join(", ");
69
+ // Org-name similarity for the org-name entity-truth (the gold-set rule: same address + same org name
70
+ // ⇒ same entity, even when NPPES doesn't flag the subpart). Strip corporate-form + articles, keep
71
+ // domain words (the distinguishing signal).
72
+ const ORG_STOP = new Set([
73
+ "llc",
74
+ "inc",
75
+ "incorporated",
76
+ "corp",
77
+ "corporation",
78
+ "co",
79
+ "ltd",
80
+ "pllc",
81
+ "pc",
82
+ "pa",
83
+ "lp",
84
+ "llp",
85
+ "the",
86
+ "of",
87
+ "and",
88
+ ]);
89
+ const orgTokens = (s) => new Set(s
90
+ .toLowerCase()
91
+ .replace(/[^a-z0-9 ]/g, " ")
92
+ .split(/\s+/)
93
+ .filter((t) => t && !ORG_STOP.has(t)));
94
+ function orgJaccard(a, b) {
95
+ if (a.size === 0 || b.size === 0)
96
+ return 0;
97
+ let inter = 0;
98
+ for (const t of a)
99
+ if (b.has(t)) {
100
+ inter++;
101
+ }
102
+ return inter / (a.size + b.size - inter);
103
+ }
104
+ const ORG_TAU = 0.7; // gold-set threshold
105
+ /** The #617 NPPES dedup benchmark — see the module doc. Emits the markdown report to stdout. */
106
+ export async function nppesDedupBenchmark(options, report) {
107
+ const SOURCES = options.sources || dataRootPath("record-matcher", "sources");
108
+ const STATE = (options.state || "TX").toUpperCase();
109
+ const MAX_NPIS = options.maxNpis ?? 300;
110
+ const OUT_MD = options.outMd || "";
111
+ const TRAIN_EM = options.trainEm ?? true;
112
+ const LEGACY = options.legacyJoin ?? false;
113
+ const CANDIDATE = options.candidate || "";
114
+ const PARALLEL_GEOCODE = options.parallelGeocode ?? false;
115
+ const GEO_CONC = options.geoConcurrency ?? 2;
116
+ const REGISTRY = `${SOURCES}/nppes_npi-registry_20260607.tsv`;
117
+ const OTHER_NAMES = `${SOURCES}/nppes_other-names_20260607.tsv`;
118
+ // --- Phase A: the variation set — NPIs that carry ≥1 alternate organization name. ---
119
+ report?.("[A] streaming other-names…");
120
+ const altNames = new Map();
121
+ for await (const r of streamRows(OTHER_NAMES)) {
122
+ const npi = norm(r[C.npi]);
123
+ const alt = norm(r[C.otherOrg]);
124
+ if (!npi || !alt)
125
+ continue;
126
+ const list = altNames.get(npi) ?? [];
127
+ if (list.length < 5) {
128
+ list.push(alt);
129
+ } // cap fan-out per NPI
130
+ altNames.set(npi, list);
131
+ }
132
+ report?.(` ${altNames.size} NPIs with ≥1 alternate name`);
133
+ // --- Phase B: ONE full registry pass — build the GLOBAL address-frequency table (every practice
134
+ // address, so the sharing structure is corpus-wide, not sample-biased) AND collect the sample. ---
135
+ report?.(`[B] full registry pass: address-frequency table + ${MAX_NPIS} ${STATE} sample…`);
136
+ const rows = [];
137
+ const kept = new Set();
138
+ // Per-NPI primary org name + practice address key — the basis for the ORG-NAME entity-truth.
139
+ const npiPrimary = new Map();
140
+ const addrCounts = new Map();
141
+ let addrTotal = 0;
142
+ let scanned = 0;
143
+ for await (const r of streamRows(REGISTRY)) {
144
+ if (++scanned % 1_000_000 === 0) {
145
+ report?.(` scanned ${scanned / 1e6}M rows, kept ${kept.size}`);
146
+ }
147
+ const practice = addr(r[C.pAddr], r[C.pCity], r[C.pState], r[C.pZip]);
148
+ // Global address-frequency: count every practice address (one row ≈ one distinct NPI).
149
+ if (practice) {
150
+ const k = addressFrequencyKey(practice);
151
+ addrCounts.set(k, (addrCounts.get(k) ?? 0) + 1);
152
+ addrTotal++;
153
+ }
154
+ // Sample: in-state NPIs with ≥1 alternate name, up to MAX_NPIS — NO early break (the table needs the full pass).
155
+ const npi = norm(r[C.npi]);
156
+ if (kept.size < MAX_NPIS &&
157
+ npi &&
158
+ !kept.has(npi) &&
159
+ altNames.has(npi) &&
160
+ practice &&
161
+ norm(r[C.pState]).toUpperCase() === STATE) {
162
+ const isOrg = norm(r[C.entityType]) === "2";
163
+ const primaryName = isOrg ? norm(r[C.orgLegal]) : `${norm(r[C.first])} ${norm(r[C.last])}`.trim();
164
+ if (primaryName) {
165
+ const org = isOrg ? norm(r[C.orgLegal]) : "";
166
+ const auth = `${norm(r[C.authFirst])} ${norm(r[C.authLast])}`.trim(); // the NPI's registrant — shared across its records
167
+ // #625: the taxonomy-code set (up to 15 slots), whitespace-joined — identical across the NPI's
168
+ // records by construction (it's a per-NPI registry attribute), so it NEVER splits one entity;
169
+ // it only separates co-located DISTINCT providers whose sets are disjoint.
170
+ const taxonomy = C.taxonomy
171
+ .map((col) => norm(r[col]))
172
+ .filter(Boolean)
173
+ .join(" ");
174
+ // Entity-level (site) truth: same org + same physical address. Subparts (NPPES
175
+ // "Is Organization Subpart" + parent LBN/TIN) collapse to their PARENT, so the matcher isn't
176
+ // charged for correctly fusing one org's many subpart-NPIs at a site; an NPI's mailing-vs-
177
+ // practice records stay DISTINCT sites. orgKey = parent identity for subparts, else the NPI
178
+ // (independent orgs sharing an address stay distinct — the conservative choice).
179
+ const isSubpart = norm(r[C.isSubpart]).toUpperCase() === "Y";
180
+ const parentKey = `${norm(r[C.parentLBN])}|${norm(r[C.parentTIN])}`.toLowerCase();
181
+ const orgKey = isSubpart && parentKey !== "|" ? `p:${parentKey}` : `n:${npi}`;
182
+ const eid = (a) => `${addressFrequencyKey(a)}|${orgKey}`;
183
+ if (org) {
184
+ npiPrimary.set(npi, { tokens: orgTokens(org), addrKey: addressFrequencyKey(practice) });
185
+ }
186
+ kept.add(npi);
187
+ rows.push({ npi, name: primaryName, org, address: practice, auth, taxonomy, entityID: eid(practice) });
188
+ // primary
189
+ for (const alt of altNames.get(npi)) {
190
+ rows.push({ npi, name: alt, org: alt, address: practice, auth, taxonomy, entityID: eid(practice) });
191
+ } // name drift
192
+ const mailing = addr(r[C.mAddr], r[C.mCity], r[C.mState], r[C.mZip]);
193
+ if (mailing && mailing !== practice) {
194
+ rows.push({ npi, name: primaryName, org, address: mailing, auth, taxonomy, entityID: eid(mailing) });
195
+ } // address variation
196
+ }
197
+ }
198
+ }
199
+ // Corpus-wide address-frequency table — the inverse-frequency signal (#617 fix per the DeepSeek consult).
200
+ const addressFrequency = {
201
+ total: addrTotal,
202
+ distinct: addrCounts.size,
203
+ frequency: (v) => (v ? (addrCounts.get(addressFrequencyKey(v)) ?? 0) / addrTotal : 0),
204
+ };
205
+ report?.(` ${kept.size} NPIs → ${rows.length} records; address table: ${addrCounts.size} distinct over ${addrTotal} rows`);
206
+ // --- Phase C: geocode + ingest (the NPI rides on record.id as the held-out label). The heavy
207
+ // geocoder is injected (see ./eval-geocoder.ts); model-swap for a multi-version curve rides the
208
+ // command's factory config (--model/--tokenizer/--model-card; modelCardPath is MANDATORY when
209
+ // modelPath is set — without it a STAGE3 model silently mis-decodes into empty parses). ---
210
+ report?.("[C] building the geocoder + geocoding records…");
211
+ const mapping = {
212
+ id: "npi",
213
+ name: "name",
214
+ organization: "org",
215
+ address: "address",
216
+ // `entityTruth` rides as an attribute purely for scoring (NOT a discriminator → never used in
217
+ // matching); it carries the site-level entity-level label alongside the NPI (record.id).
218
+ attributes: { authorizedOfficial: "auth", taxonomy: "taxonomy", entityTruth: "entityID" },
219
+ source: "nppes",
220
+ };
221
+ let geo = 0;
222
+ let records;
223
+ if (PARALLEL_GEOCODE) {
224
+ // Threaded geocode: normalize on the main thread, then hand records to a worker pool that each rebuild the
225
+ // classifier/resolver/shards from config. `address` is a single pre-joined column here, so `--legacy-join`
226
+ // (a separator toggle) is a no-op for this path; `normalizeCase` follows the worker default (on).
227
+ if (!options.geocodeStream) {
228
+ throw new Error("parallelGeocode requires the injected geocodeStream (see ./eval-geocoder.ts)");
229
+ }
230
+ const normalized = await ingestRows(rows, mapping);
231
+ const order = new Map(normalized.map((r, i) => [r.id, i]));
232
+ const geocoded = [];
233
+ for await (const rec of options.geocodeStream(normalized, { mapping, concurrency: GEO_CONC })) {
234
+ geocoded.push(rec);
235
+ if (rec.address?.geocode) {
236
+ geo++;
237
+ }
238
+ }
239
+ // geocodeStream yields in completion order; restore input order so downstream cluster tie-breaks are byte-stable.
240
+ geocoded.sort((a, b) => (order.get(a.id) ?? 0) - (order.get(b.id) ?? 0));
241
+ records = geocoded;
242
+ }
243
+ else {
244
+ const geocoder = await options.createGeocoder({ normalizeCase: !LEGACY });
245
+ // Count placements at the seam (parity with the retired in-script counter).
246
+ const countedSeam = async (raw) => {
247
+ const g = await geocoder.seam(raw);
248
+ if (g?.geocode) {
249
+ geo++;
250
+ }
251
+ return g;
252
+ };
253
+ records = await ingestRows(rows, mapping, {
254
+ geocodeAddress: countedSeam,
255
+ addressSeparator: LEGACY ? " " : ", ",
256
+ });
257
+ geocoder.close();
258
+ }
259
+ report?.(` geocoded ${geo}/${rows.length} (${((100 * geo) / rows.length).toFixed(1)}%)`);
260
+ // --- Phase E: score recovered clusters vs the NPI grouping (record.id = the held-out NPI). ---
261
+ const choose2 = (n) => (n * (n - 1)) / 2;
262
+ const N = records.length;
263
+ function scoreEntities(entities, labelOf) {
264
+ const npiTotals = new Map();
265
+ const npiClusters = new Map();
266
+ let sumCK = 0; // Σ C(n_ck, 2)
267
+ let sumCluster = 0; // Σ_c C(|c|, 2)
268
+ let singletons = 0;
269
+ let overMergedClusters = 0;
270
+ let recordsInOverMerged = 0;
271
+ let maxNpisFused = 0;
272
+ entities.forEach((e, ci) => {
273
+ const byNPI = new Map();
274
+ for (const rec of e.records) {
275
+ const lbl = labelOf(rec);
276
+ byNPI.set(lbl, (byNPI.get(lbl) ?? 0) + 1);
277
+ }
278
+ sumCluster += choose2(e.records.length);
279
+ if (e.records.length === 1) {
280
+ singletons++;
281
+ }
282
+ if (byNPI.size > 1) {
283
+ overMergedClusters++;
284
+ recordsInOverMerged += e.records.length;
285
+ maxNpisFused = Math.max(maxNpisFused, byNPI.size);
286
+ }
287
+ for (const [npi, n] of byNPI) {
288
+ sumCK += choose2(n);
289
+ npiTotals.set(npi, (npiTotals.get(npi) ?? 0) + n);
290
+ }
291
+ for (const rec of e.records) {
292
+ const lbl = labelOf(rec);
293
+ const s = npiClusters.get(lbl) ?? new Set();
294
+ s.add(ci);
295
+ npiClusters.set(lbl, s);
296
+ }
297
+ });
298
+ let sumClass = 0;
299
+ // Σ_k C(|k|, 2)
300
+ for (const total of npiTotals.values()) {
301
+ sumClass += choose2(total);
302
+ }
303
+ const tp = sumCK;
304
+ const precision = tp + (sumCluster - tp) > 0 ? tp / sumCluster : 0;
305
+ const recall = sumClass > 0 ? tp / sumClass : 0;
306
+ const f1 = precision + recall > 0 ? (2 * precision * recall) / (precision + recall) : 0;
307
+ const expected = (sumCluster * sumClass) / choose2(N);
308
+ const maxIndex = (sumCluster + sumClass) / 2;
309
+ const ari = maxIndex - expected !== 0 ? (tp - expected) / (maxIndex - expected) : 1;
310
+ const splitNpis = [...npiClusters.values()].filter((s) => s.size > 1).length;
311
+ return {
312
+ precision,
313
+ recall,
314
+ f1,
315
+ ari,
316
+ clusters: entities.length,
317
+ singletons,
318
+ overMergedClusters,
319
+ recordsInOverMerged,
320
+ maxNpisFused,
321
+ splitNpis,
322
+ };
323
+ }
324
+ // Truth labels: NPI-level (the conservative held-out NPI = record.id) and entity-level (the
325
+ // site-level subpart-collapsed id that rides on attributes.entityTruth). Scoring the SAME clusters
326
+ // both ways isolates how much of the apparent over-merge is NPI over-segmentation, not model error.
327
+ const npiLabel = (rec) => rec.id;
328
+ const entityLabel = (rec) => rec.attributes?.["entityTruth"] ?? rec.id;
329
+ // --- ORG-NAME entity-truth (the gold-set lever, #625). Union-find over NPIs: same NPI ⇒ same entity
330
+ // (so an NPI's records stay together — recall preserved), PLUS union two NPIs at the same address whose
331
+ // primary org names match (Jaccard ≥ ORG_TAU). This collapses the same-org-many-NPIs over-segmentation
332
+ // the gold set proved is correct, WITHOUT the subpart flag (which the gold set showed misses 37%). ---
333
+ const parent = new Map();
334
+ const find = (x) => {
335
+ if (!parent.has(x)) {
336
+ parent.set(x, x);
337
+ }
338
+ let root = x;
339
+ while (parent.get(root) !== root) {
340
+ root = parent.get(root);
341
+ }
342
+ while (parent.get(x) !== root) {
343
+ const next = parent.get(x);
344
+ parent.set(x, root);
345
+ x = next;
346
+ }
347
+ return root;
348
+ };
349
+ const union = (a, b) => {
350
+ const ra = find(a);
351
+ const rb = find(b);
352
+ if (ra !== rb) {
353
+ parent.set(ra, rb);
354
+ }
355
+ };
356
+ {
357
+ const byAddr = new Map();
358
+ for (const [npi, info] of npiPrimary) {
359
+ find(npi);
360
+ // seed
361
+ if (!info.addrKey)
362
+ continue;
363
+ if (!byAddr.has(info.addrKey)) {
364
+ byAddr.set(info.addrKey, []);
365
+ }
366
+ byAddr.get(info.addrKey).push(npi);
367
+ }
368
+ for (const group of byAddr.values()) {
369
+ for (let i = 0; i < group.length; i++) {
370
+ for (let j = i + 1; j < group.length; j++) {
371
+ if (orgJaccard(npiPrimary.get(group[i]).tokens, npiPrimary.get(group[j]).tokens) >= ORG_TAU) {
372
+ union(group[i], group[j]);
373
+ }
374
+ }
375
+ }
376
+ }
377
+ }
378
+ const orgNameLabel = (rec) => (npiPrimary.has(rec.id) ? find(rec.id) : rec.id);
379
+ // --- ORG-NAME-COORD entity-truth (Tier 2D, #625). The string org-name truth above blocks by the
380
+ // address STRING (`addressFrequencyKey`), so it MISSES same-building pairs whose text differs —
381
+ // "1504 Taub LOOP" vs "1504 Taub LP STE 100" key apart even though the geocoder places them at one
382
+ // point. This variant blocks by the GEOCODED BUILDING instead: union two NPIs whose org names match
383
+ // (Jaccard ≥ ORG_TAU) AND whose primary practice coordinates are within the same-building distance
384
+ // (≤ 50 m haversine, the DEFAULT_DISTANCE_LEVELS grain). Brute-force pairwise over the ~1000 sampled
385
+ // NPIs (trivial); a tighter LOWER bound on the org-name truth — the org-name F1 here is ≥ the string
386
+ // one. The Jaccard gate still prevents collapsing distinct co-located orgs (the gold-set safety). ---
387
+ const COLOCATION_KM = 0.05;
388
+ const npiCoord = new Map();
389
+ for (const rec of records) {
390
+ const c = rec.address?.geocode?.coordinate;
391
+ // first geocoded record per NPI ≈ its primary practice address (primary row is pushed first)
392
+ if (c && !npiCoord.has(rec.id)) {
393
+ npiCoord.set(rec.id, c);
394
+ }
395
+ }
396
+ const parentC = new Map();
397
+ const findC = (x) => {
398
+ if (!parentC.has(x)) {
399
+ parentC.set(x, x);
400
+ }
401
+ let root = x;
402
+ while (parentC.get(root) !== root) {
403
+ root = parentC.get(root);
404
+ }
405
+ while (parentC.get(x) !== root) {
406
+ const next = parentC.get(x);
407
+ parentC.set(x, root);
408
+ x = next;
409
+ }
410
+ return root;
411
+ };
412
+ const unionC = (a, b) => {
413
+ const ra = findC(a);
414
+ const rb = findC(b);
415
+ if (ra !== rb) {
416
+ parentC.set(ra, rb);
417
+ }
418
+ };
419
+ {
420
+ const coLocated = [...npiPrimary.keys()].filter((n) => npiCoord.has(n));
421
+ for (const n of npiPrimary.keys()) {
422
+ findC(n);
423
+ }
424
+ // seed every NPI (un-geocoded ones stay singletons)
425
+ for (let i = 0; i < coLocated.length; i++) {
426
+ for (let j = i + 1; j < coLocated.length; j++) {
427
+ const a = coLocated[i];
428
+ const b = coLocated[j];
429
+ if (haversineKm(npiCoord.get(a), npiCoord.get(b)) > COLOCATION_KM)
430
+ continue;
431
+ if (orgJaccard(npiPrimary.get(a).tokens, npiPrimary.get(b).tokens) >= ORG_TAU) {
432
+ unionC(a, b);
433
+ }
434
+ }
435
+ }
436
+ }
437
+ const geocodedNpis = [...npiPrimary.keys()].filter((n) => npiCoord.has(n)).length;
438
+ const orgNameCoordLabel = (rec) => (npiPrimary.has(rec.id) ? findC(rec.id) : rec.id);
439
+ // --- ORG-NAME-H3 entity-truth (Task 4, #109). The same building-grain co-location, but keyed on an
440
+ // H3 CELL (the geocode-first "cell" the issue suggested) instead of a pairwise 50 m haversine: assign
441
+ // each NPI's coordinate to an H3 cell at building-block resolution, then union same-org (Jaccard ≥
442
+ // ORG_TAU) NPIs that share a cell. A robustness check on the haversine coord-grain — if the F1
443
+ // matches, the number isn't an artifact of the 50 m threshold, and cell-blocking is O(n) not O(n²).
444
+ // Caveat: a hard cell boundary can split a same-building pair into adjacent cells (a slight
445
+ // under-count vs the radius); res 10 (~65 m edge) absorbs most of it. ---
446
+ const H3_RES = options.h3Res ?? 11; // res 11 ≈ 25 m edge; res 10 ≈ 65 m (block scale)
447
+ const parentH = new Map();
448
+ const findH = (x) => {
449
+ if (!parentH.has(x)) {
450
+ parentH.set(x, x);
451
+ }
452
+ let root = x;
453
+ while (parentH.get(root) !== root) {
454
+ root = parentH.get(root);
455
+ }
456
+ while (parentH.get(x) !== root) {
457
+ const next = parentH.get(x);
458
+ parentH.set(x, root);
459
+ x = next;
460
+ }
461
+ return root;
462
+ };
463
+ const unionH = (a, b) => {
464
+ const ra = findH(a);
465
+ const rb = findH(b);
466
+ if (ra !== rb) {
467
+ parentH.set(ra, rb);
468
+ }
469
+ };
470
+ {
471
+ const byCell = new Map();
472
+ for (const n of npiPrimary.keys()) {
473
+ findH(n); // seed every NPI (un-geocoded ones stay singletons)
474
+ const c = npiCoord.get(n);
475
+ if (!c)
476
+ continue;
477
+ const cell = latLngToCell(c.latitude, c.longitude, H3_RES);
478
+ if (!byCell.has(cell)) {
479
+ byCell.set(cell, []);
480
+ }
481
+ byCell.get(cell).push(n);
482
+ }
483
+ for (const group of byCell.values()) {
484
+ for (let i = 0; i < group.length; i++) {
485
+ for (let j = i + 1; j < group.length; j++) {
486
+ if (orgJaccard(npiPrimary.get(group[i]).tokens, npiPrimary.get(group[j]).tokens) >= ORG_TAU) {
487
+ unionH(group[i], group[j]);
488
+ }
489
+ }
490
+ }
491
+ }
492
+ }
493
+ const orgNameH3Label = (rec) => (npiPrimary.has(rec.id) ? findH(rec.id) : rec.id);
494
+ // --- Phase D: the comparison-model lever progression — toggle each lever ON in turn at the default
495
+ // threshold to isolate its marginal effect, then sweep the link threshold on the best config (geocode
496
+ // once, resolve many — config is cheap). ---
497
+ report?.(`[D] resolving the lever progression${TRAIN_EM ? " (EM-trained)" : ""}…`);
498
+ // The proven levers are now DEFAULT-ON in resolveEntities (#86). Each row sets BOTH `collapseSpatial`
499
+ // and `addressFrequency` EXPLICITLY so the progression isolates one lever at a time — otherwise the
500
+ // flipped default (collapseSpatial:true) would silently ride the `+ inverse-address-frequency` row and
501
+ // the A1 delta would read as 0. Every row feeds the corpus-wide frequency table (the realistic
502
+ // deployment, where the CLI builds it from the full source files); the zero-config `{}` default is
503
+ // reported SEPARATELY below, since on a sub-sample its input-scoped table is intentionally sparse.
504
+ const LEVERS = [
505
+ {
506
+ label: "baseline (legacy: address-key + distance, levers OFF)",
507
+ config: { collapseSpatial: false, addressFrequency: false },
508
+ },
509
+ { label: "+ inverse-address-frequency (#617, corpus-wide)", config: { collapseSpatial: false, addressFrequency } },
510
+ { label: "+ collapsed spatial signal (A1, #625)", config: { collapseSpatial: true, addressFrequency } },
511
+ {
512
+ label: "+ authorized-official discriminator (#625)",
513
+ config: { collapseSpatial: true, addressFrequency, discriminators: ["authorizedOfficial"] },
514
+ },
515
+ // A2–A4 (#625): the built-but-unmeasured over-merge levers. Each builds on the A1 + discriminator
516
+ // stack so the marginal effect is isolated. A2 (require name/org corroboration) is the direct
517
+ // over-merge precision lever; A3 (phone) is the recall-tail corroborator that should keep A2 from
518
+ // killing name-drift links; A4 (average-linkage) splits a component joined only by a weak bridge.
519
+ {
520
+ label: "+ require name/org corroboration (A2, #625)",
521
+ config: {
522
+ collapseSpatial: true,
523
+ addressFrequency,
524
+ discriminators: ["authorizedOfficial"],
525
+ requireCorroboration: true,
526
+ },
527
+ },
528
+ {
529
+ label: "+ phone comparison (A3, #625)",
530
+ config: {
531
+ collapseSpatial: true,
532
+ addressFrequency,
533
+ discriminators: ["authorizedOfficial"],
534
+ requireCorroboration: true,
535
+ usePhone: true,
536
+ },
537
+ },
538
+ {
539
+ label: "+ average-linkage clustering (A4, #625, full A1–A4 stack)",
540
+ config: {
541
+ collapseSpatial: true,
542
+ addressFrequency,
543
+ discriminators: ["authorizedOfficial"],
544
+ requireCorroboration: true,
545
+ usePhone: true,
546
+ linkage: "average",
547
+ },
548
+ },
549
+ // A5 (#625): the taxonomy code-set discriminator — set-overlap agreement over the NPI's 15 taxonomy
550
+ // slots. The named "still-more-distinctive identifier" from the 2026-06-16 report: co-located
551
+ // DISTINCT providers usually have disjoint sets (the over-merge separator) while an entity's own
552
+ // records always share theirs (never splits). Stacked on the BEST prior classical config (A1 +
553
+ // authorized-official; A3 phone + A4 avg-linkage were measured neutral-to-negative and are left off).
554
+ {
555
+ label: "+ taxonomy code-set discriminator (A5, #625)",
556
+ config: {
557
+ collapseSpatial: true,
558
+ addressFrequency,
559
+ discriminators: ["authorizedOfficial"],
560
+ exactDiscriminators: ["taxonomy"],
561
+ },
562
+ },
563
+ ];
564
+ // learnedScorer:false throughout — this benchmark studies the FS COMPARISON-MODEL levers (#617/#625).
565
+ // The learned scorer is now default-on, so it must be pinned off here or every row would silently be the
566
+ // GBT; the learned scorer is measured separately (learned-scorer-clustering-eval / -crossstate-eval).
567
+ const progression = LEVERS.map((l) => {
568
+ const res = resolveEntities(records, { learnedScorer: false, trainEM: TRAIN_EM, threshold: 0, ...l.config });
569
+ return { ...l, res, score: scoreEntities(res.entities, npiLabel) };
570
+ });
571
+ const baseline = progression[0]; // no levers — the prior-prior behaviour
572
+ const bestLever = progression[progression.length - 1]; // the full lever stack
573
+ // The SHIPPED out-of-box default (#86): no lever config at all → resolveEntities auto-computes an
574
+ // input-scoped address-frequency table + collapsed spatial. On this deliberately-sub-sampled corpus the
575
+ // auto table is sparse (few repeats), so the inverse-frequency signal is near-inert and F1 collapses to
576
+ // ≈baseline — NOT a regression, just the honest truth that IDF is a corpus statistic you can't synthesize
577
+ // from a slice. On a FULL-dataset dedup the input IS the corpus and this default reaches the baseline; the
578
+ // CLI passes a corpus-wide table built from the full source files so even a geocoded sub-sample benefits.
579
+ const defaultOutOfBox = (() => {
580
+ const res = resolveEntities(records, { learnedScorer: false, trainEM: TRAIN_EM, threshold: 0 });
581
+ return { res, score: scoreEntities(res.entities, npiLabel) };
582
+ })();
583
+ const THRESHOLDS = [0, 4, 8, 12, 16, 20];
584
+ const sweep = THRESHOLDS.map((t) => {
585
+ const res = resolveEntities(records, { learnedScorer: false, trainEM: TRAIN_EM, threshold: t, ...bestLever.config });
586
+ return { t, res, score: scoreEntities(res.entities, npiLabel) };
587
+ });
588
+ const base = sweep[0]; // threshold 0, full lever stack
589
+ const best = sweep.reduce((a, b) => (b.score.f1 > a.score.f1 ? b : a));
590
+ report?.(` progression @ threshold 0: ${progression.map((p) => `${(100 * p.score.f1).toFixed(1)}%`).join(" → ")} F1`);
591
+ report?.(` default F1 ${(100 * base.score.f1).toFixed(1)}% → best F1 ${(100 * best.score.f1).toFixed(1)}% @ threshold ${best.t}`);
592
+ // --- Phase F: NPI-level vs ENTITY-level truth. Score the SAME clusters against both yardsticks to
593
+ // reveal how much of the apparent over-merge is NPI over-segmentation (one org / many subpart-NPIs,
594
+ // where merging is CORRECT) rather than model error. Two production configs: the FS full lever stack
595
+ // and the shipped default (GBT, default-on) — each fed the corpus-wide address-frequency table. ---
596
+ const entityCount = new Set(records.map((r) => entityLabel(r))).size;
597
+ const orgCount = new Set(records.map((r) => orgNameLabel(r))).size;
598
+ const fsNPI = bestLever.score;
599
+ const fsEntity = scoreEntities(bestLever.res.entities, entityLabel);
600
+ const fsOrg = scoreEntities(bestLever.res.entities, orgNameLabel);
601
+ const gbtRes = resolveEntities(records, { addressFrequency, trainEM: TRAIN_EM }); // GBT default-on (production)
602
+ const gbtNPI = scoreEntities(gbtRes.entities, npiLabel);
603
+ const gbtEntity = scoreEntities(gbtRes.entities, entityLabel);
604
+ const gbtOrg = scoreEntities(gbtRes.entities, orgNameLabel);
605
+ // Tier 2D: the coordinate-co-location org-name truth (tighter lower bound).
606
+ const orgCoordCount = new Set(records.map((r) => orgNameCoordLabel(r))).size;
607
+ const fsOrgCoord = scoreEntities(bestLever.res.entities, orgNameCoordLabel);
608
+ const gbtOrgCoord = scoreEntities(gbtRes.entities, orgNameCoordLabel);
609
+ // Task 4 (#109): the H3-cell co-location truth — a robustness check on the haversine coord-grain.
610
+ const orgH3Count = new Set(records.map((r) => orgNameH3Label(r))).size;
611
+ const gbtOrgH3 = scoreEntities(gbtRes.entities, orgNameH3Label);
612
+ // --- #625 gold-set adjudication packet (--dump-overmerges <path>): the org-name-grain over-merged
613
+ // clusters from the SHIPPED (GBT) config, with full member records, formatted for HUMAN review. The
614
+ // residual over-merge is small (~21 clusters) and approaching the measured ~1.6% irreducible ceiling —
615
+ // per-pair adjudication (same entity? distinct co-located?) is the only instrument left that can
616
+ // separate model error from yardstick error. Each cluster prints its members grouped by org-name
617
+ // label with every matcher-visible field, so a reviewer can adjudicate in one glance.
618
+ const DUMP_OVERMERGES = options.dumpOvermerges || "";
619
+ if (DUMP_OVERMERGES) {
620
+ const rowByID = new Map(rows.map((r) => [r.npi, r]));
621
+ const out = [
622
+ "# #625 gold-set adjudication packet — org-name-grain over-merged clusters (GBT, shipped config)",
623
+ "",
624
+ `TX --max-npis ${MAX_NPIS} · ${records.length} records · generated by \`registry scorer-eval nppes-benchmark --dump-overmerges\``,
625
+ "",
626
+ "For each cluster: the matcher fused records that the org-name truth says belong to DIFFERENT entities.",
627
+ "Adjudicate each: **[same]** one real-world entity (yardstick error — the truth under-collapsed) or",
628
+ "**[distinct]** genuinely different co-located providers (model over-merge). Mark inline and return.",
629
+ "",
630
+ ];
631
+ let n = 0;
632
+ gbtRes.entities.forEach((e) => {
633
+ const byLabel = new Map();
634
+ for (const rec of e.records) {
635
+ const lbl = orgNameLabel(rec);
636
+ const list = byLabel.get(lbl) ?? [];
637
+ list.push(rec);
638
+ byLabel.set(lbl, list);
639
+ }
640
+ if (byLabel.size <= 1)
641
+ return;
642
+ n++;
643
+ out.push(`## Cluster ${n} — ${e.records.length} records, ${byLabel.size} org-name entities → verdict: [ ]`);
644
+ for (const [lbl, members] of byLabel) {
645
+ out.push(`- **entity ${lbl}**`);
646
+ for (const rec of members) {
647
+ const src = rowByID.get(rec.id);
648
+ out.push(` - npi=${rec.id} · name="${[rec.name?.given, rec.name?.family].filter(Boolean).join(" ")}" · org="${rec.organization?.canonical ?? ""}" · addr="${rec.address?.raw ?? ""}" · auth="${src?.auth ?? ""}" · taxonomy="${src?.taxonomy ?? ""}"`);
649
+ }
650
+ }
651
+ out.push("");
652
+ });
653
+ writeFileSync(DUMP_OVERMERGES, out.join("\n"));
654
+ report?.(` adjudication packet: ${n} over-merged clusters -> ${DUMP_OVERMERGES}`);
655
+ }
656
+ // Optional candidate A/B (--candidate): score a trained GBT module at both levels, at its own
657
+ // recommendedThreshold, alongside the shipped GBT — grades a new model (e.g. corroboration features).
658
+ let cand = null;
659
+ if (CANDIDATE) {
660
+ const mod = (await import(__rewriteRelativeImportExtension(pathToFileURL(resolvePath(CANDIDATE)).href)));
661
+ const t = mod.DEDUP_GBT_META?.recommendedThreshold ?? 0;
662
+ const res = resolveEntities(records, {
663
+ addressFrequency,
664
+ trainEM: TRAIN_EM,
665
+ learnedScorer: mod.DEDUP_GBT_MODEL,
666
+ threshold: t,
667
+ });
668
+ const cost = mod.DEDUP_GBT_META?.costNegative ?? 1;
669
+ cand = {
670
+ label: `GBT candidate (${mod.DEDUP_GBT_META?.features ?? "?"}-feat${cost !== 1 ? `, cost ×${cost}` : ""})`,
671
+ npi: scoreEntities(res.entities, npiLabel),
672
+ entity: scoreEntities(res.entities, entityLabel),
673
+ };
674
+ report?.(` candidate ${CANDIDATE}: NPI ${(100 * cand.npi.f1).toFixed(1)}% / entity ${(100 * cand.entity.f1).toFixed(1)}%`);
675
+ }
676
+ report?.(` truth-grains — GBT NPI ${(100 * gbtNPI.f1).toFixed(1)}% → site ${(100 * gbtEntity.f1).toFixed(1)}% → org-name ${(100 * gbtOrg.f1).toFixed(1)}% → org-name-coord ${(100 * gbtOrgCoord.f1).toFixed(1)}% → org-name-h3 ${(100 * gbtOrgH3.f1).toFixed(1)}% (res ${H3_RES}); ` +
677
+ `FS: NPI ${(100 * fsNPI.f1).toFixed(1)}% / entity ${(100 * fsEntity.f1).toFixed(1)}% / org-coord ${(100 * fsOrgCoord.f1).toFixed(1)}%`);
678
+ // NOTE(phase4): local pct keeps the fraction-in/no-%-suffix shape — not core formatPercent's
679
+ // numerator/denominator contract (call sites append their own "%").
680
+ const pct = (x) => (100 * x).toFixed(1);
681
+ const signed = (x) => `${x >= 0 ? "+" : ""}${x.toFixed(1)}pp`;
682
+ const lines = [];
683
+ lines.push(`# NPPES NPI dedup benchmark (#617)`);
684
+ lines.push("");
685
+ lines.push(`_Generated by \`mailwoman registry scorer-eval nppes-benchmark\`. Sample: ${kept.size} ${STATE} NPIs with ≥1 ` +
686
+ `alternate name → ${N} records (${(N / kept.size).toFixed(1)}/NPI) from real registry + other-names + ` +
687
+ `mailing-vs-practice variation. Matcher run BLIND to the NPI${TRAIN_EM ? ", EM-trained (label-free)" : ""}; ` +
688
+ `geocoded ${pct(geo / N)}% of addresses. The NPI is held-out ground truth._`);
689
+ lines.push("");
690
+ lines.push(`**Headline — org-name truth (the honest grain):** the shipped ` +
691
+ `matcher resolves these records at **F1 ${pct(gbtOrg.f1)}%** against org-name entity-truth — not the NPI-level ` +
692
+ `${pct(gbtNPI.f1)}%, which mostly measures NPI over-segmentation (one organization holds many subpart NPIs, so ` +
693
+ `correct co-located merges are scored as errors). Same clusters, three rulers: ` +
694
+ `**NPI ${pct(gbtNPI.f1)}% → site ${pct(gbtEntity.f1)}% → org-name ${pct(gbtOrg.f1)}%** ` +
695
+ `(${kept.size} NPI → ${entityCount} site → ${orgCount} org-name classes); the climb is the yardstick getting honest, ` +
696
+ `not the model changing — gold-set validated (120/120 hard pairs = same org). Details in "Three truth grains" below.`);
697
+ lines.push("");
698
+ lines.push(`## The comparison-model levers (each toggled on, at the default threshold)`);
699
+ lines.push("");
700
+ lines.push(`| model | precision | recall | F1 | ΔF1 | ARI | over-merged |`);
701
+ lines.push(`|---|---:|---:|---:|---:|---:|---:|`);
702
+ progression.forEach((p, i) => {
703
+ const delta = i === 0 ? "—" : signed(100 * (p.score.f1 - progression[i - 1].score.f1));
704
+ const bold = i === progression.length - 1;
705
+ const w = (s) => (bold ? `**${s}**` : s);
706
+ lines.push(`| ${w(p.label)} | ${w(pct(p.score.precision) + "%")} | ${w(pct(p.score.recall) + "%")} | ${w(pct(p.score.f1) + "%")} | ${delta} | ${w(p.score.ari.toFixed(3))} | ${w(String(p.score.overMergedClusters))} |`);
707
+ });
708
+ lines.push("");
709
+ lines.push(`Inverse-frequency weighting uses the corpus-wide table (${addrCounts.size.toLocaleString()} distinct addresses ` +
710
+ `over ${addrTotal.toLocaleString()} providers) to down-weight a crowded shared address; collapsing the redundant ` +
711
+ `address-key + distance comparisons into one spatial signal (A1) removes the double-count that let a shared address ` +
712
+ `over-vote a disagreeing name. The address-frequency + A1 baseline is F1 ${pct(progression[2].score.f1)}% at the ` +
713
+ `default threshold; the **authorized-official discriminator** is roughly neutral there (${signed(100 * (bestLever.score.f1 - progression[2].score.f1))}) ` +
714
+ `but enables a higher cutoff — it holds recall where the baseline alone collapses, reaching **${pct(best.score.f1)}%** at ` +
715
+ `threshold ${best.t} (below), the first config past the baseline (#625).`);
716
+ lines.push("");
717
+ lines.push(`**Out-of-the-box (zero-config \`resolveEntities(records)\`, levers default-on #86):** F1 ` +
718
+ `**${pct(defaultOutOfBox.score.f1)}%** on this sample — essentially the baseline. The default auto-computes the ` +
719
+ `address-frequency table over the INPUT records, and this benchmark deliberately sub-samples ${N} records, so ` +
720
+ `that table is too sparse to carry the inverse-frequency signal (a corpus statistic you can't synthesize from a ` +
721
+ `slice). It's **not a regression** (≥ baseline, no over-merge added) — it's the honest floor when the input isn't ` +
722
+ `corpus-scale. Fed the corpus-wide table (the \`+ inverse-address-frequency\` row above, what the CLI builds from ` +
723
+ `the full source files) the SAME default reaches the **${pct(progression[2].score.f1)}%** baseline. On a full-dataset ` +
724
+ `dedup the input IS the corpus, so zero-config reaches the baseline on its own.`);
725
+ lines.push("");
726
+ lines.push(`## With all levers on, across the link threshold (the secondary lever)`);
727
+ lines.push("");
728
+ lines.push(`| link threshold (bits) | precision | recall | F1 | ARI | clusters | over-merged |`);
729
+ lines.push(`|---:|---:|---:|---:|---:|---:|---:|`);
730
+ for (const s of sweep) {
731
+ const star = s === best ? " ⭐" : "";
732
+ lines.push(`| ${s.t}${s.t === 0 ? " (default)" : ""} | ${pct(s.score.precision)}% | ${pct(s.score.recall)}% | **${pct(s.score.f1)}%**${star} | ${s.score.ari.toFixed(3)} | ${s.score.clusters} | ${s.score.overMergedClusters} |`);
733
+ }
734
+ lines.push("");
735
+ lines.push(best.t === 0
736
+ ? `Best F1 is at the **default threshold** (${pct(base.score.f1)}%): raising it only trades recall away faster ` +
737
+ `than it buys precision. So the threshold knob alone can't separate co-located distinct providers — the ` +
738
+ `over-merge is structural, in the comparison model, not the cutoff.`
739
+ : `Best F1 **${pct(best.score.f1)}%** (ARI ${best.score.ari.toFixed(3)}) at threshold ${best.t}, vs **${pct(base.score.f1)}%** at the ` +
740
+ `default — the threshold knob moves it ${(100 * (best.score.f1 - base.score.f1)).toFixed(0)}pp. Higher thresholds trade recall for precision.`);
741
+ lines.push("");
742
+ lines.push(`## Shape + where the errors are (at the default threshold)`);
743
+ lines.push("");
744
+ lines.push(`- records: ${N} · true entities (NPIs): ${kept.size} · recovered clusters: ${base.score.clusters}`);
745
+ lines.push(`- candidate pairs blocked: ${base.res.candidatePairs}${base.res.droppedBlocks.length ? ` · oversized blocks skipped: ${base.res.droppedBlocks.length}` : ""}`);
746
+ lines.push(`- **Over-merge (precision):** ${base.score.overMergedClusters} clusters fuse ≥2 distinct NPIs (largest fuses ` +
747
+ `${base.score.maxNpisFused}; ${base.score.recordsInOverMerged} records) — **co-located providers sharing a clinic / ` +
748
+ `billing address**, linked by address agreement despite different names.`);
749
+ lines.push(`- **Under-merge (recall):** ${base.score.splitNpis}/${kept.size} NPIs split across >1 cluster — records at distant ` +
750
+ `addresses (mailing vs practice) or with strong name drift the score didn't bridge.`);
751
+ lines.push("");
752
+ lines.push(`## Three truth grains — NPI → site → org-name (the over-segmentation correction)`);
753
+ lines.push("");
754
+ lines.push(`NPI-as-truth OVER-SEGMENTS: one org holds many NPIs, so the matcher's correct co-located merges are scored as ` +
755
+ `errors. Three yardsticks, same clusters: **NPI** (one entity per registration), **site** (subpart-flagged ` +
756
+ `collapse + split an NPI's distinct addresses), and **org-name** — the gold-set-validated truth: same NPI ⇒ ` +
757
+ `same entity (recall preserved) PLUS collapse co-located NPIs whose primary org names match (Jaccard ≥ ${ORG_TAU}), ` +
758
+ `with NO reliance on the subpart flag (the gold set showed it misses 37%). The same ${N} records carry ` +
759
+ `**${kept.size} NPI** → **${entityCount} site** → **${orgCount} org-name** classes. The org-name number is the ` +
760
+ `honest one: it stops charging the matcher for the same-org merges the gold set proved are correct.`);
761
+ lines.push("");
762
+ lines.push(`| config | truth | precision | recall | F1 | ΔF1 vs NPI | ARI | over-merged |`);
763
+ lines.push(`|---|---|---:|---:|---:|---:|---:|---:|`);
764
+ const dualRow = (label, truth, s, delta) => lines.push(`| ${label} | ${truth} | ${pct(s.precision)}% | ${pct(s.recall)}% | **${pct(s.f1)}%** | ${delta === undefined ? "—" : signed(100 * delta)} | ${s.ari.toFixed(3)} | ${s.overMergedClusters} |`);
765
+ dualRow("FS full stack", "NPI", fsNPI);
766
+ dualRow("FS full stack", "site", fsEntity, fsEntity.f1 - fsNPI.f1);
767
+ dualRow("FS full stack", "**org-name**", fsOrg, fsOrg.f1 - fsNPI.f1);
768
+ dualRow("FS full stack", "org-name (coord)", fsOrgCoord, fsOrgCoord.f1 - fsNPI.f1);
769
+ dualRow("GBT (shipped default)", "NPI", gbtNPI);
770
+ dualRow("GBT (shipped default)", "site", gbtEntity, gbtEntity.f1 - gbtNPI.f1);
771
+ dualRow("GBT (shipped default)", "**org-name**", gbtOrg, gbtOrg.f1 - gbtNPI.f1);
772
+ dualRow("GBT (shipped default)", "**org-name (coord)**", gbtOrgCoord, gbtOrgCoord.f1 - gbtNPI.f1);
773
+ dualRow("GBT (shipped default)", `org-name (H3 res ${H3_RES})`, gbtOrgH3, gbtOrgH3.f1 - gbtNPI.f1);
774
+ if (cand) {
775
+ dualRow(cand.label, "NPI", cand.npi);
776
+ dualRow(cand.label, "**entity**", cand.entity, cand.entity.f1 - cand.npi.f1);
777
+ }
778
+ lines.push("");
779
+ lines.push(`The F1 **climbs as the yardstick gets honest**: GBT **${pct(gbtNPI.f1)}% (NPI) → ${pct(gbtEntity.f1)}% (site) → ` +
780
+ `${pct(gbtOrg.f1)}% (org-name)**, the over-merge collapsing (${gbtNPI.overMergedClusters} → ${gbtOrg.overMergedClusters}) ` +
781
+ `and precision rising (${pct(gbtNPI.precision)}% → ${pct(gbtOrg.precision)}%). The clusters are IDENTICAL across the three ` +
782
+ `columns — the climb is purely the ruler ceasing to charge the matcher for the correct same-org merges the gold set proved ` +
783
+ `(\`2026-06-16-dedup-gold-set-tx120.md\`: 120/120 same org, 0 genuine over-merges).`);
784
+ lines.push("");
785
+ lines.push(`**Tier 2D — tightening the org-name ruler with the geocode coordinate.** The org-name truth above blocks by the address ` +
786
+ `STRING (\`addressFrequencyKey\`), so two records at one building whose text differs — \`1504 Taub LOOP\` vs ` +
787
+ `\`1504 Taub LP STE 100\` — key apart and the merge is still charged as an error. Block by the GEOCODED BUILDING instead ` +
788
+ `(union co-located NPIs within ${COLOCATION_KM * 1000} m whose org names agree, same Jaccard gate) and the truth tightens ` +
789
+ `further: GBT **org-name ${pct(gbtOrg.f1)}% → org-name-coord ${pct(gbtOrgCoord.f1)}%** ` +
790
+ `(${signed(100 * (gbtOrgCoord.f1 - gbtOrg.f1))}), ${orgCount} → ${orgCoordCount} classes, over ${geocodedNpis}/${kept.size} ` +
791
+ `geocoded NPIs. The string org-name F1 is a conservative LOWER bound; the coordinate one is tighter (the Jaccard gate ` +
792
+ `still blocks distinct co-located orgs). Both are honest — the coordinate is the geocode-first key.`);
793
+ lines.push("");
794
+ lines.push(`**Task 4 (#109) — H3-cell robustness check.** Re-keying the same building-grain co-location on an H3 cell ` +
795
+ `(res ${H3_RES}) instead of the 50 m haversine radius — the deterministic, O(n) "geocode-first cell" the issue ` +
796
+ `suggested — gives GBT **org-name-h3 ${pct(gbtOrgH3.f1)}%** (${orgH3Count} classes), vs the haversine ` +
797
+ `${pct(gbtOrgCoord.f1)}% (${orgCoordCount}). ${Math.abs(gbtOrgH3.f1 - gbtOrgCoord.f1) < 0.015
798
+ ? "Within noise of the haversine grain — the ~" +
799
+ pct(gbtOrgCoord.f1) +
800
+ "% coord-grain F1 is robust to the co-location method, not an artifact of the 50 m threshold."
801
+ : "The two co-location methods differ by " +
802
+ signed(100 * (gbtOrgH3.f1 - gbtOrgCoord.f1)) +
803
+ " — the cell-vs-radius boundary handling shifts the count (a hard H3 boundary can split a same-building pair into adjacent cells)."}`);
804
+ lines.push("");
805
+ lines.push(`**Takeaways:** (1) The dedup model's REAL quality is the **org-name F1 ~${pct(gbtOrg.f1)}%**, not the NPI-level ` +
806
+ `${pct(gbtNPI.f1)}% — the difference was NPI over-segmentation, not model error. (2) The #625 lever was the YARDSTICK, ` +
807
+ `not the scorer: the corroboration-feature experiment (reverted) couldn't move precision because the over-merge was ` +
808
+ `mostly correct. (3) The remaining org-name over-merge (${gbtOrg.overMergedClusters} clusters) is the genuine frontier — ` +
809
+ `small, approaching the ceiling's ~1.6% irreducible (\`2026-06-16-dedup-ceiling.md\`). (4) Trust the large eval: a 50-NPI ` +
810
+ `smoke misled on the site delta (+5–7pp vs this run's ±2pp).`);
811
+ lines.push("");
812
+ lines.push(`Caveats: the programmatic site-truth is CONSERVATIVE (collapses only NPPES-flagged subparts; unflagged same-org pairs still ` +
813
+ `read as over-merge), so it understates the subpart correction. A hand-adjudicated gold set on the ambiguous co-located + ` +
814
+ `two-site slice is the next refinement (#625).`);
815
+ lines.push("");
816
+ lines.push(`## Reading`);
817
+ lines.push("");
818
+ lines.push(`The geocode-first **foundation works**: **${pct(geo / N)}%** of addresses placed, blocking + clustering clean — the ` +
819
+ `geocoding (the Pelias/Nominatim-can't-do-this part) is not the bottleneck. The comparison-model levers reach the ` +
820
+ `address-frequency + A1 baseline at F1 **${pct(progression[2].score.f1)}%** (${signed(100 * (progression[2].score.f1 - baseline.score.f1))} over baseline): ` +
821
+ `inverse-frequency weighting restores full weight to a *rare* shared address (stitching a provider's name-drifted ` +
822
+ `records together — mostly recall) while down-weighting a *crowded* one, and the collapsed spatial signal (A1) drops ` +
823
+ `the address+distance double-count. What remains is **precision / over-merge** — ${bestLever.score.overMergedClusters} ` +
824
+ `clusters still fuse distinct co-located providers, because even one down-weighted spatial agreement can outvote a ` +
825
+ `disagreeing name. The lever search (#625) — two negatives, then the first positive: a name/org/phone ` +
826
+ `**corroboration gate** (A2/A3) — phone is an unreliable secondary identifier on NPPES (shared institutional ` +
827
+ `switchboard lines), so it over-links and falsely corroborates co-phone distinct providers; and **average-linkage ` +
828
+ `clustering** (A4) — the over-merged clusters are joined by STRONG shared-address edges, not weak bridges, so ` +
829
+ `average-linkage can't split them and only trades away name-drift recall. The over-merge is a **scoring** problem ` +
830
+ `this data can't resolve, not a clustering-topology one. The **authorized-official discriminator** is the first lever to beat the baseline — a reliable secondary identifier holds recall so a higher threshold separates the co-located providers; a still-more-distinctive identifier ` +
831
+ `(taxonomy / license) or a learned scorer over the FS feature vector (#603) goes further. Config ` +
832
+ `dominates the model (the pre-registered finding) — tracked as #625 / the selective-model work (#602 / #603).`);
833
+ lines.push("");
834
+ lines.push(`NPI-as-truth is **conservative**: a cluster fusing two NPIs is a candidate "same entity, two NPIs" surfaced for ` +
835
+ `review, not an adjudicated error; an NPI split across genuinely-distant addresses is geo-first behaving correctly, ` +
836
+ `counted here as a recall miss. We resolve and report; interpretation is the consumer's.`);
837
+ lines.push("");
838
+ const md = lines.join("\n");
839
+ console.log(md);
840
+ if (OUT_MD) {
841
+ writeFileSync(OUT_MD, md);
842
+ report?.(`\n[written] ${OUT_MD}`);
843
+ }
844
+ return { markdown: md };
845
+ }
846
+ //# sourceMappingURL=nppes-dedup-benchmark.js.map