@mailwoman/registry 9.1.0 → 9.3.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 (228) hide show
  1. package/README.md +2 -2
  2. package/{address-key.ts → lib/address-key.ts} +1 -1
  3. package/{geocode-handler.ts → lib/geocode-handler.ts} +7 -7
  4. package/{geojson.ts → lib/geojson.ts} +12 -6
  5. package/{index.ts → lib/index.ts} +10 -10
  6. package/{ingest.ts → lib/ingest.ts} +77 -69
  7. package/{learned-scorer.ts → lib/learned-scorer.ts} +1 -1
  8. package/{map-html.ts → lib/map-html.ts} +10 -16
  9. package/{reconcile.ts → lib/reconcile.ts} +9 -24
  10. package/{resolve.ts → lib/resolve.ts} +31 -13
  11. package/{tools → lib/tools}/coverage-reconciliation.ts +13 -15
  12. package/{tools → lib/tools}/cross-dataset-correlation.ts +64 -139
  13. package/{tools → lib/tools}/cross-source-threshold-sweep.ts +21 -32
  14. package/{tools → lib/tools}/dedup-ceiling.ts +33 -144
  15. package/{tools → lib/tools}/eval-geocoder.ts +10 -11
  16. package/{tools → lib/tools}/geocoder-namesake-probe.ts +5 -12
  17. package/{tools → lib/tools}/geocoder-vs-provided-coords.ts +12 -11
  18. package/lib/tools/gold-set-sample.ts +141 -0
  19. package/lib/tools/index.ts +31 -0
  20. package/{tools → lib/tools}/learned-scorer-clustering-eval.ts +71 -260
  21. package/{tools → lib/tools}/learned-scorer-crossstate-eval.ts +62 -245
  22. package/{tools → lib/tools}/learned-scorer-eval.ts +64 -263
  23. package/{tools → lib/tools}/matcher-scale.ts +5 -5
  24. package/lib/tools/nppes/org-name.ts +23 -0
  25. package/lib/tools/nppes/overmerge-packet.ts +94 -0
  26. package/lib/tools/nppes/report.ts +373 -0
  27. package/lib/tools/nppes/sample.ts +245 -0
  28. package/lib/tools/nppes/scoring.ts +114 -0
  29. package/lib/tools/nppes/settings.ts +102 -0
  30. package/lib/tools/nppes/truth-grains.ts +161 -0
  31. package/lib/tools/nppes-dedup-benchmark.ts +408 -0
  32. package/lib/tools/shared.ts +763 -0
  33. package/lib/tools/train-cross-gbt.ts +209 -0
  34. package/{tools → lib/tools}/train-gbt.ts +38 -156
  35. package/lib/tools/train-org-cross-gbt.ts +179 -0
  36. package/{tools → lib/tools}/txhhsc-to-oarow.ts +10 -28
  37. package/lib/tools/viz/browser.ts +50 -0
  38. package/{tools → lib/tools}/viz/cross-dataset-map.ts +16 -39
  39. package/{tools → lib/tools}/viz/geocode-first-surface.ts +13 -39
  40. package/{tools → lib/tools}/viz/render-map.ts +10 -23
  41. package/lib/tools/viz/render.ts +98 -0
  42. package/{tools → lib/tools}/viz/source-provenance-map.ts +20 -39
  43. package/{tools → lib/tools}/viz/yardstick-figure.ts +6 -5
  44. package/{types.ts → lib/types.ts} +10 -1
  45. package/out/address-key.d.ts +1 -1
  46. package/out/address-key.d.ts.map +1 -1
  47. package/out/address-key.js.map +1 -1
  48. package/out/geocode-handler.d.ts +6 -6
  49. package/out/geocode-handler.d.ts.map +1 -1
  50. package/out/geocode-handler.js +6 -6
  51. package/out/geocode-handler.js.map +1 -1
  52. package/out/geojson.d.ts +7 -2
  53. package/out/geojson.d.ts.map +1 -1
  54. package/out/geojson.js +8 -5
  55. package/out/geojson.js.map +1 -1
  56. package/out/index.d.ts +10 -10
  57. package/out/index.d.ts.map +1 -1
  58. package/out/index.js +10 -10
  59. package/out/index.js.map +1 -1
  60. package/out/ingest.d.ts +64 -46
  61. package/out/ingest.d.ts.map +1 -1
  62. package/out/ingest.js +33 -46
  63. package/out/ingest.js.map +1 -1
  64. package/out/learned-scorer.d.ts +1 -1
  65. package/out/learned-scorer.d.ts.map +1 -1
  66. package/out/learned-scorer.js.map +1 -1
  67. package/out/map-html.d.ts +4 -4
  68. package/out/map-html.d.ts.map +1 -1
  69. package/out/map-html.js +6 -11
  70. package/out/map-html.js.map +1 -1
  71. package/out/models/crosssource-gbt-en-us.d.ts.map +1 -1
  72. package/out/models/crosssource-gbt-en-us.js.map +1 -1
  73. package/out/models/dedup-gbt-en-us.d.ts.map +1 -1
  74. package/out/models/dedup-gbt-en-us.js.map +1 -1
  75. package/out/models/org-crosssource-gbt-en-us.d.ts.map +1 -1
  76. package/out/models/org-crosssource-gbt-en-us.js.map +1 -1
  77. package/out/reconcile.d.ts +6 -1
  78. package/out/reconcile.d.ts.map +1 -1
  79. package/out/reconcile.js +7 -21
  80. package/out/reconcile.js.map +1 -1
  81. package/out/resolve.d.ts +19 -7
  82. package/out/resolve.d.ts.map +1 -1
  83. package/out/resolve.js +20 -6
  84. package/out/resolve.js.map +1 -1
  85. package/out/tools/coverage-reconciliation.d.ts +1 -1
  86. package/out/tools/coverage-reconciliation.d.ts.map +1 -1
  87. package/out/tools/coverage-reconciliation.js +12 -12
  88. package/out/tools/coverage-reconciliation.js.map +1 -1
  89. package/out/tools/cross-dataset-correlation.d.ts +4 -4
  90. package/out/tools/cross-dataset-correlation.d.ts.map +1 -1
  91. package/out/tools/cross-dataset-correlation.js +60 -111
  92. package/out/tools/cross-dataset-correlation.js.map +1 -1
  93. package/out/tools/cross-source-threshold-sweep.d.ts +2 -2
  94. package/out/tools/cross-source-threshold-sweep.d.ts.map +1 -1
  95. package/out/tools/cross-source-threshold-sweep.js +19 -27
  96. package/out/tools/cross-source-threshold-sweep.js.map +1 -1
  97. package/out/tools/dedup-ceiling.d.ts.map +1 -1
  98. package/out/tools/dedup-ceiling.js +36 -118
  99. package/out/tools/dedup-ceiling.js.map +1 -1
  100. package/out/tools/eval-geocoder.d.ts +9 -13
  101. package/out/tools/eval-geocoder.d.ts.map +1 -1
  102. package/out/tools/eval-geocoder.js +2 -2
  103. package/out/tools/eval-geocoder.js.map +1 -1
  104. package/out/tools/geocoder-namesake-probe.d.ts +2 -2
  105. package/out/tools/geocoder-namesake-probe.d.ts.map +1 -1
  106. package/out/tools/geocoder-namesake-probe.js +4 -8
  107. package/out/tools/geocoder-namesake-probe.js.map +1 -1
  108. package/out/tools/geocoder-vs-provided-coords.d.ts +1 -1
  109. package/out/tools/geocoder-vs-provided-coords.d.ts.map +1 -1
  110. package/out/tools/geocoder-vs-provided-coords.js +11 -9
  111. package/out/tools/geocoder-vs-provided-coords.js.map +1 -1
  112. package/out/tools/gold-set-sample.d.ts +5 -5
  113. package/out/tools/gold-set-sample.d.ts.map +1 -1
  114. package/out/tools/gold-set-sample.js +37 -121
  115. package/out/tools/gold-set-sample.js.map +1 -1
  116. package/out/tools/index.d.ts +24 -29
  117. package/out/tools/index.d.ts.map +1 -1
  118. package/out/tools/index.js +24 -29
  119. package/out/tools/index.js.map +1 -1
  120. package/out/tools/learned-scorer-clustering-eval.d.ts +1 -1
  121. package/out/tools/learned-scorer-clustering-eval.d.ts.map +1 -1
  122. package/out/tools/learned-scorer-clustering-eval.js +35 -170
  123. package/out/tools/learned-scorer-clustering-eval.js.map +1 -1
  124. package/out/tools/learned-scorer-crossstate-eval.d.ts +5 -5
  125. package/out/tools/learned-scorer-crossstate-eval.d.ts.map +1 -1
  126. package/out/tools/learned-scorer-crossstate-eval.js +44 -166
  127. package/out/tools/learned-scorer-crossstate-eval.js.map +1 -1
  128. package/out/tools/learned-scorer-eval.d.ts +1 -1
  129. package/out/tools/learned-scorer-eval.d.ts.map +1 -1
  130. package/out/tools/learned-scorer-eval.js +37 -173
  131. package/out/tools/learned-scorer-eval.js.map +1 -1
  132. package/out/tools/matcher-scale.d.ts.map +1 -1
  133. package/out/tools/matcher-scale.js +5 -5
  134. package/out/tools/matcher-scale.js.map +1 -1
  135. package/out/tools/nppes/org-name.d.ts +21 -0
  136. package/out/tools/nppes/org-name.d.ts.map +1 -0
  137. package/out/tools/nppes/org-name.js +13 -0
  138. package/out/tools/nppes/org-name.js.map +1 -0
  139. package/out/tools/nppes/overmerge-packet.d.ts +39 -0
  140. package/out/tools/nppes/overmerge-packet.d.ts.map +1 -0
  141. package/out/tools/nppes/overmerge-packet.js +55 -0
  142. package/out/tools/nppes/overmerge-packet.js.map +1 -0
  143. package/out/tools/nppes/report.d.ts +93 -0
  144. package/out/tools/nppes/report.d.ts.map +1 -0
  145. package/out/tools/nppes/report.js +186 -0
  146. package/out/tools/nppes/report.js.map +1 -0
  147. package/out/tools/nppes/sample.d.ts +90 -0
  148. package/out/tools/nppes/sample.d.ts.map +1 -0
  149. package/out/tools/nppes/sample.js +131 -0
  150. package/out/tools/nppes/sample.js.map +1 -0
  151. package/out/tools/nppes/scoring.d.ts +36 -0
  152. package/out/tools/nppes/scoring.d.ts.map +1 -0
  153. package/out/tools/nppes/scoring.js +80 -0
  154. package/out/tools/nppes/scoring.js.map +1 -0
  155. package/out/tools/nppes/settings.d.ts +38 -0
  156. package/out/tools/nppes/settings.d.ts.map +1 -0
  157. package/out/tools/nppes/settings.js +79 -0
  158. package/out/tools/nppes/settings.js.map +1 -0
  159. package/out/tools/nppes/truth-grains.d.ts +50 -0
  160. package/out/tools/nppes/truth-grains.d.ts.map +1 -0
  161. package/out/tools/nppes/truth-grains.js +123 -0
  162. package/out/tools/nppes/truth-grains.js.map +1 -0
  163. package/out/tools/nppes-dedup-benchmark.d.ts +7 -3
  164. package/out/tools/nppes-dedup-benchmark.d.ts.map +1 -1
  165. package/out/tools/nppes-dedup-benchmark.js +106 -673
  166. package/out/tools/nppes-dedup-benchmark.js.map +1 -1
  167. package/out/tools/shared.d.ts +244 -7
  168. package/out/tools/shared.d.ts.map +1 -1
  169. package/out/tools/shared.js +353 -21
  170. package/out/tools/shared.js.map +1 -1
  171. package/out/tools/train-cross-gbt.d.ts +7 -7
  172. package/out/tools/train-cross-gbt.d.ts.map +1 -1
  173. package/out/tools/train-cross-gbt.js +47 -145
  174. package/out/tools/train-cross-gbt.js.map +1 -1
  175. package/out/tools/train-gbt.d.ts +7 -7
  176. package/out/tools/train-gbt.d.ts.map +1 -1
  177. package/out/tools/train-gbt.js +31 -111
  178. package/out/tools/train-gbt.js.map +1 -1
  179. package/out/tools/train-org-cross-gbt.d.ts +7 -5
  180. package/out/tools/train-org-cross-gbt.d.ts.map +1 -1
  181. package/out/tools/train-org-cross-gbt.js +45 -141
  182. package/out/tools/train-org-cross-gbt.js.map +1 -1
  183. package/out/tools/txhhsc-to-oarow.d.ts +2 -2
  184. package/out/tools/txhhsc-to-oarow.d.ts.map +1 -1
  185. package/out/tools/txhhsc-to-oarow.js +9 -23
  186. package/out/tools/txhhsc-to-oarow.js.map +1 -1
  187. package/out/tools/viz/browser.d.ts +34 -0
  188. package/out/tools/viz/browser.d.ts.map +1 -0
  189. package/out/tools/viz/browser.js +33 -0
  190. package/out/tools/viz/browser.js.map +1 -0
  191. package/out/tools/viz/cross-dataset-map.d.ts +4 -25
  192. package/out/tools/viz/cross-dataset-map.d.ts.map +1 -1
  193. package/out/tools/viz/cross-dataset-map.js +12 -33
  194. package/out/tools/viz/cross-dataset-map.js.map +1 -1
  195. package/out/tools/viz/geocode-first-surface.d.ts +6 -35
  196. package/out/tools/viz/geocode-first-surface.d.ts.map +1 -1
  197. package/out/tools/viz/geocode-first-surface.js +10 -37
  198. package/out/tools/viz/geocode-first-surface.js.map +1 -1
  199. package/out/tools/viz/render-map.d.ts +3 -6
  200. package/out/tools/viz/render-map.d.ts.map +1 -1
  201. package/out/tools/viz/render-map.js +9 -19
  202. package/out/tools/viz/render-map.js.map +1 -1
  203. package/out/tools/viz/render.d.ts +4 -9
  204. package/out/tools/viz/render.d.ts.map +1 -1
  205. package/out/tools/viz/render.js +24 -39
  206. package/out/tools/viz/render.js.map +1 -1
  207. package/out/tools/viz/source-provenance-map.d.ts +4 -24
  208. package/out/tools/viz/source-provenance-map.d.ts.map +1 -1
  209. package/out/tools/viz/source-provenance-map.js +12 -32
  210. package/out/tools/viz/source-provenance-map.js.map +1 -1
  211. package/out/tools/viz/yardstick-figure.d.ts +2 -2
  212. package/out/tools/viz/yardstick-figure.d.ts.map +1 -1
  213. package/out/tools/viz/yardstick-figure.js +5 -4
  214. package/out/tools/viz/yardstick-figure.js.map +1 -1
  215. package/out/types.d.ts +11 -1
  216. package/out/types.d.ts.map +1 -1
  217. package/out/types.js.map +1 -1
  218. package/package.json +180 -11
  219. package/tools/gold-set-sample.ts +0 -252
  220. package/tools/index.ts +0 -36
  221. package/tools/nppes-dedup-benchmark.ts +0 -1180
  222. package/tools/shared.ts +0 -160
  223. package/tools/train-cross-gbt.ts +0 -358
  224. package/tools/train-org-cross-gbt.ts +0 -329
  225. package/tools/viz/render.ts +0 -113
  226. /package/{models → lib/models}/crosssource-gbt-en-us.ts +0 -0
  227. /package/{models → lib/models}/dedup-gbt-en-us.ts +0 -0
  228. /package/{models → lib/models}/org-crosssource-gbt-en-us.ts +0 -0
@@ -35,22 +35,15 @@
35
35
  * [--data-root <dir>] [--seed 1] [--out-md <md>]`
36
36
  */
37
37
 
38
- import { writeFileSync } from "node:fs"
39
-
40
- import { dataRootPath, makeLcg } from "@mailwoman/core/utils"
38
+ import { dataRootPath } from "@mailwoman/core/data-root"
39
+ import { writeLocalFile } from "@mailwoman/core/fs/writers"
40
+ import { makeLcg } from "@mailwoman/core/random"
41
41
  import { agreementPattern, block, estimateParameters, gbtScore, scorePair, trainGBT } from "@mailwoman/match"
42
- import {
43
- addressFrequencyKey,
44
- buildDefaultModel,
45
- defaultBlockingKeys,
46
- ingestRows,
47
- streamRows,
48
- type ColumnMapping,
49
- type SourceRecord,
50
- } from "@mailwoman/registry"
51
-
52
- import type { EvalGeocoderFactory } from "./eval-geocoder.ts"
53
- import { addr, MIN_GROUP_SIZE, norm, NPPES_COLUMNS as C, TRAINING_EPOCHS } from "./shared.ts"
42
+
43
+ import { buildDefaultModel, createMatchFeaturizer, defaultBlockingKeys, ingestRows, type ColumnMapping } from "#index"
44
+ import type { EvalGeocoderFactory } from "#tools/eval-geocoder"
45
+ import { buildNPPESSample } from "#tools/nppes/sample"
46
+ import { mean, pct, sgn, stateOption, std, trainLogisticRegression } from "#tools/shared"
54
47
 
55
48
  /**
56
49
  * Smallest mean gap counted as a real difference rather than seed noise.
@@ -77,11 +70,6 @@ const STRONG_EVIDENCE_Z = 3
77
70
  */
78
71
  const TRAIN_SPLIT_FRACTION = 0.67
79
72
 
80
- /**
81
- * Highest k swept when scanning cluster counts.
82
- */
83
- const MAX_K = 32
84
-
85
73
  /**
86
74
  * Options for {@linkcode scorerPairwiseEval}.
87
75
  */
@@ -116,115 +104,6 @@ export interface ScorerPairwiseEvalOptions {
116
104
  outMd?: string
117
105
  }
118
106
 
119
- interface MessyRow {
120
- npi: string
121
- name: string
122
- org: string
123
- address: string
124
- }
125
-
126
- /**
127
- * The address-frequency table the collapsed-spatial model needs: how common each normalized address is.
128
- */
129
- interface AddressFrequency {
130
- total: number
131
- distinct: number
132
- frequency: (v: string) => number
133
- }
134
-
135
- /**
136
- * One full registry pass: the NPI-keyed messy rows (primary name + every other-name alias + the mailing address when it
137
- * differs) and the address-frequency table, built together because both want the same scan. Same generation the dedup
138
- * benchmark uses — the two evals must see identical inputs to be comparable.
139
- */
140
- async function generateMessyRows(paths: {
141
- registry: string
142
- otherNames: string
143
- state: string
144
- npis: number
145
- report?: (line: string) => void
146
- }): Promise<{ rows: MessyRow[]; keptNPIs: Set<string>; addressFrequency: AddressFrequency }> {
147
- const { registry: REGISTRY, otherNames: OTHER_NAMES, state: STATE, npis: NPIS, report } = paths
148
- report?.("[A] streaming other-names…")
149
- const altNames = new Map<string, string[]>()
150
-
151
- for await (const r of streamRows(OTHER_NAMES)) {
152
- const npi = norm(r[C.npi])
153
- const alt = norm(r[C.otherOrg])
154
-
155
- if (!npi || !alt) continue
156
- const list = altNames.get(npi) ?? []
157
-
158
- if (list.length < MIN_GROUP_SIZE) {
159
- list.push(alt)
160
- }
161
-
162
- altNames.set(npi, list)
163
- }
164
-
165
- report?.(`[B] full registry pass: address-frequency table + ${NPIS} ${STATE} sample…`)
166
- const rows: MessyRow[] = []
167
- const kept = new Set<string>()
168
- const addrCounts = new Map<string, number>()
169
- let addrTotal = 0
170
- let scanned = 0
171
-
172
- for await (const r of streamRows(REGISTRY)) {
173
- if (++scanned % 1_000_000 === 0) {
174
- report?.(` scanned ${scanned / 1e6}M, kept ${kept.size}`)
175
- }
176
-
177
- const practice = addr(r[C.pAddr]!, r[C.pCity]!, r[C.pState]!, r[C.pZip]!)
178
-
179
- if (practice) {
180
- const k = addressFrequencyKey(practice)
181
- addrCounts.set(k, (addrCounts.get(k) ?? 0) + 1)
182
-
183
- addrTotal++
184
- }
185
-
186
- const npi = norm(r[C.npi])
187
-
188
- if (
189
- kept.size < NPIS &&
190
- npi &&
191
- !kept.has(npi) &&
192
- altNames.has(npi) &&
193
- practice &&
194
- norm(r[C.pState]).toUpperCase() === STATE
195
- ) {
196
- const isOrg = norm(r[C.entityType]) === "2"
197
- const primaryName = isOrg ? norm(r[C.orgLegal]) : `${norm(r[C.first])} ${norm(r[C.last])}`.trim()
198
-
199
- if (primaryName) {
200
- const org = isOrg ? norm(r[C.orgLegal]) : ""
201
- kept.add(npi)
202
- rows.push({ npi, name: primaryName, org, address: practice })
203
-
204
- for (const alt of altNames.get(npi)!) {
205
- rows.push({ npi, name: alt, org: alt, address: practice })
206
- }
207
-
208
- const mailing = addr(r[C.mAddr]!, r[C.mCity]!, r[C.mState]!, r[C.mZip]!)
209
-
210
- if (mailing && mailing !== practice) {
211
- rows.push({ npi, name: primaryName, org, address: mailing })
212
- }
213
- }
214
- }
215
- }
216
-
217
- const addressFrequency = {
218
- total: addrTotal,
219
- distinct: addrCounts.size,
220
- frequency: (v: string) => (v ? (addrCounts.get(addressFrequencyKey(v)) ?? 0) / addrTotal : 0),
221
- }
222
-
223
- report?.(` ${kept.size} NPIs → ${rows.length} records`)
224
-
225
- return { rows, keptNPIs: kept, addressFrequency }
226
- }
227
-
228
107
  /**
229
108
  * Learned-scorer pairwise probe (#603) — see the module doc. Emits the markdown report to stdout.
230
109
  */
@@ -233,7 +112,7 @@ export async function scorerPairwiseEval(
233
112
  report?: (line: string) => void
234
113
  ): Promise<{ markdown: string }> {
235
114
  const SOURCES = options.sources || dataRootPath("record-matcher", "sources")
236
- const STATE = (options.state || "TX").toUpperCase()
115
+ const STATE = stateOption(options)
237
116
  const NPIS = options.npis ?? 1500
238
117
  const SEED = options.seed ?? 1
239
118
  const OUT_MD = options.outMd || ""
@@ -241,24 +120,31 @@ export async function scorerPairwiseEval(
241
120
  const REGISTRY = `${SOURCES}/nppes_npi-registry_20260607.tsv`
242
121
  const OTHER_NAMES = `${SOURCES}/nppes_other-names_20260607.tsv`
243
122
 
244
- // --- Data-gen: same NPI-keyed records as the dedup benchmark. ---
245
- const { rows, keptNPIs, addressFrequency } = await generateMessyRows({
246
- registry: REGISTRY,
247
- otherNames: OTHER_NAMES,
248
- state: STATE,
249
- npis: NPIS,
250
- report,
251
- })
123
+ // --- Data-gen: the same NPI-keyed records as the dedup benchmark (the SHARED sample builder). ---
124
+ const { rows, keptNpis, addressFrequency } = await buildNPPESSample(
125
+ { registryPath: REGISTRY, otherNamesPath: OTHER_NAMES, state: STATE, maxNpis: NPIS },
126
+ report
127
+ )
252
128
 
253
129
  report?.("[C] geocoding…")
254
130
  const geocoder = await options.createGeocoder()
255
- const mapping: ColumnMapping = { id: "npi", name: "name", organization: "org", address: "address", source: "nppes" }
256
131
 
257
- const records = await ingestRows(rows as unknown as Record<string, string>[], mapping, {
258
- geocodeAddress: geocoder.seam,
132
+ // `auth`/`taxonomy` ride as attributes so the SHARED featurizer's #625 roll-up features can read the
133
+ // authorized official; the FS arm ignores them (no discriminators configured).
134
+ const mapping: ColumnMapping = {
135
+ id: "npi",
136
+ name: "name",
137
+ organization: "org",
138
+ address: "address",
139
+ attributes: { authorizedOfficial: "auth", taxonomy: "taxonomy" },
140
+ source: "nppes",
141
+ }
142
+
143
+ const records = await ingestRows(rows, mapping, {
144
+ geocodeAddress: geocoder.geocodeAddress,
259
145
  })
260
146
 
261
- geocoder.close()
147
+ geocoder[Symbol.dispose]()
262
148
 
263
149
  // --- Block + feature extraction. The model (collapsed spatial + address-frequency) defines the
264
150
  // comparisons; EM-fit it for the FS baseline. ---
@@ -268,44 +154,8 @@ export async function scorerPairwiseEval(
268
154
  const patterns = pairs.map(([a, b]) => agreementPattern(model.comparisons, a, b))
269
155
  const fsModel = estimateParameters(model, patterns).model
270
156
 
271
- // Level counts per comparison (for one-hot). Index -1 (missing) → all-zero block.
272
- const levelCounts = model.comparisons.map((c) => c.levels.length)
273
- const compIndex = Object.fromEntries(model.comparisons.map((c, i) => [c.name, i]))
274
- const spatialI = compIndex["spatial"]!
275
- const givenI = compIndex["given"]!
276
- const familyI = compIndex["family"]!
277
- const orgI = compIndex["organization"]!
278
- const lastLevel = (i: number) => levelCounts[i]! - 1
279
-
280
- // the "different"/"far" catch-all level
281
-
282
- /**
283
- * Feature vector for a pair: one-hot agreement levels + the over-merge interactions + address crowdedness.
284
- */
285
- function features(pat: number[], a: SourceRecord): number[] {
286
- const f: number[] = []
287
-
288
- for (let i = 0; i < pat.length; i++) {
289
- const lvl = pat[i]!
290
-
291
- for (let l = 0; l < levelCounts[i]!; l++) {
292
- f.push(lvl === l ? 1 : 0)
293
- }
294
- }
295
-
296
- // Interaction: co-located (spatial exact = level 0) AND the names/org disagree (catch-all level).
297
- const spatialExact = pat[spatialI] === 0 ? 1 : 0
298
- const nameDisagree = pat[givenI] === lastLevel(givenI) && pat[familyI] === lastLevel(familyI) ? 1 : 0
299
- const orgDisagree = pat[orgI] === lastLevel(orgI) ? 1 : 0
300
- f.push(spatialExact * nameDisagree) // the over-merge signature: same place, names disagree
301
- f.push(spatialExact * orgDisagree)
302
- // Address crowdedness (how shared this address is) — high → "same address" is weak evidence.
303
- const freq = a.address?.raw ? addressFrequency.frequency(a.address.raw) : 0
304
- f.push(Math.min(1, freq * 1000))
305
-
306
- // scale into a usable range
307
- return f
308
- }
157
+ // The SHARED production featurizer (createMatchFeaturizer) — train ≡ eval ≡ inference, one definition.
158
+ const featurize = createMatchFeaturizer({ comparisons: model.comparisons, addressFrequency })
309
159
 
310
160
  interface Sample {
311
161
  x: number[]
@@ -327,8 +177,6 @@ export async function scorerPairwiseEval(
327
177
  gbtScored: Scored[]
328
178
  }
329
179
 
330
- const sigmoid = (z: number) => 1 / (1 + Math.exp(-Math.max(-30, Math.min(30, z))))
331
-
332
180
  /**
333
181
  * One train/test split (by NPI): train the L2 logistic regression on the train pairs, then score the held-out test
334
182
  * pairs with both the LR and the EM-fitted FS scorer. The FS model is seed-independent (fit unsupervised on ALL
@@ -338,14 +186,14 @@ export async function scorerPairwiseEval(
338
186
  const rnd = makeLcg(seed || 1)
339
187
  const npiSplit = new Map<string, "train" | "test">()
340
188
 
341
- for (const npi of keptNPIs) {
189
+ for (const npi of keptNpis) {
342
190
  npiSplit.set(npi, rnd() < TRAIN_SPLIT_FRACTION ? "train" : "test")
343
191
  }
344
192
 
345
193
  const train: Sample[] = []
346
194
  const test: Sample[] = []
347
195
 
348
- pairs.forEach(([a, b], i) => {
196
+ pairs.forEach(([a, b]) => {
349
197
  const sa = npiSplit.get(a.id)
350
198
  const sb = npiSplit.get(b.id)
351
199
 
@@ -353,7 +201,7 @@ export async function scorerPairwiseEval(
353
201
 
354
202
  // cross-split or unknown → drop (no leakage)
355
203
  const sample: Sample = {
356
- x: features(patterns[i]!, a),
204
+ x: featurize(a, b),
357
205
  y: a.id === b.id ? 1 : 0,
358
206
  fs: scorePair(fsModel, a, b).weight,
359
207
  }
@@ -361,58 +209,23 @@ export async function scorerPairwiseEval(
361
209
  })
362
210
 
363
211
  const dim = train[0]?.x.length ?? 0
364
-
365
- // L2-regularized logistic regression (batch gradient descent), rare class up-weighted.
366
- const w = new Array<number>(dim).fill(0)
367
- let bias = 0
368
- const lrate = 0.1
369
- const l2 = 1e-3
370
212
  const posWeight = train.filter((s) => s.y === 1).length / Math.max(1, train.length)
213
+ const sampleWeights = train.map((s) => (s.y === 1 ? 1 - posWeight : posWeight))
371
214
 
372
- for (let epoch = 0; epoch < TRAINING_EPOCHS; epoch++) {
373
- const gw = new Array<number>(dim).fill(0)
374
- let gb = 0
375
-
376
- for (const s of train) {
377
- let z = bias
378
-
379
- for (let j = 0; j < dim; j++) {
380
- z += w[j]! * s.x[j]!
381
- }
382
-
383
- const p = sigmoid(z)
384
- const sampleW = s.y === 1 ? 1 - posWeight : posWeight
385
- const err = (p - s.y) * sampleW
386
-
387
- for (let j = 0; j < dim; j++) {
388
- gw[j]! += err * s.x[j]!
389
- }
390
-
391
- gb += err
392
- }
393
-
394
- for (let j = 0; j < dim; j++) {
395
- w[j]! -= lrate * (gw[j]! / train.length + l2 * w[j]!)
396
- }
397
-
398
- bias -= lrate * (gb / train.length)
399
- }
400
-
401
- const lrScore = (x: number[]) => {
402
- let z = bias
403
-
404
- for (let j = 0; j < x.length; j++) {
405
- z += w[j]! * x[j]!
406
- }
407
-
408
- return z
409
- }
215
+ // L2-regularized logistic regression (batch gradient descent), rare class up-weighted — the
216
+ // SHARED trainer.
217
+ const lrScore = trainLogisticRegression(
218
+ train.map((s) => s.x),
219
+ train.map((s) => s.y),
220
+ sampleWeights,
221
+ dim
222
+ )
410
223
 
411
224
  // Gradient-boosted trees on the SAME train pairs + class weights — the non-linear arm.
412
225
  const gbt = trainGBT(
413
226
  train.map((s) => s.x),
414
227
  train.map((s) => s.y),
415
- train.map((s) => (s.y === 1 ? 1 - posWeight : posWeight)),
228
+ sampleWeights,
416
229
  { rounds: 120, depth: 3, lr: 0.3, minLeaf: 20 }
417
230
  )
418
231
 
@@ -492,13 +305,6 @@ export async function scorerPairwiseEval(
492
305
  report?.("[E] training across seeds…")
493
306
  const SEEDS = options.seeds ?? 8
494
307
  const splits = Array.from({ length: SEEDS }, (_, k) => runSplit(SEED + k))
495
- const mean = (xs: number[]) => xs.reduce((a, b) => a + b, 0) / Math.max(1, xs.length)
496
-
497
- const std = (xs: number[]) => {
498
- const m = mean(xs)
499
-
500
- return Math.sqrt(mean(xs.map((x) => (x - m) ** 2)))
501
- }
502
308
 
503
309
  const fsAucs = splits.map((r) => auc(r.fsScored))
504
310
  const lrAucs = splits.map((r) => auc(r.lrScored))
@@ -506,23 +312,22 @@ export async function scorerPairwiseEval(
506
312
  const fsF1s = splits.map((r) => bestF1(r.fsScored).f1)
507
313
  const lrF1s = splits.map((r) => bestF1(r.lrScored).f1)
508
314
  const lrWins = deltas.filter((d) => d > 0).length
509
- const meanDelta = mean(deltas)
510
- const avgTestN = mean(splits.map((r) => r.testN))
511
- const avgTestPos = mean(splits.map((r) => r.lrScored.filter((d) => d.y === 1).length))
315
+ const meanDelta = mean(deltas)!
316
+ const avgTestN = mean(splits.map((r) => r.testN))!
317
+ const avgTestPos = mean(splits.map((r) => r.lrScored.filter((d) => d.y === 1).length))!
512
318
  const seMean = std(deltas) / Math.sqrt(SEEDS) // standard error of the mean ΔAUC
513
319
  const zScore = seMean > 0 ? meanDelta / seMean : 0 // ΔAUC in standard errors above zero
514
- const f1Delta = mean(lrF1s) - mean(fsF1s) // operating-point F1 gain (LR − FS)
320
+ const f1Delta = mean(lrF1s)! - mean(fsF1s)! // operating-point F1 gain (LR − FS)
515
321
  const unanimous = lrWins === SEEDS
516
322
  // GBT (non-linear) arm.
517
323
  const gbtAucs = splits.map((r) => auc(r.gbtScored))
518
324
  const gbtF1s = splits.map((r) => bestF1(r.gbtScored).f1)
519
325
  const gbtVsFs = splits.map((_, i) => gbtAucs[i]! - fsAucs[i]!)
520
326
  const gbtVsLr = splits.map((_, i) => gbtAucs[i]! - lrAucs[i]!)
521
- const gbtBeatsFs = gbtVsFs.filter((d) => d > 0).length
522
327
  const gbtBeatsLr = gbtVsLr.filter((d) => d > 0).length
523
- const meanGbtVsFs = mean(gbtVsFs)
524
- const meanGbtVsLr = mean(gbtVsLr)
525
- const f1DeltaGbt = mean(gbtF1s) - mean(fsF1s)
328
+ const meanGbtVsFs = mean(gbtVsFs)!
329
+ const meanGbtVsLr = mean(gbtVsLr)!
330
+ const f1DeltaGbt = mean(gbtF1s)! - mean(fsF1s)!
526
331
 
527
332
  // operating-point F1 gain (GBT − FS)
528
333
  for (const r of splits) {
@@ -537,21 +342,17 @@ export async function scorerPairwiseEval(
537
342
  }
538
343
 
539
344
  report?.(
540
- ` mean/${SEEDS} — FS ${mean(fsAucs).toFixed(4)} LR ${mean(lrAucs).toFixed(4)} (Δ${meanDelta >= 0 ? "+" : ""}${meanDelta.toFixed(4)}) ` +
541
- `GBT ${mean(gbtAucs).toFixed(4)} (Δ${meanGbtVsFs >= 0 ? "+" : ""}${meanGbtVsFs.toFixed(4)} vs FS, ` +
345
+ ` mean/${SEEDS} — FS ${mean(fsAucs)!.toFixed(4)} LR ${mean(lrAucs)!.toFixed(4)} (Δ${meanDelta >= 0 ? "+" : ""}${meanDelta.toFixed(4)}) ` +
346
+ `GBT ${mean(gbtAucs)!.toFixed(4)} (Δ${meanGbtVsFs >= 0 ? "+" : ""}${meanGbtVsFs.toFixed(4)} vs FS, ` +
542
347
  `${meanGbtVsLr >= 0 ? "+" : ""}${meanGbtVsLr.toFixed(4)} vs LR)`
543
348
  )
544
349
 
545
- // NOTE(phase4): local pct keeps the fraction-in/no-%-suffix shape — not core formatPercent's
546
- // numerator/denominator contract (call sites append their own "%").
547
- const pct = (x: number) => (100 * x).toFixed(1)
548
350
  const f4 = (x: number) => x.toFixed(4)
549
- const sgn = (x: number) => (x >= 0 ? "+" : "")
550
351
 
551
352
  const lines: string[] = [
552
353
  `# Learned-scorer probe (#603) — does a model beat Fellegi-Sunter on the FS feature vector?`,
553
354
  "",
554
- `_Generated by \`mailwoman registry scorer-eval pairwise\`. ${keptNPIs.size} ${STATE} NPIs → ${records.length} ` +
355
+ `_Generated by \`mailwoman registry scorer-eval pairwise\`. ${keptNpis.size} ${STATE} NPIs → ${records.length} ` +
555
356
  `records, geocoded. Candidate pairs are split BY NPI into train/test (no NPI's records cross the split), repeated ` +
556
357
  `over ${SEEDS} seeds to bound split variance. Two learned scorers over the FS agreement pattern + over-merge ` +
557
358
  `interaction features (spatial-exact × name-disagree, spatial-exact × org-disagree, address crowdedness) — features ` +
@@ -564,15 +365,15 @@ export async function scorerPairwiseEval(
564
365
  "",
565
366
  `| scorer | ROC-AUC (mean±std) | ΔAUC vs FS | best F1 (mean) |`,
566
367
  `|---|---:|---:|---:|`,
567
- `| Fellegi-Sunter (EM-fit) | ${f4(mean(fsAucs))} ± ${f4(std(fsAucs))} | — | ${pct(mean(fsF1s))}% |`,
568
- `| logistic regression (linear) | ${f4(mean(lrAucs))} ± ${f4(std(lrAucs))} | ${sgn(meanDelta)}${f4(meanDelta)} | ${pct(mean(lrF1s))}% |`,
569
- `| **gradient-boosted trees** | **${f4(mean(gbtAucs))} ± ${f4(std(gbtAucs))}** | **${sgn(meanGbtVsFs)}${f4(meanGbtVsFs)}** | **${pct(mean(gbtF1s))}%** |`,
368
+ `| Fellegi-Sunter (EM-fit) | ${f4(mean(fsAucs)!)} ± ${f4(std(fsAucs))} | — | ${pct(mean(fsF1s)!)}% |`,
369
+ `| logistic regression (linear) | ${f4(mean(lrAucs)!)} ± ${f4(std(lrAucs))} | ${sgn(meanDelta)}${f4(meanDelta)} | ${pct(mean(lrF1s)!)}% |`,
370
+ `| **gradient-boosted trees** | **${f4(mean(gbtAucs)!)} ± ${f4(std(gbtAucs))}** | **${sgn(meanGbtVsFs)}${f4(meanGbtVsFs)}** | **${pct(mean(gbtF1s)!)}%** |`,
570
371
  "",
571
372
  `**ΔAUC (LR − FS): ${sgn(meanDelta)}${f4(meanDelta)} ± ${f4(std(deltas))}, LR > FS in ${lrWins}/${SEEDS} seeds.**`,
572
373
  "",
573
374
  `Robustness: the ΔAUC is small but **consistent** — std ${f4(std(deltas))} across seeds, SE ±${f4(seMean)} → ` +
574
375
  `≈${zScore.toFixed(1)}σ above zero, ${lrWins}/${SEEDS} seeds in LR's favour. At the operating point the gap is ` +
575
- `larger: **ΔF1 ${sgn(f1Delta * 100)}${(f1Delta * 100).toFixed(1)}pp** (${pct(mean(fsF1s))}% → ${pct(mean(lrF1s))}%), ` +
376
+ `larger: **ΔF1 ${sgn(f1Delta * 100)}${(f1Delta * 100).toFixed(1)}pp** (${pct(mean(fsF1s)!)}% → ${pct(mean(lrF1s)!)}%), ` +
576
377
  `because the interaction features sharpen the hard co-located band near the decision boundary even where overall ` +
577
378
  `ranking barely moves.`,
578
379
  "",
@@ -595,7 +396,7 @@ export async function scorerPairwiseEval(
595
396
  `Because the key over-merge interactions are ALREADY hand-engineered into the feature vector, the tree's main ` +
596
397
  `advantage — auto-discovering interactions — is largely pre-empted; it neither extends nor erases the linear ` +
597
398
  `gain. The signal in this feature set is close to linearly saturated, so a production GBM should budget for the ` +
598
- `SAME modest margin the LR shows, not a step change — its real value is generalizing the #625 levers, not ` +
399
+ `SAME modest margin the LR shows, not a step change — its real value is generalizing the #625 changes, not ` +
599
400
  `finding hidden non-linear structure here.`
600
401
 
601
402
  lines.push(treeVerdict)
@@ -614,13 +415,13 @@ export async function scorerPairwiseEval(
614
415
  const verdict =
615
416
  unanimous && (meanDelta > CLEAR_WIN_DELTA || f1Delta > CLEAR_WIN_F1_DELTA)
616
417
  ? `The LR beats FS **consistently** — it wins ${lrWins}/${SEEDS} seeds and lifts the operating-point F1 by ` +
617
- `${sgn(f1Delta * 100)}${(f1Delta * 100).toFixed(1)}pp (${pct(mean(fsF1s))}% → ${pct(mean(lrF1s))}%). The ΔAUC is ` +
618
- `small (+${f4(meanDelta)}) only because FS already ranks well (${f4(mean(fsAucs))}); the gain concentrates at the ` +
418
+ `${sgn(f1Delta * 100)}${(f1Delta * 100).toFixed(1)}pp (${pct(mean(fsF1s)!)}% → ${pct(mean(lrF1s)!)}%). The ΔAUC is ` +
419
+ `small (+${f4(meanDelta)}) only because FS already ranks well (${f4(mean(fsAucs)!)}); the gain concentrates at the ` +
619
420
  `decision boundary, exactly where the interaction features (which FS structurally can't express) bite. ` +
620
421
  `**This greenlights the #603 learned scorer:** a GBM — non-linear over the same features — is the principled ` +
621
- `generalization of the hand-tuned #625 levers and should extend this linear gain. Honest framing: the linear ` +
422
+ `generalization of the hand-tuned #625 changes and should extend this linear gain. Honest framing: the linear ` +
622
423
  `headroom is modest, so the GBM's job is to *widen a real-but-small margin*, not to unlock a step change past the ` +
623
- `64.7% dedup plateau on its own — the reliable secondary identifier (#625) is still the larger lever.`
424
+ `64.7% dedup plateau on its own — the reliable secondary identifier (#625) is still the larger gain.`
624
425
  : unanimous && zScore >= STRONG_EVIDENCE_Z
625
426
  ? `The LR beats FS by a **small but statistically robust** margin (ΔAUC +${f4(meanDelta)}, ≈${zScore.toFixed(1)}σ, ` +
626
427
  `${lrWins}/${SEEDS} seeds; ΔF1 ${sgn(f1Delta * 100)}${(f1Delta * 100).toFixed(1)}pp). The interaction features ` +
@@ -641,7 +442,7 @@ export async function scorerPairwiseEval(
641
442
  lines.push("")
642
443
 
643
444
  lines.push(
644
- `In-domain (${STATE} only), ${keptNPIs.size} NPIs, PAIRWISE ranking (not the assembled clustering metric the dedup ` +
445
+ `In-domain (${STATE} only), ${keptNpis.size} NPIs, PAIRWISE ranking (not the assembled clustering metric the dedup ` +
645
446
  `benchmark reports against the 64.7% baseline — a better pairwise scorer need not translate 1:1 to cluster F1). The GBT ` +
646
447
  `is a compact pure-Node implementation (120 boosting rounds, depth 3), a faithful stand-in for an offline ` +
647
448
  `XGBoost/LightGBM but not tuned. The split is by NPI so there's no record-level leakage, but the address-frequency ` +
@@ -659,7 +460,7 @@ export async function scorerPairwiseEval(
659
460
  console.log(md)
660
461
 
661
462
  if (OUT_MD) {
662
- writeFileSync(OUT_MD, md)
463
+ await writeLocalFile(md, OUT_MD)
663
464
  report?.(`[written] ${OUT_MD}`)
664
465
  }
665
466
 
@@ -16,10 +16,10 @@
16
16
  * [--em] [--out-md <md>]`
17
17
  */
18
18
 
19
- import { writeFileSync } from "node:fs"
19
+ import { writeLocalFile } from "@mailwoman/core/fs/writers"
20
+ import { makeLcg } from "@mailwoman/core/random"
20
21
 
21
- import { makeLcg } from "@mailwoman/core/utils"
22
- import { resolveEntities, type SourceRecord } from "@mailwoman/registry"
22
+ import { resolveEntities, type SourceRecord } from "#index"
23
23
 
24
24
  /**
25
25
  * Options for {@linkcode matcherScale}.
@@ -170,7 +170,7 @@ export async function matcherScale(
170
170
  lines.push(
171
171
  `RSS is the shared-process high-water mark across the sweep (each size reuses the heap), so it is an upper ` +
172
172
  `bound, not a per-N working set. The largest size that fits is bounded by the record objects + the link array; ` +
173
- `beyond that, shard by geography (each cell is independent) — the same partition the blocking already implies.`
173
+ `beyond that, extract by geography (each cell is independent) — the same partition the blocking already implies.`
174
174
  )
175
175
 
176
176
  lines.push("")
@@ -189,7 +189,7 @@ export async function matcherScale(
189
189
  console.log(md)
190
190
 
191
191
  if (OUT_MD) {
192
- writeFileSync(OUT_MD, md)
192
+ await writeLocalFile(md, OUT_MD)
193
193
  report?.(`[written] ${OUT_MD}`)
194
194
  }
195
195
 
@@ -0,0 +1,23 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ * @file Org-name similarity primitives for the NPPES benchmark's org-name entity truth.
6
+ */
7
+
8
+ export { orgTokens } from "#tools/shared"
9
+
10
+ /**
11
+ * Jaccard floor at or above which two {@linkcode orgTokens} sets count as the same organization — the gold-set
12
+ * threshold.
13
+ */
14
+ export const ORG_TAU = 0.7
15
+
16
+ /**
17
+ * An NPI's primary registry identity: the org-name token set plus the address key of its practice location. Every grain
18
+ * of the org-name truth blocks on a location and filters on the tokens.
19
+ */
20
+ export interface NPIPrimary {
21
+ tokens: Set<string>
22
+ addrKey: string
23
+ }
@@ -0,0 +1,94 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ * @file The gold-set adjudication packet — the org-name-grain over-merged clusters, with every matcher-visible field,
6
+ * formatted for human review.
7
+ */
8
+
9
+ import { writeLocalTextFile } from "@mailwoman/core/fs/writers"
10
+ import { isPresent } from "@mailwoman/core/objects"
11
+
12
+ import type { ResolvedEntity, SourceRecord } from "#index"
13
+ import type { MessyRow } from "#tools/nppes/sample"
14
+ import type { TruthLabel } from "#tools/nppes/truth-grains"
15
+
16
+ /**
17
+ * Everything the packet reads.
18
+ */
19
+ export interface OvermergePacketInput {
20
+ /**
21
+ * The clusters to inspect — the SHIPPED config's, since the packet exists to adjudicate what production produces.
22
+ */
23
+ entities: readonly ResolvedEntity[]
24
+ /**
25
+ * The source rows, for the fields that ride as attributes rather than on the record face.
26
+ */
27
+ rows: readonly MessyRow[]
28
+ recordCount: number
29
+ maxNpis: number
30
+ /**
31
+ * The state the sample was drawn from, so the packet's own header names the run an adjudicator is holding.
32
+ */
33
+ state: string
34
+ orgNameLabel: TruthLabel
35
+ }
36
+
37
+ /**
38
+ * Write the packet and return the number of over-merged clusters it holds.
39
+ *
40
+ * A cluster qualifies when its members carry more than one org-name label — the matcher fused records the org-name
41
+ * truth says belong to different entities. Per-pair human adjudication is the only instrument that separates model
42
+ * error from yardstick error once the residual is near the measured irreducible ceiling.
43
+ */
44
+ export async function writeOvermergePacket(path: string, input: OvermergePacketInput): Promise<number> {
45
+ const { entities, rows, recordCount, maxNpis, state, orgNameLabel } = input
46
+ const rowByID = new Map(rows.map((r) => [r.npi, r]))
47
+
48
+ const out: string[] = [
49
+ "# #625 gold-set adjudication packet — org-name-grain over-merged clusters (GBT, shipped config)",
50
+ "",
51
+ `${state} --max-npis ${maxNpis} · ${recordCount} records · generated by \`registry scorer-eval nppes-benchmark --dump-overmerges\``,
52
+ "",
53
+ "For each cluster: the matcher fused records that the org-name truth says belong to DIFFERENT entities.",
54
+ "Adjudicate each: **[same]** one real-world entity (yardstick error — the truth under-collapsed) or",
55
+ "**[distinct]** genuinely different co-located providers (model over-merge). Mark inline and return.",
56
+ "",
57
+ ]
58
+
59
+ let n = 0
60
+
61
+ entities.forEach((e) => {
62
+ const byLabel = new Map<string, SourceRecord[]>()
63
+
64
+ for (const rec of e.records) {
65
+ const lbl = orgNameLabel(rec)
66
+ const list = byLabel.get(lbl) ?? []
67
+ list.push(rec)
68
+ byLabel.set(lbl, list)
69
+ }
70
+
71
+ if (byLabel.size <= 1) return
72
+
73
+ n++
74
+ out.push(`## Cluster ${n} — ${e.records.length} records, ${byLabel.size} org-name entities → verdict: [ ]`)
75
+
76
+ for (const [lbl, members] of byLabel) {
77
+ out.push(`- **entity ${lbl}**`)
78
+
79
+ for (const rec of members) {
80
+ const src = rowByID.get(rec.id)
81
+
82
+ out.push(
83
+ ` - npi=${rec.id} · name="${[rec.name?.given, rec.name?.family].filter(isPresent).join(" ")}" · org="${rec.organization?.canonical ?? ""}" · addr="${rec.address?.raw ?? ""}" · auth="${src?.auth ?? ""}" · taxonomy="${src?.taxonomy ?? ""}"`
84
+ )
85
+ }
86
+ }
87
+
88
+ out.push("")
89
+ })
90
+
91
+ await writeLocalTextFile(out.join("\n"), path)
92
+
93
+ return n
94
+ }