@mailwoman/registry 9.1.0 → 9.2.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 (149) hide show
  1. package/README.md +1 -1
  2. package/geojson.ts +3 -2
  3. package/ingest.ts +2 -1
  4. package/map-html.ts +4 -4
  5. package/out/geojson.d.ts.map +1 -1
  6. package/out/geojson.js +3 -2
  7. package/out/geojson.js.map +1 -1
  8. package/out/ingest.d.ts.map +1 -1
  9. package/out/ingest.js +2 -1
  10. package/out/ingest.js.map +1 -1
  11. package/out/map-html.d.ts +2 -2
  12. package/out/map-html.d.ts.map +1 -1
  13. package/out/map-html.js.map +1 -1
  14. package/out/reconcile.d.ts.map +1 -1
  15. package/out/reconcile.js +2 -1
  16. package/out/reconcile.js.map +1 -1
  17. package/out/resolve.d.ts.map +1 -1
  18. package/out/resolve.js +4 -1
  19. package/out/resolve.js.map +1 -1
  20. package/out/tools/coverage-reconciliation.js +2 -2
  21. package/out/tools/coverage-reconciliation.js.map +1 -1
  22. package/out/tools/cross-dataset-correlation.d.ts.map +1 -1
  23. package/out/tools/cross-dataset-correlation.js +6 -5
  24. package/out/tools/cross-dataset-correlation.js.map +1 -1
  25. package/out/tools/cross-source-threshold-sweep.js +2 -2
  26. package/out/tools/cross-source-threshold-sweep.js.map +1 -1
  27. package/out/tools/dedup-ceiling.d.ts.map +1 -1
  28. package/out/tools/dedup-ceiling.js +2 -3
  29. package/out/tools/dedup-ceiling.js.map +1 -1
  30. package/out/tools/eval-geocoder.d.ts +1 -1
  31. package/out/tools/eval-geocoder.d.ts.map +1 -1
  32. package/out/tools/geocoder-vs-provided-coords.d.ts.map +1 -1
  33. package/out/tools/geocoder-vs-provided-coords.js +3 -2
  34. package/out/tools/geocoder-vs-provided-coords.js.map +1 -1
  35. package/out/tools/gold-set-sample.d.ts.map +1 -1
  36. package/out/tools/gold-set-sample.js +4 -3
  37. package/out/tools/gold-set-sample.js.map +1 -1
  38. package/out/tools/index.d.ts +1 -6
  39. package/out/tools/index.d.ts.map +1 -1
  40. package/out/tools/index.js +1 -6
  41. package/out/tools/index.js.map +1 -1
  42. package/out/tools/learned-scorer-clustering-eval.d.ts.map +1 -1
  43. package/out/tools/learned-scorer-clustering-eval.js +1 -2
  44. package/out/tools/learned-scorer-clustering-eval.js.map +1 -1
  45. package/out/tools/learned-scorer-crossstate-eval.d.ts.map +1 -1
  46. package/out/tools/learned-scorer-crossstate-eval.js +1 -1
  47. package/out/tools/learned-scorer-crossstate-eval.js.map +1 -1
  48. package/out/tools/learned-scorer-eval.d.ts.map +1 -1
  49. package/out/tools/learned-scorer-eval.js +1 -6
  50. package/out/tools/learned-scorer-eval.js.map +1 -1
  51. package/out/tools/matcher-scale.d.ts.map +1 -1
  52. package/out/tools/matcher-scale.js +1 -1
  53. package/out/tools/matcher-scale.js.map +1 -1
  54. package/out/tools/nppes/levers.d.ts +38 -0
  55. package/out/tools/nppes/levers.d.ts.map +1 -0
  56. package/out/tools/nppes/levers.js +79 -0
  57. package/out/tools/nppes/levers.js.map +1 -0
  58. package/out/tools/nppes/org-name.d.ts +24 -0
  59. package/out/tools/nppes/org-name.d.ts.map +1 -0
  60. package/out/tools/nppes/org-name.js +42 -0
  61. package/out/tools/nppes/org-name.js.map +1 -0
  62. package/out/tools/nppes/overmerge-packet.d.ts +39 -0
  63. package/out/tools/nppes/overmerge-packet.d.ts.map +1 -0
  64. package/out/tools/nppes/overmerge-packet.js +55 -0
  65. package/out/tools/nppes/overmerge-packet.js.map +1 -0
  66. package/out/tools/nppes/report.d.ts +93 -0
  67. package/out/tools/nppes/report.d.ts.map +1 -0
  68. package/out/tools/nppes/report.js +188 -0
  69. package/out/tools/nppes/report.js.map +1 -0
  70. package/out/tools/nppes/sample.d.ts +64 -0
  71. package/out/tools/nppes/sample.d.ts.map +1 -0
  72. package/out/tools/nppes/sample.js +113 -0
  73. package/out/tools/nppes/sample.js.map +1 -0
  74. package/out/tools/nppes/scoring.d.ts +36 -0
  75. package/out/tools/nppes/scoring.d.ts.map +1 -0
  76. package/out/tools/nppes/scoring.js +80 -0
  77. package/out/tools/nppes/scoring.js.map +1 -0
  78. package/out/tools/nppes/truth-grains.d.ts +50 -0
  79. package/out/tools/nppes/truth-grains.d.ts.map +1 -0
  80. package/out/tools/nppes/truth-grains.js +148 -0
  81. package/out/tools/nppes/truth-grains.js.map +1 -0
  82. package/out/tools/nppes-dedup-benchmark.d.ts +4 -0
  83. package/out/tools/nppes-dedup-benchmark.d.ts.map +1 -1
  84. package/out/tools/nppes-dedup-benchmark.js +79 -652
  85. package/out/tools/nppes-dedup-benchmark.js.map +1 -1
  86. package/out/tools/shared.d.ts.map +1 -1
  87. package/out/tools/shared.js +5 -4
  88. package/out/tools/shared.js.map +1 -1
  89. package/out/tools/train-cross-gbt.d.ts.map +1 -1
  90. package/out/tools/train-cross-gbt.js +2 -2
  91. package/out/tools/train-cross-gbt.js.map +1 -1
  92. package/out/tools/train-gbt.d.ts.map +1 -1
  93. package/out/tools/train-gbt.js +2 -2
  94. package/out/tools/train-gbt.js.map +1 -1
  95. package/out/tools/train-org-cross-gbt.d.ts.map +1 -1
  96. package/out/tools/train-org-cross-gbt.js +2 -2
  97. package/out/tools/train-org-cross-gbt.js.map +1 -1
  98. package/out/tools/txhhsc-to-oarow.js +2 -2
  99. package/out/tools/txhhsc-to-oarow.js.map +1 -1
  100. package/out/tools/viz/cross-dataset-map.d.ts +2 -23
  101. package/out/tools/viz/cross-dataset-map.d.ts.map +1 -1
  102. package/out/tools/viz/cross-dataset-map.js +7 -28
  103. package/out/tools/viz/cross-dataset-map.js.map +1 -1
  104. package/out/tools/viz/geocode-first-surface.d.ts +2 -32
  105. package/out/tools/viz/geocode-first-surface.d.ts.map +1 -1
  106. package/out/tools/viz/geocode-first-surface.js +4 -33
  107. package/out/tools/viz/geocode-first-surface.js.map +1 -1
  108. package/out/tools/viz/render.js +1 -1
  109. package/out/tools/viz/render.js.map +1 -1
  110. package/out/tools/viz/source-provenance-map.d.ts +2 -22
  111. package/out/tools/viz/source-provenance-map.d.ts.map +1 -1
  112. package/out/tools/viz/source-provenance-map.js +7 -26
  113. package/out/tools/viz/source-provenance-map.js.map +1 -1
  114. package/out/types.d.ts +11 -1
  115. package/out/types.d.ts.map +1 -1
  116. package/out/types.js.map +1 -1
  117. package/package.json +78 -9
  118. package/reconcile.ts +2 -1
  119. package/resolve.ts +6 -1
  120. package/tools/coverage-reconciliation.ts +3 -3
  121. package/tools/cross-dataset-correlation.ts +7 -5
  122. package/tools/cross-source-threshold-sweep.ts +3 -3
  123. package/tools/dedup-ceiling.ts +3 -3
  124. package/tools/eval-geocoder.ts +1 -1
  125. package/tools/geocoder-vs-provided-coords.ts +4 -2
  126. package/tools/gold-set-sample.ts +5 -3
  127. package/tools/index.ts +1 -6
  128. package/tools/learned-scorer-clustering-eval.ts +4 -4
  129. package/tools/learned-scorer-crossstate-eval.ts +4 -4
  130. package/tools/learned-scorer-eval.ts +4 -9
  131. package/tools/matcher-scale.ts +2 -1
  132. package/tools/nppes/levers.ts +102 -0
  133. package/tools/nppes/org-name.ts +56 -0
  134. package/tools/nppes/overmerge-packet.ts +96 -0
  135. package/tools/nppes/report.ts +376 -0
  136. package/tools/nppes/sample.ts +197 -0
  137. package/tools/nppes/scoring.ts +114 -0
  138. package/tools/nppes/truth-grains.ts +201 -0
  139. package/tools/nppes-dedup-benchmark.ts +92 -868
  140. package/tools/shared.ts +6 -4
  141. package/tools/train-cross-gbt.ts +6 -5
  142. package/tools/train-gbt.ts +5 -4
  143. package/tools/train-org-cross-gbt.ts +6 -5
  144. package/tools/txhhsc-to-oarow.ts +2 -2
  145. package/tools/viz/cross-dataset-map.ts +12 -34
  146. package/tools/viz/geocode-first-surface.ts +5 -33
  147. package/tools/viz/render.ts +1 -1
  148. package/tools/viz/source-provenance-map.ts +14 -31
  149. package/types.ts +10 -1
@@ -21,6 +21,10 @@
21
21
  * alternate name, so every entity has ≥2 records and the dedup is non-trivial. Streams the 4.8 GB
22
22
  * registry via `streamRows` (#616), so nothing loads whole.
23
23
  *
24
+ * The stages live in `./nppes/`: the sample, the scorer, the truth grains, the lever progression,
25
+ * the adjudication packet, and the report. This file is the orchestration — read it for the order
26
+ * of operations, the modules for what each stage does.
27
+ *
24
28
  * Run: `mailwoman registry scorer-eval nppes-benchmark [--state TX] [--max-npis 300]
25
29
  * [--wof <admin.db>] [--data-root <dir>] [--no-train-em]
26
30
  * [--out-md docs/articles/evals/matcher-dedup/<date>-nppes-dedup-benchmark.md]`
@@ -31,26 +35,30 @@ import { resolve as resolvePath } from "node:path"
31
35
  import { pathToFileURL } from "node:url"
32
36
 
33
37
  import { dataRootPath } from "@mailwoman/core/utils"
34
- import { haversineKm, jaccard, type GBT } from "@mailwoman/match"
38
+ import type { GBT } from "@mailwoman/match"
39
+
35
40
  import {
36
- addressFrequencyKey,
37
41
  ingestRows,
38
42
  resolveEntities,
39
- streamRows,
40
43
  type ColumnMapping,
41
44
  type GeocodeAddress,
42
45
  type ResolvedEntity,
43
46
  type SourceRecord,
44
- } from "@mailwoman/registry"
45
- import { latLngToCell } from "h3-js"
47
+ } from "#index"
46
48
 
47
49
  import type { EvalGeocodeStream, EvalGeocoderFactory } from "./eval-geocoder.ts"
48
- import { addr, MIN_GROUP_SIZE, norm, NPPES_COLUMNS as C } from "./shared.ts"
49
-
50
- /**
51
- * F1 gap within which two blocking strategies are treated as equivalent.
52
- */
53
- const BLOCKING_PARITY_TOLERANCE = 0.015
50
+ import { buildLevers } from "./nppes/levers.ts"
51
+ import { writeOvermergePacket } from "./nppes/overmerge-packet.ts"
52
+ import { renderNPPESDedupReport, type SweepArm } from "./nppes/report.ts"
53
+ import { buildNPPESSample } from "./nppes/sample.ts"
54
+ import { scoreEntities, type Score } from "./nppes/scoring.ts"
55
+ import {
56
+ buildOrgNameCoordGrain,
57
+ buildOrgNameGrain,
58
+ buildOrgNameH3Grain,
59
+ collectPrimaryCoordinates,
60
+ type TruthLabel,
61
+ } from "./nppes/truth-grains.ts"
54
62
 
55
63
  /**
56
64
  * Options for {@linkcode nppesDedupBenchmark}.
@@ -115,70 +123,9 @@ export interface NPPESDedupBenchmarkOptions {
115
123
  outMd?: string
116
124
  }
117
125
 
118
- /**
119
- * NPPES column names (verbatim from the file headers).
120
- */
121
- /**
122
- * Org-name similarity for the org-name entity-truth (the gold-set rule: same address + same org name ⇒ same entity,
123
- * even when NPPES doesn't flag the subpart). Strip corporate-form + articles, keep domain words (the distinguishing
124
- * signal).
125
- */
126
- const ORG_STOP = new Set([
127
- "llc",
128
- "inc",
129
- "incorporated",
130
- "corp",
131
- "corporation",
132
- "co",
133
- "ltd",
134
- "pllc",
135
- "pc",
136
- "pa",
137
- "lp",
138
- "llp",
139
- "the",
140
- "of",
141
- "and",
142
- ])
143
-
144
- const orgTokens = (s: string): Set<string> =>
145
- new Set(
146
- s
147
- .toLowerCase()
148
- .replaceAll(/[^a-z0-9 ]/g, " ")
149
- .split(/\s+/)
150
- .filter((t) => t && !ORG_STOP.has(t))
151
- )
152
-
153
- /**
154
- * Gold-set threshold.
155
- */
156
- const ORG_TAU = 0.7
157
-
158
- /**
159
- * One synthetic input row for the matcher; `npi` is the hidden NPI-level truth, `entityID` the site-level entity-level
160
- * truth (subpart-collapsed).
161
- */
162
- interface MessyRow {
163
- npi: string
164
- name: string
165
- org: string
166
- address: string
167
- auth: string
168
- /**
169
- * Whitespace-joined taxonomy-code set (up to 15 slots) — the #625 code-set discriminator.
170
- */
171
- taxonomy: string
172
- entityID: string
173
- }
174
-
175
126
  /**
176
127
  * The #617 NPPES dedup benchmark — see the module doc. Emits the markdown report to stdout.
177
128
  */
178
- /* oxlint-disable max-lines, max-statements, complexity -- 824 lines / 261 statements / complexity 101.
179
- Same shape as oa-resolver-eval: a linear benchmark (build the sample, run each lever, score, emit the
180
- markdown) whose report half wants the same extraction that file got. Left whole because the report
181
- reads ~40 locals and typing that seam properly is a bigger change than this pass should carry. */
182
129
  export async function nppesDedupBenchmark(
183
130
  options: NPPESDedupBenchmarkOptions,
184
131
  report?: (line: string) => void
@@ -193,124 +140,15 @@ export async function nppesDedupBenchmark(
193
140
  const PARALLEL_GEOCODE = options.parallelGeocode ?? false
194
141
  const GEO_CONC = options.geoConcurrency ?? 2
195
142
 
196
- const REGISTRY = `${SOURCES}/nppes_npi-registry_20260607.tsv`
197
- const OTHER_NAMES = `${SOURCES}/nppes_other-names_20260607.tsv`
198
-
199
- // --- Phase A: the variation set — NPIs that carry ≥1 alternate organization name. ---
200
- report?.("[A] streaming other-names…")
201
- const altNames = new Map<string, string[]>()
202
-
203
- for await (const r of streamRows(OTHER_NAMES)) {
204
- const npi = norm(r[C.npi])
205
- const alt = norm(r[C.otherOrg])
206
-
207
- if (!npi || !alt) continue
208
- const list = altNames.get(npi) ?? []
209
-
210
- if (list.length < MIN_GROUP_SIZE) {
211
- list.push(alt)
212
- }
213
-
214
- // cap fan-out per NPI
215
- altNames.set(npi, list)
216
- }
217
-
218
- report?.(` ${altNames.size} NPIs with ≥1 alternate name`)
219
-
220
- // --- Phase B: ONE full registry pass — build the GLOBAL address-frequency table (every practice
221
- // address, so the sharing structure is corpus-wide, not sample-biased) AND collect the sample. ---
222
- report?.(`[B] full registry pass: address-frequency table + ${MAX_NPIS} ${STATE} sample…`)
223
- const rows: MessyRow[] = []
224
- const kept = new Set<string>()
225
- // Per-NPI primary org name + practice address key — the basis for the ORG-NAME entity-truth.
226
- const npiPrimary = new Map<string, { tokens: Set<string>; addrKey: string }>()
227
- const addrCounts = new Map<string, number>()
228
- let addrTotal = 0
229
- let scanned = 0
230
-
231
- for await (const r of streamRows(REGISTRY)) {
232
- if (++scanned % 1_000_000 === 0) {
233
- report?.(` scanned ${scanned / 1e6}M rows, kept ${kept.size}`)
234
- }
235
-
236
- const practice = addr(r[C.pAddr]!, r[C.pCity]!, r[C.pState]!, r[C.pZip]!)
237
-
238
- // Global address-frequency: count every practice address (one row ≈ one distinct NPI).
239
- if (practice) {
240
- const k = addressFrequencyKey(practice)
241
- addrCounts.set(k, (addrCounts.get(k) ?? 0) + 1)
242
-
243
- addrTotal++
244
- }
245
-
246
- // Sample: in-state NPIs with ≥1 alternate name, up to MAX_NPIS — NO early break (the table needs the full pass).
247
- const npi = norm(r[C.npi])
248
-
249
- if (
250
- kept.size < MAX_NPIS &&
251
- npi &&
252
- !kept.has(npi) &&
253
- altNames.has(npi) &&
254
- practice &&
255
- norm(r[C.pState]).toUpperCase() === STATE
256
- ) {
257
- const isOrg = norm(r[C.entityType]) === "2"
258
- const primaryName = isOrg ? norm(r[C.orgLegal]) : `${norm(r[C.first])} ${norm(r[C.last])}`.trim()
259
-
260
- if (primaryName) {
261
- const org = isOrg ? norm(r[C.orgLegal]) : ""
262
- const auth = `${norm(r[C.authFirst])} ${norm(r[C.authLast])}`.trim()
263
-
264
- // the NPI's registrant — shared across its records
265
- // #625: the taxonomy-code set (up to 15 slots), whitespace-joined — identical across the NPI's
266
- // records by construction (it's a per-NPI registry attribute), so it NEVER splits one entity;
267
- // it only separates co-located DISTINCT providers whose sets are disjoint.
268
- const taxonomy = C.taxonomy
269
- .map((col) => norm(r[col]))
270
- .filter(Boolean)
271
- .join(" ")
272
-
273
- // Entity-level (site) truth: same org + same physical address. Subparts (NPPES
274
- // "Is Organization Subpart" + parent LBN/TIN) collapse to their PARENT, so the matcher isn't
275
- // charged for correctly fusing one org's many subpart-NPIs at a site; an NPI's mailing-vs-
276
- // practice records stay DISTINCT sites. orgKey = parent identity for subparts, else the NPI
277
- // (independent orgs sharing an address stay distinct — the conservative choice).
278
- const isSubpart = norm(r[C.isSubpart]).toUpperCase() === "Y"
279
- const parentKey = `${norm(r[C.parentLBN])}|${norm(r[C.parentTIN])}`.toLowerCase()
280
- const orgKey = isSubpart && parentKey !== "|" ? `p:${parentKey}` : `n:${npi}`
281
- const eid = (a: string) => `${addressFrequencyKey(a)}|${orgKey}`
282
-
283
- if (org) {
284
- npiPrimary.set(npi, { tokens: orgTokens(org), addrKey: addressFrequencyKey(practice) })
285
- }
286
-
287
- kept.add(npi)
288
- rows.push({ npi, name: primaryName, org, address: practice, auth, taxonomy, entityID: eid(practice) })
289
-
290
- // primary
291
- for (const alt of altNames.get(npi)!) {
292
- rows.push({ npi, name: alt, org: alt, address: practice, auth, taxonomy, entityID: eid(practice) })
293
- }
294
-
295
- // name drift
296
- const mailing = addr(r[C.mAddr]!, r[C.mCity]!, r[C.mState]!, r[C.mZip]!)
297
-
298
- if (mailing && mailing !== practice) {
299
- rows.push({ npi, name: primaryName, org, address: mailing, auth, taxonomy, entityID: eid(mailing) })
300
- } // address variation
301
- }
302
- }
303
- }
304
-
305
- // Corpus-wide address-frequency table — the inverse-frequency signal (#617 fix per the DeepSeek consult).
306
- const addressFrequency = {
307
- total: addrTotal,
308
- distinct: addrCounts.size,
309
- frequency: (v: string) => (v ? (addrCounts.get(addressFrequencyKey(v)) ?? 0) / addrTotal : 0),
310
- }
311
-
312
- report?.(
313
- ` ${kept.size} NPIs → ${rows.length} records; address table: ${addrCounts.size} distinct over ${addrTotal} rows`
143
+ // --- Phases A + B: the variation-rich sample plus the corpus-wide address-frequency table. ---
144
+ const { rows, keptNpis, npiPrimary, addressFrequency } = await buildNPPESSample(
145
+ {
146
+ registryPath: `${SOURCES}/nppes_npi-registry_20260607.tsv`,
147
+ otherNamesPath: `${SOURCES}/nppes_other-names_20260607.tsv`,
148
+ state: STATE,
149
+ maxNpis: MAX_NPIS,
150
+ },
151
+ report
314
152
  )
315
153
 
316
154
  // --- Phase C: geocode + ingest (the NPI rides on record.id as the held-out label). The heavy
@@ -341,7 +179,7 @@ export async function nppesDedupBenchmark(
341
179
  throw new Error("parallelGeocode requires the injected geocodeStream (see ./eval-geocoder.ts)")
342
180
  }
343
181
 
344
- const normalized = await ingestRows(rows as unknown as Record<string, string>[], mapping)
182
+ const normalized = await ingestRows(rows, mapping)
345
183
  const order = new Map(normalized.map((r, i) => [r.id, i]))
346
184
  const geocoded: SourceRecord[] = []
347
185
 
@@ -370,7 +208,7 @@ export async function nppesDedupBenchmark(
370
208
  return g
371
209
  }
372
210
 
373
- records = await ingestRows(rows as unknown as Record<string, string>[], mapping, {
211
+ records = await ingestRows(rows, mapping, {
374
212
  geocodeAddress: countedSeam,
375
213
  addressSeparator: LEGACY ? " " : ", ",
376
214
  })
@@ -380,403 +218,41 @@ export async function nppesDedupBenchmark(
380
218
 
381
219
  report?.(` geocoded ${geo}/${rows.length} (${((100 * geo) / rows.length).toFixed(1)}%)`)
382
220
 
383
- // --- Phase E: score recovered clusters vs the NPI grouping (record.id = the held-out NPI). ---
384
- const choose2 = (n: number) => (n * (n - 1)) / 2
221
+ // --- Phase E: score recovered clusters against each truth grain (record.id = the held-out NPI). ---
385
222
  const N = records.length
386
223
 
387
- interface Score {
388
- precision: number
389
- recall: number
390
- f1: number
391
- ari: number
392
- clusters: number
393
- singletons: number
394
- overMergedClusters: number
395
- recordsInOverMerged: number
396
- maxNpisFused: number
397
- splitNpis: number
398
- }
399
-
400
- function scoreEntities(entities: ResolvedEntity[], labelOf: (rec: SourceRecord) => string): Score {
401
- const npiTotals = new Map<string, number>()
402
- const npiClusters = new Map<string, Set<number>>()
403
- let sumCK = 0 // Σ C(n_ck, 2)
404
- let sumCluster = 0 // Σ_c C(|c|, 2)
405
- let singletons = 0
406
- let overMergedClusters = 0
407
- let recordsInOverMerged = 0
408
- let maxNpisFused = 0
409
-
410
- entities.forEach((e, ci) => {
411
- const byNPI = new Map<string, number>()
412
-
413
- for (const rec of e.records) {
414
- const lbl = labelOf(rec)
415
- byNPI.set(lbl, (byNPI.get(lbl) ?? 0) + 1)
416
- }
417
-
418
- sumCluster += choose2(e.records.length)
419
-
420
- if (e.records.length === 1) {
421
- singletons++
422
- }
423
-
424
- if (byNPI.size > 1) {
425
- overMergedClusters++
426
- recordsInOverMerged += e.records.length
427
- maxNpisFused = Math.max(maxNpisFused, byNPI.size)
428
- }
429
-
430
- for (const [npi, n] of byNPI) {
431
- sumCK += choose2(n)
432
- npiTotals.set(npi, (npiTotals.get(npi) ?? 0) + n)
433
- }
434
-
435
- for (const rec of e.records) {
436
- const lbl = labelOf(rec)
437
- const s = npiClusters.get(lbl) ?? new Set<number>()
438
- s.add(ci)
439
- npiClusters.set(lbl, s)
440
- }
441
- })
442
-
443
- let sumClass = 0
444
-
445
- // Σ_k C(|k|, 2)
446
- for (const total of npiTotals.values()) {
447
- sumClass += choose2(total)
448
- }
449
-
450
- const tp = sumCK
451
- const precision = tp + (sumCluster - tp) > 0 ? tp / sumCluster : 0
452
- const recall = sumClass > 0 ? tp / sumClass : 0
453
- const f1 = precision + recall > 0 ? (2 * precision * recall) / (precision + recall) : 0
454
- const expected = (sumCluster * sumClass) / choose2(N)
455
- const maxIndex = (sumCluster + sumClass) / 2
456
- const ari = maxIndex - expected !== 0 ? (tp - expected) / (maxIndex - expected) : 1
457
- const splitNpis = [...npiClusters.values()].filter((s) => s.size > 1).length
458
-
459
- return {
460
- precision,
461
- recall,
462
- f1,
463
- ari,
464
- clusters: entities.length,
465
- singletons,
466
- overMergedClusters,
467
- recordsInOverMerged,
468
- maxNpisFused,
469
- splitNpis,
470
- }
471
- }
224
+ // Every grain scores against the SAME record population, so the ARI expectation is fixed for the run.
225
+ const score = (entities: readonly ResolvedEntity[], labelOf: TruthLabel): Score => scoreEntities(entities, labelOf, N)
472
226
 
473
227
  // Truth labels: NPI-level (the conservative held-out NPI = record.id) and entity-level (the
474
228
  // site-level subpart-collapsed id that rides on attributes.entityTruth). Scoring the SAME clusters
475
229
  // both ways isolates how much of the apparent over-merge is NPI over-segmentation, not model error.
476
230
  const npiLabel = (rec: SourceRecord) => rec.id
477
231
  const entityLabel = (rec: SourceRecord) => rec.attributes?.["entityTruth"] ?? rec.id
232
+ const orgNameLabel = buildOrgNameGrain(npiPrimary)
478
233
 
479
- // --- ORG-NAME entity-truth (the gold-set lever, #625). Union-find over NPIs: same NPI ⇒ same entity
480
- // (so an NPI's records stay together — recall preserved), PLUS union two NPIs at the same address whose
481
- // primary org names match (Jaccard ≥ ORG_TAU). This collapses the same-org-many-NPIs over-segmentation
482
- // the gold set proved is correct, WITHOUT the subpart flag (which the gold set showed misses 37%). ---
483
- const parent = new Map<string, string>()
484
-
485
- const find = (x: string): string => {
486
- if (!parent.has(x)) {
487
- parent.set(x, x)
488
- }
489
-
490
- let root = x
491
-
492
- while (parent.get(root)! !== root) {
493
- root = parent.get(root)!
494
- }
495
-
496
- while (parent.get(x)! !== root) {
497
- const next = parent.get(x)!
498
- parent.set(x, root)
499
- x = next
500
- }
501
-
502
- return root
503
- }
504
-
505
- const union = (a: string, b: string) => {
506
- const ra = find(a)
507
- const rb = find(b)
508
-
509
- if (ra !== rb) {
510
- parent.set(ra, rb)
511
- }
512
- }
513
-
514
- {
515
- const byAddr = new Map<string, string[]>()
516
-
517
- for (const [npi, info] of npiPrimary) {
518
- find(npi)
519
-
520
- // seed
521
- if (!info.addrKey) continue
522
-
523
- if (!byAddr.has(info.addrKey)) {
524
- byAddr.set(info.addrKey, [])
525
- }
526
-
527
- byAddr.get(info.addrKey)!.push(npi)
528
- }
529
-
530
- for (const group of byAddr.values()) {
531
- for (let i = 0; i < group.length; i++) {
532
- for (let j = i + 1; j < group.length; j++) {
533
- if (jaccard(npiPrimary.get(group[i]!)!.tokens, npiPrimary.get(group[j]!)!.tokens) >= ORG_TAU) {
534
- union(group[i]!, group[j]!)
535
- }
536
- }
537
- }
538
- }
539
- }
540
- const orgNameLabel = (rec: SourceRecord) => (npiPrimary.has(rec.id) ? find(rec.id) : rec.id)
541
-
542
- // --- ORG-NAME-COORD entity-truth (Tier 2D, #625). The string org-name truth above blocks by the
543
- // address STRING (`addressFrequencyKey`), so it MISSES same-building pairs whose text differs —
544
- // "1504 Taub LOOP" vs "1504 Taub LP STE 100" key apart even though the geocoder places them at one
545
- // point. This variant blocks by the GEOCODED BUILDING instead: union two NPIs whose org names match
546
- // (Jaccard ≥ ORG_TAU) AND whose primary practice coordinates are within the same-building distance
547
- // (≤ 50 m haversine, the DEFAULT_DISTANCE_LEVELS grain). Brute-force pairwise over the ~1000 sampled
548
- // NPIs (trivial); a tighter LOWER bound on the org-name truth — the org-name F1 here is ≥ the string
549
- // one. The Jaccard gate still prevents collapsing distinct co-located orgs (the gold-set safety). ---
550
- const COLOCATION_KM = 0.05
551
- const npiCoord = new Map<string, { latitude: number; longitude: number }>()
552
-
553
- for (const rec of records) {
554
- const c = rec.address?.geocode?.coordinate
555
-
556
- // first geocoded record per NPI ≈ its primary practice address (primary row is pushed first)
557
- if (c && !npiCoord.has(rec.id)) {
558
- npiCoord.set(rec.id, c)
559
- }
560
- }
561
-
562
- const parentC = new Map<string, string>()
563
-
564
- const findC = (x: string): string => {
565
- if (!parentC.has(x)) {
566
- parentC.set(x, x)
567
- }
568
-
569
- let root = x
570
-
571
- while (parentC.get(root)! !== root) {
572
- root = parentC.get(root)!
573
- }
574
-
575
- while (parentC.get(x)! !== root) {
576
- const next = parentC.get(x)!
577
- parentC.set(x, root)
578
- x = next
579
- }
580
-
581
- return root
582
- }
583
-
584
- const unionC = (a: string, b: string) => {
585
- const ra = findC(a)
586
- const rb = findC(b)
587
-
588
- if (ra !== rb) {
589
- parentC.set(ra, rb)
590
- }
591
- }
592
-
593
- {
594
- const coLocated = [...npiPrimary.keys()].filter((n) => npiCoord.has(n))
595
-
596
- for (const n of npiPrimary.keys()) {
597
- findC(n)
598
- }
599
-
600
- // seed every NPI (un-geocoded ones stay singletons)
601
- for (let i = 0; i < coLocated.length; i++) {
602
- for (let j = i + 1; j < coLocated.length; j++) {
603
- const a = coLocated[i]!
604
- const b = coLocated[j]!
605
-
606
- if (haversineKm(npiCoord.get(a)!, npiCoord.get(b)!) > COLOCATION_KM) continue
607
-
608
- if (jaccard(npiPrimary.get(a)!.tokens, npiPrimary.get(b)!.tokens) >= ORG_TAU) {
609
- unionC(a, b)
610
- }
611
- }
612
- }
613
- }
234
+ const npiCoord = collectPrimaryCoordinates(records)
235
+ const orgNameCoordLabel = buildOrgNameCoordGrain(npiPrimary, npiCoord)
614
236
  const geocodedNpis = [...npiPrimary.keys()].filter((n) => npiCoord.has(n)).length
615
- const orgNameCoordLabel = (rec: SourceRecord) => (npiPrimary.has(rec.id) ? findC(rec.id) : rec.id)
616
237
 
617
- // --- ORG-NAME-H3 entity-truth (#109). The same building-grain co-location, but keyed on an
618
- // H3 CELL (the geocode-first "cell" the issue suggested) instead of a pairwise 50 m haversine: assign
619
- // each NPI's coordinate to an H3 cell at building-block resolution, then union same-org (Jaccard ≥
620
- // ORG_TAU) NPIs that share a cell. A robustness check on the haversine coord-grain — if the F1
621
- // matches, the number isn't an artifact of the 50 m threshold, and cell-blocking is O(n) not O(n²).
622
- // Caveat: a hard cell boundary can split a same-building pair into adjacent cells (a slight
623
- // under-count vs the radius); res 10 (~65 m edge) absorbs most of it. ---
624
238
  const H3_RES = options.h3Res ?? 11 // res 11 ≈ 25 m edge; res 10 ≈ 65 m (block scale)
625
- const parentH = new Map<string, string>()
626
-
627
- const findH = (x: string): string => {
628
- if (!parentH.has(x)) {
629
- parentH.set(x, x)
630
- }
631
-
632
- let root = x
633
-
634
- while (parentH.get(root)! !== root) {
635
- root = parentH.get(root)!
636
- }
637
-
638
- while (parentH.get(x)! !== root) {
639
- const next = parentH.get(x)!
640
- parentH.set(x, root)
641
- x = next
642
- }
643
-
644
- return root
645
- }
646
-
647
- const unionH = (a: string, b: string) => {
648
- const ra = findH(a)
649
- const rb = findH(b)
650
-
651
- if (ra !== rb) {
652
- parentH.set(ra, rb)
653
- }
654
- }
655
-
656
- {
657
- const byCell = new Map<string, string[]>()
658
-
659
- for (const n of npiPrimary.keys()) {
660
- findH(n) // seed every NPI (un-geocoded ones stay singletons)
661
- const c = npiCoord.get(n)
662
-
663
- if (!c) continue
664
- const cell = latLngToCell(c.latitude, c.longitude, H3_RES)
665
-
666
- if (!byCell.has(cell)) {
667
- byCell.set(cell, [])
668
- }
669
-
670
- byCell.get(cell)!.push(n)
671
- }
672
-
673
- for (const group of byCell.values()) {
674
- for (let i = 0; i < group.length; i++) {
675
- for (let j = i + 1; j < group.length; j++) {
676
- if (jaccard(npiPrimary.get(group[i]!)!.tokens, npiPrimary.get(group[j]!)!.tokens) >= ORG_TAU) {
677
- unionH(group[i]!, group[j]!)
678
- }
679
- }
680
- }
681
- }
682
- }
683
- const orgNameH3Label = (rec: SourceRecord) => (npiPrimary.has(rec.id) ? findH(rec.id) : rec.id)
239
+ const orgNameH3Label = buildOrgNameH3Grain(npiPrimary, npiCoord, H3_RES)
684
240
 
685
241
  // --- Phase D: the comparison-model lever progression — toggle each lever ON in turn at the default
686
242
  // threshold to isolate its marginal effect, then sweep the link threshold on the best config (geocode
687
243
  // once, resolve many — config is cheap). ---
688
244
  report?.(`[D] resolving the lever progression${TRAIN_EM ? " (EM-trained)" : ""}…`)
689
245
 
690
- interface LeverConfig {
691
- addressFrequency?: typeof addressFrequency | false
692
- collapseSpatial?: boolean
693
- discriminators?: string[]
694
- requireCorroboration?: boolean
695
- usePhone?: boolean
696
- linkage?: "single" | "average"
697
- exactDiscriminators?: string[]
698
- }
699
-
700
- // The proven levers are now DEFAULT-ON in resolveEntities (#86). Each row sets BOTH `collapseSpatial`
701
- // and `addressFrequency` EXPLICITLY so the progression isolates one lever at a time — otherwise the
702
- // flipped default (collapseSpatial:true) would silently ride the `+ inverse-address-frequency` row and
703
- // the A1 delta would read as 0. Every row feeds the corpus-wide frequency table (the realistic
704
- // deployment, where the CLI builds it from the full source files); the zero-config `{}` default is
705
- // reported SEPARATELY below, since on a sub-sample its input-scoped table is intentionally sparse.
706
- const LEVERS: Array<{ label: string; config: LeverConfig }> = [
707
- {
708
- label: "baseline (legacy: address-key + distance, levers OFF)",
709
- config: { collapseSpatial: false, addressFrequency: false },
710
- },
711
- { label: "+ inverse-address-frequency (#617, corpus-wide)", config: { collapseSpatial: false, addressFrequency } },
712
- { label: "+ collapsed spatial signal (A1, #625)", config: { collapseSpatial: true, addressFrequency } },
713
- {
714
- label: "+ authorized-official discriminator (#625)",
715
- config: { collapseSpatial: true, addressFrequency, discriminators: ["authorizedOfficial"] },
716
- },
717
- // A2–A4 (#625): the built-but-unmeasured over-merge levers. Each builds on the A1 + discriminator
718
- // stack so the marginal effect is isolated. A2 (require name/org corroboration) is the direct
719
- // over-merge precision lever; A3 (phone) is the recall-tail corroborator that should keep A2 from
720
- // killing name-drift links; A4 (average-linkage) splits a component joined only by a weak bridge.
721
- {
722
- label: "+ require name/org corroboration (A2, #625)",
723
- config: {
724
- collapseSpatial: true,
725
- addressFrequency,
726
- discriminators: ["authorizedOfficial"],
727
- requireCorroboration: true,
728
- },
729
- },
730
- {
731
- label: "+ phone comparison (A3, #625)",
732
- config: {
733
- collapseSpatial: true,
734
- addressFrequency,
735
- discriminators: ["authorizedOfficial"],
736
- requireCorroboration: true,
737
- usePhone: true,
738
- },
739
- },
740
- {
741
- label: "+ average-linkage clustering (A4, #625, full A1–A4 stack)",
742
- config: {
743
- collapseSpatial: true,
744
- addressFrequency,
745
- discriminators: ["authorizedOfficial"],
746
- requireCorroboration: true,
747
- usePhone: true,
748
- linkage: "average",
749
- },
750
- },
751
- // A5 (#625): the taxonomy code-set discriminator — set-overlap agreement over the NPI's 15 taxonomy
752
- // slots. The named "still-more-distinctive identifier" from the 2026-06-16 report: co-located
753
- // DISTINCT providers usually have disjoint sets (the over-merge separator) while an entity's own
754
- // records always share theirs (never splits). Stacked on the BEST prior classical config (A1 +
755
- // authorized-official; A3 phone + A4 avg-linkage were measured neutral-to-negative and are left off).
756
- {
757
- label: "+ taxonomy code-set discriminator (A5, #625)",
758
- config: {
759
- collapseSpatial: true,
760
- addressFrequency,
761
- discriminators: ["authorizedOfficial"],
762
- exactDiscriminators: ["taxonomy"],
763
- },
764
- },
765
- ]
766
-
767
246
  // learnedScorer:false throughout — this benchmark studies the FS COMPARISON-MODEL levers (#617/#625).
768
247
  // The learned scorer is now default-on, so it must be pinned off here or every row would silently be the
769
248
  // GBT; the learned scorer is measured separately (learned-scorer-clustering-eval / -crossstate-eval).
770
- const progression = LEVERS.map((l) => {
249
+ const progression = buildLevers(addressFrequency).map((l) => {
771
250
  const res = resolveEntities(records, { learnedScorer: false, trainEM: TRAIN_EM, threshold: 0, ...l.config })
772
251
 
773
- return { ...l, res, score: scoreEntities(res.entities, npiLabel) }
252
+ return { ...l, res, score: score(res.entities, npiLabel) }
774
253
  })
775
254
 
776
- const baseline = progression[0]! // no levers — the prior-prior behaviour
777
- const bestLever = progression.at(-1)!
778
-
779
- // the full lever stack
255
+ const bestLever = progression.at(-1)! // the full lever stack
780
256
 
781
257
  // The SHIPPED out-of-box default (#86): no lever config at all → resolveEntities auto-computes an
782
258
  // input-scoped address-frequency table + collapsed spatial. On this deliberately-sub-sampled corpus the
@@ -784,18 +260,15 @@ export async function nppesDedupBenchmark(
784
260
  // ≈baseline — NOT a regression, just the honest truth that IDF is a corpus statistic you can't synthesize
785
261
  // from a slice. On a FULL-dataset dedup the input IS the corpus and this default reaches the baseline; the
786
262
  // CLI passes a corpus-wide table built from the full source files so even a geocoded sub-sample benefits.
787
- const defaultOutOfBox = (() => {
788
- const res = resolveEntities(records, { learnedScorer: false, trainEM: TRAIN_EM, threshold: 0 })
789
-
790
- return { res, score: scoreEntities(res.entities, npiLabel) }
791
- })()
263
+ const defaultRes = resolveEntities(records, { learnedScorer: false, trainEM: TRAIN_EM, threshold: 0 })
264
+ const defaultOutOfBox = score(defaultRes.entities, npiLabel)
792
265
 
793
266
  const THRESHOLDS = [0, 4, 8, 12, 16, 20]
794
267
 
795
- const sweep = THRESHOLDS.map((t) => {
268
+ const sweep: SweepArm[] = THRESHOLDS.map((t) => {
796
269
  const res = resolveEntities(records, { learnedScorer: false, trainEM: TRAIN_EM, threshold: t, ...bestLever.config })
797
270
 
798
- return { t, res, score: scoreEntities(res.entities, npiLabel) }
271
+ return { t, res, score: score(res.entities, npiLabel) }
799
272
  })
800
273
 
801
274
  const base = sweep[0]! // threshold 0, full lever stack
@@ -822,76 +295,36 @@ export async function nppesDedupBenchmark(
822
295
  const entityCount = new Set(records.map((r) => entityLabel(r))).size
823
296
  const orgCount = new Set(records.map((r) => orgNameLabel(r))).size
824
297
  const fsNPI = bestLever.score
825
- const fsEntity = scoreEntities(bestLever.res.entities, entityLabel)
826
- const fsOrg = scoreEntities(bestLever.res.entities, orgNameLabel)
298
+ const fsEntity = score(bestLever.res.entities, entityLabel)
299
+ const fsOrg = score(bestLever.res.entities, orgNameLabel)
827
300
  const gbtRes = resolveEntities(records, { addressFrequency, trainEM: TRAIN_EM }) // GBT default-on (production)
828
- const gbtNPI = scoreEntities(gbtRes.entities, npiLabel)
829
- const gbtEntity = scoreEntities(gbtRes.entities, entityLabel)
830
- const gbtOrg = scoreEntities(gbtRes.entities, orgNameLabel)
301
+ const gbtNPI = score(gbtRes.entities, npiLabel)
302
+ const gbtEntity = score(gbtRes.entities, entityLabel)
303
+ const gbtOrg = score(gbtRes.entities, orgNameLabel)
831
304
  // Tier 2D: the coordinate-co-location org-name truth (tighter lower bound).
832
305
  const orgCoordCount = new Set(records.map((r) => orgNameCoordLabel(r))).size
833
- const fsOrgCoord = scoreEntities(bestLever.res.entities, orgNameCoordLabel)
834
- const gbtOrgCoord = scoreEntities(gbtRes.entities, orgNameCoordLabel)
306
+ const fsOrgCoord = score(bestLever.res.entities, orgNameCoordLabel)
307
+ const gbtOrgCoord = score(gbtRes.entities, orgNameCoordLabel)
835
308
  // #109: the H3-cell co-location truth — a robustness check on the haversine coord-grain.
836
309
  const orgH3Count = new Set(records.map((r) => orgNameH3Label(r))).size
837
- const gbtOrgH3 = scoreEntities(gbtRes.entities, orgNameH3Label)
310
+ const gbtOrgH3 = score(gbtRes.entities, orgNameH3Label)
838
311
 
839
- // --- #625 gold-set adjudication packet (--dump-overmerges <path>): the org-name-grain over-merged
840
- // clusters from the SHIPPED (GBT) config, with full member records, formatted for HUMAN review. The
841
- // residual over-merge is small (~21 clusters) and approaching the measured ~1.6% irreducible ceiling —
842
- // per-pair adjudication (same entity? distinct co-located?) is the only instrument left that can
843
- // separate model error from yardstick error. Each cluster prints its members grouped by org-name
844
- // label with every matcher-visible field, so a reviewer can adjudicate in one glance.
312
+ // The adjudication packet grades the SHIPPED (GBT) clusters, because the residual over-merge is small and
313
+ // approaching the measured ~1.6% irreducible ceiling — per-pair human adjudication (same entity? distinct
314
+ // co-located?) is the only instrument left that can separate model error from yardstick error.
845
315
  const DUMP_OVERMERGES = options.dumpOvermerges || ""
846
316
 
847
317
  if (DUMP_OVERMERGES) {
848
- const rowByID = new Map(rows.map((r) => [r.npi, r]))
849
-
850
- const out: string[] = [
851
- "# #625 gold-set adjudication packet — org-name-grain over-merged clusters (GBT, shipped config)",
852
- "",
853
- `TX --max-npis ${MAX_NPIS} · ${records.length} records · generated by \`registry scorer-eval nppes-benchmark --dump-overmerges\``,
854
- "",
855
- "For each cluster: the matcher fused records that the org-name truth says belong to DIFFERENT entities.",
856
- "Adjudicate each: **[same]** one real-world entity (yardstick error — the truth under-collapsed) or",
857
- "**[distinct]** genuinely different co-located providers (model over-merge). Mark inline and return.",
858
- "",
859
- ]
860
-
861
- let n = 0
862
-
863
- gbtRes.entities.forEach((e) => {
864
- const byLabel = new Map<string, SourceRecord[]>()
865
-
866
- for (const rec of e.records) {
867
- const lbl = orgNameLabel(rec)
868
- const list = byLabel.get(lbl) ?? []
869
- list.push(rec)
870
- byLabel.set(lbl, list)
871
- }
872
-
873
- if (byLabel.size <= 1) return
874
-
875
- n++
876
- out.push(`## Cluster ${n} — ${e.records.length} records, ${byLabel.size} org-name entities → verdict: [ ]`)
877
-
878
- for (const [lbl, members] of byLabel) {
879
- out.push(`- **entity ${lbl}**`)
880
-
881
- for (const rec of members) {
882
- const src = rowByID.get(rec.id)
883
-
884
- out.push(
885
- ` - 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 ?? ""}"`
886
- )
887
- }
888
- }
889
-
890
- out.push("")
318
+ const clusters = writeOvermergePacket(DUMP_OVERMERGES, {
319
+ state: STATE,
320
+ entities: gbtRes.entities,
321
+ rows,
322
+ recordCount: records.length,
323
+ maxNpis: MAX_NPIS,
324
+ orgNameLabel,
891
325
  })
892
326
 
893
- writeFileSync(DUMP_OVERMERGES, out.join("\n"))
894
- report?.(` adjudication packet: ${n} over-merged clusters -> ${DUMP_OVERMERGES}`)
327
+ report?.(` adjudication packet: ${clusters} over-merged clusters -> ${DUMP_OVERMERGES}`)
895
328
  }
896
329
 
897
330
  // Optional candidate A/B (--candidate): score a trained GBT module at both levels, at its own
@@ -917,8 +350,8 @@ export async function nppesDedupBenchmark(
917
350
 
918
351
  cand = {
919
352
  label: `GBT candidate (${mod.DEDUP_GBT_META?.features ?? "?"}-feat${cost !== 1 ? `, cost ×${cost}` : ""})`,
920
- npi: scoreEntities(res.entities, npiLabel),
921
- entity: scoreEntities(res.entities, entityLabel),
353
+ npi: score(res.entities, npiLabel),
354
+ entity: score(res.entities, entityLabel),
922
355
  }
923
356
 
924
357
  report?.(
@@ -931,244 +364,35 @@ export async function nppesDedupBenchmark(
931
364
  `FS: NPI ${(100 * fsNPI.f1).toFixed(1)}% / entity ${(100 * fsEntity.f1).toFixed(1)}% / org-coord ${(100 * fsOrgCoord.f1).toFixed(1)}%`
932
365
  )
933
366
 
934
- // NOTE(phase4): local pct keeps the fraction-in/no-%-suffix shape — not core formatPercent's
935
- // numerator/denominator contract (call sites append their own "%").
936
- const pct = (x: number) => (100 * x).toFixed(1)
937
- const signed = (x: number) => `${x >= 0 ? "+" : ""}${x.toFixed(1)}pp`
938
-
939
- const lines: string[] = [
940
- `# NPPES NPI dedup benchmark (#617)`,
941
- "",
942
- `_Generated by \`mailwoman registry scorer-eval nppes-benchmark\`. Sample: ${kept.size} ${STATE} NPIs with ≥1 ` +
943
- `alternate name → ${N} records (${(N / kept.size).toFixed(1)}/NPI) from real registry + other-names + ` +
944
- `mailing-vs-practice variation. Matcher run BLIND to the NPI${TRAIN_EM ? ", EM-trained (label-free)" : ""}; ` +
945
- `geocoded ${pct(geo / N)}% of addresses. The NPI is held-out ground truth._`,
946
- "",
947
- `**Headline — org-name truth (the honest grain):** the shipped ` +
948
- `matcher resolves these records at **F1 ${pct(gbtOrg.f1)}%** against org-name entity-truth — not the NPI-level ` +
949
- `${pct(gbtNPI.f1)}%, which mostly measures NPI over-segmentation (one organization holds many subpart NPIs, so ` +
950
- `correct co-located merges are scored as errors). Same clusters, three rulers: ` +
951
- `**NPI ${pct(gbtNPI.f1)}% → site ${pct(gbtEntity.f1)}% → org-name ${pct(gbtOrg.f1)}%** ` +
952
- `(${kept.size} NPI → ${entityCount} site → ${orgCount} org-name classes); the climb is the yardstick getting honest, ` +
953
- `not the model changing — gold-set validated (120/120 hard pairs = same org). Details in "Three truth grains" below.`,
954
- "",
955
- `## The comparison-model levers (each toggled on, at the default threshold)`,
956
- "",
957
- `| model | precision | recall | F1 | ΔF1 | ARI | over-merged |`,
958
- `|---|---:|---:|---:|---:|---:|---:|`,
959
- ]
960
-
961
- progression.forEach((p, i) => {
962
- const delta = i === 0 ? "—" : signed(100 * (p.score.f1 - progression[i - 1]!.score.f1))
963
- const bold = i === progression.length - 1
964
- const w = (s: string) => (bold ? `**${s}**` : s)
965
-
966
- lines.push(
967
- `| ${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))} |`
968
- )
367
+ const md = renderNPPESDedupReport({
368
+ state: STATE,
369
+ keptNpis: keptNpis.size,
370
+ recordCount: N,
371
+ geocoded: geo,
372
+ trainEM: TRAIN_EM,
373
+ addressFrequency,
374
+ progression,
375
+ defaultOutOfBox,
376
+ sweep,
377
+ best,
378
+ entityCount,
379
+ orgCount,
380
+ orgCoordCount,
381
+ orgH3Count,
382
+ fsNPI,
383
+ fsEntity,
384
+ fsOrg,
385
+ fsOrgCoord,
386
+ gbtNPI,
387
+ gbtEntity,
388
+ gbtOrg,
389
+ gbtOrgCoord,
390
+ gbtOrgH3,
391
+ candidate: cand,
392
+ h3Res: H3_RES,
393
+ geocodedNpis,
969
394
  })
970
395
 
971
- lines.push("")
972
-
973
- lines.push(
974
- `Inverse-frequency weighting uses the corpus-wide table (${addrCounts.size.toLocaleString()} distinct addresses ` +
975
- `over ${addrTotal.toLocaleString()} providers) to down-weight a crowded shared address; collapsing the redundant ` +
976
- `address-key + distance comparisons into one spatial signal (A1) removes the double-count that let a shared address ` +
977
- `over-vote a disagreeing name. The address-frequency + A1 baseline is F1 ${pct(progression[2]!.score.f1)}% at the ` +
978
- `default threshold; the **authorized-official discriminator** is roughly neutral there (${signed(100 * (bestLever.score.f1 - progression[2]!.score.f1))}) ` +
979
- `but enables a higher cutoff — it holds recall where the baseline alone collapses, reaching **${pct(best.score.f1)}%** at ` +
980
- `threshold ${best.t} (below), the first config past the baseline (#625).`
981
- )
982
-
983
- lines.push("")
984
-
985
- lines.push(
986
- `**Out-of-the-box (zero-config \`resolveEntities(records)\`, levers default-on #86):** F1 ` +
987
- `**${pct(defaultOutOfBox.score.f1)}%** on this sample — essentially the baseline. The default auto-computes the ` +
988
- `address-frequency table over the INPUT records, and this benchmark deliberately sub-samples ${N} records, so ` +
989
- `that table is too sparse to carry the inverse-frequency signal (a corpus statistic you can't synthesize from a ` +
990
- `slice). It's **not a regression** (≥ baseline, no over-merge added) — it's the honest floor when the input isn't ` +
991
- `corpus-scale. Fed the corpus-wide table (the \`+ inverse-address-frequency\` row above, what the CLI builds from ` +
992
- `the full source files) the SAME default reaches the **${pct(progression[2]!.score.f1)}%** baseline. On a full-dataset ` +
993
- `dedup the input IS the corpus, so zero-config reaches the baseline on its own.`
994
- )
995
-
996
- lines.push("")
997
- lines.push(`## With all levers on, across the link threshold (the secondary lever)`)
998
- lines.push("")
999
- lines.push(`| link threshold (bits) | precision | recall | F1 | ARI | clusters | over-merged |`)
1000
- lines.push(`|---:|---:|---:|---:|---:|---:|---:|`)
1001
-
1002
- for (const s of sweep) {
1003
- const star = s === best ? " ⭐" : ""
1004
-
1005
- lines.push(
1006
- `| ${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} |`
1007
- )
1008
- }
1009
-
1010
- lines.push("")
1011
-
1012
- lines.push(
1013
- best.t === 0
1014
- ? `Best F1 is at the **default threshold** (${pct(base.score.f1)}%): raising it only trades recall away faster ` +
1015
- `than it buys precision. So the threshold knob alone can't separate co-located distinct providers — the ` +
1016
- `over-merge is structural, in the comparison model, not the cutoff.`
1017
- : `Best F1 **${pct(best.score.f1)}%** (ARI ${best.score.ari.toFixed(3)}) at threshold ${best.t}, vs **${pct(base.score.f1)}%** at the ` +
1018
- `default — the threshold knob moves it ${(100 * (best.score.f1 - base.score.f1)).toFixed(0)}pp. Higher thresholds trade recall for precision.`
1019
- )
1020
-
1021
- lines.push("")
1022
- lines.push(`## Shape + where the errors are (at the default threshold)`)
1023
- lines.push("")
1024
- lines.push(`- records: ${N} · true entities (NPIs): ${kept.size} · recovered clusters: ${base.score.clusters}`)
1025
-
1026
- lines.push(
1027
- `- candidate pairs blocked: ${base.res.candidatePairs}${base.res.droppedBlocks.length ? ` · oversized blocks skipped: ${base.res.droppedBlocks.length}` : ""}`
1028
- )
1029
-
1030
- lines.push(
1031
- `- **Over-merge (precision):** ${base.score.overMergedClusters} clusters fuse ≥2 distinct NPIs (largest fuses ` +
1032
- `${base.score.maxNpisFused}; ${base.score.recordsInOverMerged} records) — **co-located providers sharing a clinic / ` +
1033
- `billing address**, linked by address agreement despite different names.`
1034
- )
1035
-
1036
- lines.push(
1037
- `- **Under-merge (recall):** ${base.score.splitNpis}/${kept.size} NPIs split across >1 cluster — records at distant ` +
1038
- `addresses (mailing vs practice) or with strong name drift the score didn't bridge.`
1039
- )
1040
-
1041
- lines.push("")
1042
- lines.push(`## Three truth grains — NPI → site → org-name (the over-segmentation correction)`)
1043
- lines.push("")
1044
-
1045
- lines.push(
1046
- `NPI-as-truth OVER-SEGMENTS: one org holds many NPIs, so the matcher's correct co-located merges are scored as ` +
1047
- `errors. Three yardsticks, same clusters: **NPI** (one entity per registration), **site** (subpart-flagged ` +
1048
- `collapse + split an NPI's distinct addresses), and **org-name** — the gold-set-validated truth: same NPI ⇒ ` +
1049
- `same entity (recall preserved) PLUS collapse co-located NPIs whose primary org names match (Jaccard ≥ ${ORG_TAU}), ` +
1050
- `with NO reliance on the subpart flag (the gold set showed it misses 37%). The same ${N} records carry ` +
1051
- `**${kept.size} NPI** → **${entityCount} site** → **${orgCount} org-name** classes. The org-name number is the ` +
1052
- `honest one: it stops charging the matcher for the same-org merges the gold set proved are correct.`
1053
- )
1054
-
1055
- lines.push("")
1056
- lines.push(`| config | truth | precision | recall | F1 | ΔF1 vs NPI | ARI | over-merged |`)
1057
- lines.push(`|---|---|---:|---:|---:|---:|---:|---:|`)
1058
-
1059
- const dualRow = (label: string, truth: string, s: Score, delta?: number) =>
1060
- lines.push(
1061
- `| ${label} | ${truth} | ${pct(s.precision)}% | ${pct(s.recall)}% | **${pct(s.f1)}%** | ${delta === undefined ? "—" : signed(100 * delta)} | ${s.ari.toFixed(3)} | ${s.overMergedClusters} |`
1062
- )
1063
-
1064
- dualRow("FS full stack", "NPI", fsNPI)
1065
- dualRow("FS full stack", "site", fsEntity, fsEntity.f1 - fsNPI.f1)
1066
- dualRow("FS full stack", "**org-name**", fsOrg, fsOrg.f1 - fsNPI.f1)
1067
- dualRow("FS full stack", "org-name (coord)", fsOrgCoord, fsOrgCoord.f1 - fsNPI.f1)
1068
- dualRow("GBT (shipped default)", "NPI", gbtNPI)
1069
- dualRow("GBT (shipped default)", "site", gbtEntity, gbtEntity.f1 - gbtNPI.f1)
1070
- dualRow("GBT (shipped default)", "**org-name**", gbtOrg, gbtOrg.f1 - gbtNPI.f1)
1071
- dualRow("GBT (shipped default)", "**org-name (coord)**", gbtOrgCoord, gbtOrgCoord.f1 - gbtNPI.f1)
1072
- dualRow("GBT (shipped default)", `org-name (H3 res ${H3_RES})`, gbtOrgH3, gbtOrgH3.f1 - gbtNPI.f1)
1073
-
1074
- if (cand) {
1075
- dualRow(cand.label, "NPI", cand.npi)
1076
- dualRow(cand.label, "**entity**", cand.entity, cand.entity.f1 - cand.npi.f1)
1077
- }
1078
-
1079
- lines.push("")
1080
-
1081
- lines.push(
1082
- `The F1 **climbs as the yardstick gets honest**: GBT **${pct(gbtNPI.f1)}% (NPI) → ${pct(gbtEntity.f1)}% (site) → ` +
1083
- `${pct(gbtOrg.f1)}% (org-name)**, the over-merge collapsing (${gbtNPI.overMergedClusters} → ${gbtOrg.overMergedClusters}) ` +
1084
- `and precision rising (${pct(gbtNPI.precision)}% → ${pct(gbtOrg.precision)}%). The clusters are IDENTICAL across the three ` +
1085
- `columns — the climb is purely the ruler ceasing to charge the matcher for the correct same-org merges the gold set proved ` +
1086
- `(\`2026-06-16-dedup-gold-set-tx120.md\`: 120/120 same org, 0 genuine over-merges).`
1087
- )
1088
-
1089
- lines.push("")
1090
-
1091
- lines.push(
1092
- `**Tier 2D — tightening the org-name ruler with the geocode coordinate.** The org-name truth above blocks by the address ` +
1093
- `STRING (\`addressFrequencyKey\`), so two records at one building whose text differs — \`1504 Taub LOOP\` vs ` +
1094
- `\`1504 Taub LP STE 100\` — key apart and the merge is still charged as an error. Block by the GEOCODED BUILDING instead ` +
1095
- `(union co-located NPIs within ${COLOCATION_KM * 1000} m whose org names agree, same Jaccard gate) and the truth tightens ` +
1096
- `further: GBT **org-name ${pct(gbtOrg.f1)}% → org-name-coord ${pct(gbtOrgCoord.f1)}%** ` +
1097
- `(${signed(100 * (gbtOrgCoord.f1 - gbtOrg.f1))}), ${orgCount} → ${orgCoordCount} classes, over ${geocodedNpis}/${kept.size} ` +
1098
- `geocoded NPIs. The string org-name F1 is a conservative LOWER bound; the coordinate one is tighter (the Jaccard gate ` +
1099
- `still blocks distinct co-located orgs). Both are honest — the coordinate is the geocode-first key.`
1100
- )
1101
-
1102
- lines.push("")
1103
-
1104
- lines.push(
1105
- `**H3-cell robustness check (#109).** Re-keying the same building-grain co-location on an H3 cell ` +
1106
- `(res ${H3_RES}) instead of the 50 m haversine radius — the deterministic, O(n) "geocode-first cell" the issue ` +
1107
- `suggested — gives GBT **org-name-h3 ${pct(gbtOrgH3.f1)}%** (${orgH3Count} classes), vs the haversine ` +
1108
- `${pct(gbtOrgCoord.f1)}% (${orgCoordCount}). ${
1109
- Math.abs(gbtOrgH3.f1 - gbtOrgCoord.f1) < BLOCKING_PARITY_TOLERANCE
1110
- ? "Within noise of the haversine grain — the ~" +
1111
- pct(gbtOrgCoord.f1) +
1112
- "% coord-grain F1 is robust to the co-location method, not an artifact of the 50 m threshold."
1113
- : "The two co-location methods differ by " +
1114
- signed(100 * (gbtOrgH3.f1 - gbtOrgCoord.f1)) +
1115
- " — the cell-vs-radius boundary handling shifts the count (a hard H3 boundary can split a same-building pair into adjacent cells)."
1116
- }`
1117
- )
1118
-
1119
- lines.push("")
1120
-
1121
- lines.push(
1122
- `**Takeaways:** (1) The dedup model's REAL quality is the **org-name F1 ~${pct(gbtOrg.f1)}%**, not the NPI-level ` +
1123
- `${pct(gbtNPI.f1)}% — the difference was NPI over-segmentation, not model error. (2) The #625 lever was the YARDSTICK, ` +
1124
- `not the scorer: the corroboration-feature experiment (reverted) couldn't move precision because the over-merge was ` +
1125
- `mostly correct. (3) The remaining org-name over-merge (${gbtOrg.overMergedClusters} clusters) is the genuine frontier — ` +
1126
- `small, approaching the ceiling's ~1.6% irreducible (\`2026-06-16-dedup-ceiling.md\`). (4) Trust the large eval: a 50-NPI ` +
1127
- `smoke misled on the site delta (+5–7pp vs this run's ±2pp).`
1128
- )
1129
-
1130
- lines.push("")
1131
-
1132
- lines.push(
1133
- `Caveats: the programmatic site-truth is CONSERVATIVE (collapses only NPPES-flagged subparts; unflagged same-org pairs still ` +
1134
- `read as over-merge), so it understates the subpart correction. A hand-adjudicated gold set on the ambiguous co-located + ` +
1135
- `two-site slice is the next refinement (#625).`
1136
- )
1137
-
1138
- lines.push("")
1139
- lines.push(`## Reading`)
1140
- lines.push("")
1141
-
1142
- lines.push(
1143
- `The geocode-first **foundation works**: **${pct(geo / N)}%** of addresses placed, blocking + clustering clean — the ` +
1144
- `geocoding (the Pelias/Nominatim-can't-do-this part) is not the bottleneck. The comparison-model levers reach the ` +
1145
- `address-frequency + A1 baseline at F1 **${pct(progression[2]!.score.f1)}%** (${signed(100 * (progression[2]!.score.f1 - baseline.score.f1))} over baseline): ` +
1146
- `inverse-frequency weighting restores full weight to a *rare* shared address (stitching a provider's name-drifted ` +
1147
- `records together — mostly recall) while down-weighting a *crowded* one, and the collapsed spatial signal (A1) drops ` +
1148
- `the address+distance double-count. What remains is **precision / over-merge** — ${bestLever.score.overMergedClusters} ` +
1149
- `clusters still fuse distinct co-located providers, because even one down-weighted spatial agreement can outvote a ` +
1150
- `disagreeing name. The lever search (#625) — two negatives, then the first positive: a name/org/phone ` +
1151
- `**corroboration gate** (A2/A3) — phone is an unreliable secondary identifier on NPPES (shared institutional ` +
1152
- `switchboard lines), so it over-links and falsely corroborates co-phone distinct providers; and **average-linkage ` +
1153
- `clustering** (A4) — the over-merged clusters are joined by STRONG shared-address edges, not weak bridges, so ` +
1154
- `average-linkage can't split them and only trades away name-drift recall. The over-merge is a **scoring** problem ` +
1155
- `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 ` +
1156
- `(taxonomy / license) or a learned scorer over the FS feature vector (#603) goes further. Config ` +
1157
- `dominates the model (the pre-registered finding) — tracked as #625 / the selective-model work (#602 / #603).`
1158
- )
1159
-
1160
- lines.push("")
1161
-
1162
- lines.push(
1163
- `NPI-as-truth is **conservative**: a cluster fusing two NPIs is a candidate "same entity, two NPIs" surfaced for ` +
1164
- `review, not an adjudicated error; an NPI split across genuinely-distant addresses is geo-first behaving correctly, ` +
1165
- `counted here as a recall miss. We resolve and report; interpretation is the consumer's.`
1166
- )
1167
-
1168
- lines.push("")
1169
-
1170
- const md = lines.join("\n")
1171
-
1172
396
  console.log(md)
1173
397
 
1174
398
  if (OUT_MD) {