@mailwoman/resolver 9.0.0 → 9.1.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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"toponym-prior.js","sourceRoot":"","sources":["../toponym-prior.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4CG;AAIH;;;;;;;;;;;;;;;GAeG;AACH,MAAM,CAAC,MAAM,4BAA4B,GAAG,CAAC,CAAA;AAE7C;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,MAAM,gCAAgC,GAAG,IAAI,CAAA;AASpD;;;;;GAKG;AACH,SAAS,cAAc,CAAqB,UAAwB,EAAE,OAA+B;IACpG,MAAM,KAAK,GAAQ,EAAE,CAAA;IACrB,MAAM,IAAI,GAAQ,EAAE,CAAA;IAEpB,KAAK,MAAM,CAAC,IAAI,UAAU,EAAE,CAAC;QAC5B,4FAA4F;QAC5F,0FAA0F;QAC1F,uFAAuF;QACvF,4FAA4F;QAC5F,CAAC;QAAA,CAAC,CAAC,CAAC,UAAU,KAAK,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;IAChD,CAAC;IAED,yEAAyE;IACzE,OAAO,CAAC,GAAG,KAAK,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE,GAAG,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAA;AAC/D,CAAC;AAED;;;GAGG;AACH,MAAM,IAAI,GAAG,CAAC,CAAW,EAAU,EAAE,CAAC,CAAC,CAAC,UAAU,IAAI,CAAC,CAAC,KAAK,CAAA;AAE7D;;;GAGG;AACH,MAAM,QAAQ,GAAG,CAAC,CAAW,EAAW,EAAE,CAAC,OAAO,CAAC,CAAC,UAAU,KAAK,QAAQ,IAAI,MAAM,CAAC,QAAQ,CAAC,CAAC,C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,CAAA;IAEtD,MAAM,KAAK,GAAQ,EAAE,CAAA;IACrB,MAAM,IAAI,GAAQ,EAAE,CAAA;IAEpB,KAAK,MAAM,CAAC,IAAI,UAAU,EAAE,CAAC;QAC5B,sFAAsF;QACtF,CAAC;QAAA,CAAC,CAAC,CAAC,UAAU,KAAK,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;IAChD,CAAC;IAED,OAAO,CAAC,GAAG,eAAe,CAAC,KAAK,EAAE,yBAAyB,CAAC,EAAE,GAAG,eAAe,CAAC,IAAI,EAAE,yBAAyB,CAAC,CAAC,CAAA;AACnH,CAAC;AAED;;;;;;;;;;GAUG;AACH,MAAM,UAAU,kBAAkB,CACjC,UAAwB,EACxB,OAA2B,EAC3B,SAAiB,4BAA4B;IAE7C,IAAI,CAAC,OAAO,IAAI,UAAU,CAAC,MAAM,GAAG,CAAC;QAAE,OAAO,CAAC,GAAG,UAAU,CAAC,CAAA;IAC7D,MAAM,MAAM,GAAG,OAAO,CAAC,WAAW,EAAE,CAAA;IAEpC,MAAM,GAAG,GAAG,CAAC,CAAI,EAAU,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,OAAO,EAAE,WAAW,EAAE,KAAK,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;IAE1F,OAAO,cAAc,CAAC,UAAU,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,CAAA;AAC7D,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mailwoman/resolver",
3
- "version": "9.0.0",
3
+ "version": "9.1.0",
4
4
  "description": "The address resolver: walk an AddressTree, decorate nodes with gazetteer-supplied coordinates + attribution. Backend-agnostic (any ResolverBackend), with the span-rescore + postcode-consistency levers. Lifted out of @mailwoman/core so it can depend on @mailwoman/spatial (haversine) + @mailwoman/codex (USPS directionals) instead of reinventing them; the type contract stays in core so the pipeline composes it without a cycle.",
5
5
  "license": "AGPL-3.0-only OR LicenseRef-Commercial",
6
6
  "repository": {
@@ -65,8 +65,8 @@
65
65
  }
66
66
  },
67
67
  "dependencies": {
68
- "@mailwoman/codex": "9.0.0",
69
- "@mailwoman/core": "9.0.0",
70
- "@mailwoman/spatial": "9.0.0"
68
+ "@mailwoman/codex": "9.1.0",
69
+ "@mailwoman/core": "9.1.0",
70
+ "@mailwoman/spatial": "9.1.0"
71
71
  }
72
72
  }
@@ -53,6 +53,32 @@
53
53
  * geographic tie) both return `null`. The mechanism only ever speaks when exactly one country
54
54
  * makes the pair consistent, and only ever when the default country could not.
55
55
  *
56
+ * ## What #24 changed (2026-08-10)
57
+ *
58
+ * Two structural gaps, both found by replaying the 420-row panel-v2 benchmark. The pass is default-ON,
59
+ * the eu-mixed block gave it 29 chances, and it fired **zero** times — while the right answer sat in
60
+ * the shipped gazetteer within 4 km of truth on 21 of them.
61
+ *
62
+ * 1. **The candidate countries came from a proxy.** `candidateSystemsForPostcode` is a shape test over
63
+ * the eight slices codex specifies (`us de fr ca gb jp au nz`), so CZ, CH, BE, DK, AT, NL and IT
64
+ * could never be PROPOSED, however good the evidence. `13000` shapes as `[us, de, fr]`; the
65
+ * gazetteer holds it in exactly one country, and that country is CZ. The candidate set now unions
66
+ * the shape list with the countries the gazetteer actually holds the postcode in — one unscoped
67
+ * lookup, exhaustive at the measured cardinality (the most-shared code in the artifact carries 12
68
+ * rows across 8 countries). Every candidate still has to pass the same geometric pair test, so the
69
+ * widening can only convert an abstention into a verdict or a verdict into an abstention, never a
70
+ * verdict into a different one.
71
+ * 2. **The pair was all-or-nothing.** Ten panel rows had unimpeachable one-sided evidence and no pair:
72
+ * the gazetteer carries no CH or BE postcodes at all (so `Sarnen` and `Kelmis` could never agree
73
+ * with anything), and `Praha 3` / `Praha 9` are municipal districts no admin gazetteer names (so
74
+ * `13000` had nothing to agree WITH). Each half may now speak alone — but only when the DEFAULT
75
+ * country corroborates NEITHER half, and only when the speaking half names exactly one country in
76
+ * the whole gazetteer. See {@link PostcodeCountryScopeEvidence}.
77
+ *
78
+ * The abstention doctrine is unchanged and is what bounds the new rungs: a two-country tie is a HARD
79
+ * abstention that never falls through to the single-sided rungs, and any corroboration at home — the
80
+ * address's own city or its own postcode existing in the default country — stops the pass dead.
81
+ *
56
82
  * ## Evidence
57
83
  *
58
84
  * Prototyped out-of-tree against the live gazetteer over the public `findPlace` surface (2026-08-03):
@@ -89,7 +115,21 @@ import { haversineKm } from "@mailwoman/spatial"
89
115
  export const POSTCODE_COUNTRY_COHERENCE_GATE_KM = 25
90
116
 
91
117
  /**
92
- * A country in which the address's (postcode, locality) pair is geographically consistent.
118
+ * Which half (or halves) of the address bought the verdict — the firing receipt, so a reader of a scoped result can
119
+ * tell a two-sided agreement from a one-sided uniqueness claim without re-deriving it.
120
+ *
121
+ * - `pair` — postcode AND locality both resolve in this country, within the gate. The strongest rung and the only one
122
+ * that existed before #24.
123
+ * - `locality` — the locality names exactly one country in the whole gazetteer, and the postcode names none that
124
+ * contradict it. This is the CH/BE class: the gazetteer carries no Swiss or Belgian postcodes at all, so the pair
125
+ * test can never fire there no matter how good the locality evidence is.
126
+ * - `postcode` — the postcode is held in exactly one country and the locality is in no gazetteer at all. The `Praha 3`
127
+ * class: a municipal district nobody's admin gazetteer names.
128
+ */
129
+ export type PostcodeCountryScopeEvidence = "pair" | "locality" | "postcode"
130
+
131
+ /**
132
+ * A country in which the address's own evidence is geographically consistent.
93
133
  */
94
134
  export interface PostcodeCountryScope {
95
135
  /**
@@ -104,18 +144,24 @@ export interface PostcodeCountryScope {
104
144
  * The locality string the verdict was reached on.
105
145
  */
106
146
  locality: string
147
+ /**
148
+ * Which evidence carried the verdict. See {@link PostcodeCountryScopeEvidence}.
149
+ */
150
+ evidence: PostcodeCountryScopeEvidence
107
151
  /**
108
152
  * Distance between the resolved postcode point and the nearest same-named locality, in km. Always `<= gateKm`.
153
+ * Present ONLY for the `pair` rung — a single-sided verdict has no two points to measure between, and reporting a `0`
154
+ * there would assert an agreement nobody tested (the meaning-of-zero rule).
109
155
  */
110
- distanceKm: number
156
+ distanceKm?: number
111
157
  /**
112
- * The postcode place that anchored the verdict.
158
+ * The postcode place that anchored the verdict. Absent on the `locality` rung.
113
159
  */
114
- postcodePlace: ResolvedPlace
160
+ postcodePlace?: ResolvedPlace
115
161
  /**
116
- * The locality place that anchored the verdict.
162
+ * The locality place that anchored the verdict. Absent on the `postcode` rung.
117
163
  */
118
- localityPlace: ResolvedPlace
164
+ localityPlace?: ResolvedPlace
119
165
  }
120
166
 
121
167
  export interface PostcodeCountryScopeOpts {
@@ -133,6 +179,17 @@ export interface PostcodeCountryScopeOpts {
133
179
  * Consistency gate radius in km. Defaults to {@link POSTCODE_COUNTRY_COHERENCE_GATE_KM}.
134
180
  */
135
181
  gateKm?: number
182
+ /**
183
+ * Optional narrowing of the SHAPE half of the candidate-country set — the shape-coherence pass's intersection for a
184
+ * CONFIRMED postcode span (see `resolver/postcode-shape-coherence.ts`, #31 Mechanism 1). When present it REPLACES
185
+ * `candidateSystemsForPostcode`'s own list; it is a pure subset of that list (codex systems ∩ confident sibling
186
+ * systems). Upper-case ISO-3166 alpha-2, e.g. `["US"]` for a 5-digit code whose siblings all say US.
187
+ *
188
+ * It narrows the shape half only. Since #24 the candidate set also carries the countries the GAZETTEER holds this
189
+ * postcode in, and that half is not narrowable — it is the artifact reporting what it contains, which is the same
190
+ * class of evidence the pair test itself runs on. Every candidate from either half still has to pass that test.
191
+ */
192
+ candidateSystems?: readonly string[]
136
193
  }
137
194
 
138
195
  /**
@@ -162,27 +219,95 @@ export function firstLocalityValue(roots: readonly AddressNode[]): string | unde
162
219
  return undefined
163
220
  }
164
221
 
222
+ /**
223
+ * Over-fetch for the UNSCOPED holder probes (#24). Postcodes are bounded and small — the 2026-08-10 candidate
224
+ * gazetteer's most-shared code carries 12 rows across 8 countries — so 20 sees every bearer and the postcode holder set
225
+ * is COMPLETE, not a sample. Locality names are not bounded that way (`rampur` has 1,096 rows, `bara` spans 42
226
+ * countries), so 30 is a population-first WINDOW: it can only ever hide a country, which turns a "more than one
227
+ * country" abstention into a false "exactly one". The explicit default-country probe below is what closes that gap for
228
+ * the case that matters (the address is domestic after all).
229
+ */
230
+ const POSTCODE_HOLDER_FETCH = 20
231
+ const LOCALITY_HOLDER_FETCH = 30
232
+
233
+ /**
234
+ * Upper bound on countries the pair rung will test, so a pathological name can't turn one incoherent parse into a
235
+ * hundred lookups. The postcode holder set is ≤8 countries in the measured artifact and the codex shape list is ≤8, so
236
+ * this only ever binds on a gazetteer very unlike today's.
237
+ */
238
+ const MAX_CANDIDATE_COUNTRIES = 12
239
+
240
+ /**
241
+ * Countries that hold an exact, coordinate-bearing row for `text` at `placetype`, mapped to their best (first) such
242
+ * row. One UNSCOPED lookup.
243
+ *
244
+ * This is the #24 candidate source, and it replaces a proxy with the thing itself. The pass used to ask codex "which
245
+ * address SYSTEMS could this shape be?" — a model-free shape test over the eight slices codex specifies. That answer is
246
+ * correct and useless for two thirds of Europe: `13000` shapes as `[us, de, fr]`, the gazetteer holds it in exactly one
247
+ * country (CZ), and CZ has no codex slice, so the pass could not propose the only country that could possibly be right.
248
+ * Membership in the gazetteer is positive evidence of the same kind the pair test already runs on, available for one
249
+ * lookup, and it is EXHAUSTIVE for postcodes at the measured cardinality.
250
+ *
251
+ * `exactMatch !== false` is the admission bar: a fuzzy postcode hit is a DIFFERENT postcode (the 2026-08-05 Code-Point
252
+ * lesson — `BT3 9QQ` trigram-matching Sheffield's `S3 9QQ`), and a fuzzy locality hit is evidence about the index, not
253
+ * about the country. Backends that do not stamp the flag leave it undefined and still contribute.
254
+ */
255
+ async function countriesHolding(
256
+ backend: ResolverBackend,
257
+ text: string,
258
+ placetype: "postalcode" | "locality",
259
+ limit: number
260
+ ): Promise<Map<string, ResolvedPlace>> {
261
+ const out = new Map<string, ResolvedPlace>()
262
+
263
+ let hits: ResolvedPlace[]
264
+
265
+ try {
266
+ hits = await backend.findPlace({ text, placetype, limit })
267
+ } catch {
268
+ return out // a backend hiccup degrades to "no evidence", never to a crashed resolve
269
+ }
270
+
271
+ for (const hit of hits) {
272
+ const country = hit.country?.trim().toUpperCase()
273
+
274
+ if (!country || hit.exactMatch === false || !hasCoord(hit)) continue
275
+
276
+ if (!out.has(country)) {
277
+ out.set(country, hit)
278
+ }
279
+ }
280
+
281
+ return out
282
+ }
283
+
165
284
  /**
166
285
  * Is the (postcode, locality) pair geographically consistent in `country`? Returns the winning pair and its distance,
167
286
  * or `null` when the postcode does not resolve there, no same-named locality exists there, or the nearest one is
168
- * outside the gate. Costs one postcode lookup plus (only if that hit) one locality lookup.
287
+ * outside the gate. Costs one postcode lookup plus (only if that hit) one locality lookup — or just the locality lookup
288
+ * when the caller already knows the country's postcode row (`knownPostcodePlace`, from the exhaustive unscoped probe).
169
289
  */
170
290
  async function coherenceIn(
171
291
  country: string,
172
292
  postcode: string,
173
293
  locality: string,
174
294
  backend: ResolverBackend,
175
- gateKm: number
295
+ gateKm: number,
296
+ knownPostcodePlace?: ResolvedPlace
176
297
  ): Promise<{ postcodePlace: ResolvedPlace; localityPlace: ResolvedPlace; distanceKm: number } | null> {
177
- let postcodeHits: ResolvedPlace[]
298
+ let postcodePlace = knownPostcodePlace
178
299
 
179
- try {
180
- postcodeHits = await backend.findPlace({ text: postcode, placetype: "postalcode", country, limit: 3 })
181
- } catch {
182
- return null // a backend hiccup degrades to "no evidence here", never to a crashed resolve
183
- }
300
+ if (!postcodePlace) {
301
+ let postcodeHits: ResolvedPlace[]
184
302
 
185
- const postcodePlace = postcodeHits.find(hasCoord)
303
+ try {
304
+ postcodeHits = await backend.findPlace({ text: postcode, placetype: "postalcode", country, limit: 3 })
305
+ } catch {
306
+ return null // a backend hiccup degrades to "no evidence here", never to a crashed resolve
307
+ }
308
+
309
+ postcodePlace = postcodeHits.find(hasCoord)
310
+ }
186
311
 
187
312
  if (!postcodePlace) return null
188
313
 
@@ -250,26 +375,109 @@ export async function findPostcodeCountryScope(
250
375
  // no override, and the common domestic path costs two lookups and changes nothing.
251
376
  if (await coherenceIn(defaultCountry, postcode, locality, backend, gateKm)) return null
252
377
 
253
- // 2. The default could not place this pair. Which other country the SHAPE allows can?
254
- const candidates = candidateSystemsForPostcode(postcode)
255
- .map((system) => system.toUpperCase())
378
+ // 2. The default could not place this pair. Which countries could? Two sources, unioned:
379
+ //
380
+ // - the SHAPE list (`candidateSystemsForPostcode`, or the shape-coherence pass's narrowing when #31
381
+ // Mechanism 1 supplied one — a pure subset of it), and
382
+ // - the countries the GAZETTEER actually holds this postcode in (#24). Exhaustive at the measured
383
+ // cardinality, and the only source that can name a country codex has no slice for — which was the
384
+ // whole reason the CZ/CH/BE/DK/AT/NL block of the 2026-08-09 panel resolved to US namesakes while
385
+ // their own postcodes sat in the shipped gazetteer within 4 km of truth.
386
+ //
387
+ // The union can only ADD countries, and every added one must still pass the same geometric pair test,
388
+ // so this widens recall without weakening the verdict: a second coherent country turns a verdict into
389
+ // an abstention (safe), never into a wrong answer.
390
+ const pcHolders = await countriesHolding(backend, postcode, "postalcode", POSTCODE_HOLDER_FETCH)
391
+
392
+ const shapeSystems = (
393
+ opts.candidateSystems ?? candidateSystemsForPostcode(postcode).map((system) => system.toUpperCase())
394
+ ).map((country) => country.trim().toUpperCase())
395
+
396
+ const candidates = [...new Set([...shapeSystems, ...pcHolders.keys()])]
256
397
  .filter((country) => country !== defaultCountry)
257
-
258
- if (!candidates.length) return null
398
+ .slice(0, MAX_CANDIDATE_COUNTRIES)
259
399
 
260
400
  const coherent: PostcodeCountryScope[] = []
261
401
 
262
402
  for (const country of candidates) {
263
- const hit = await coherenceIn(country, postcode, locality, backend, gateKm)
403
+ const hit = await coherenceIn(country, postcode, locality, backend, gateKm, pcHolders.get(country))
264
404
 
265
405
  if (hit) {
266
- coherent.push({ country, postcode, locality, ...hit })
406
+ coherent.push({ country, postcode, locality, evidence: "pair", ...hit })
267
407
  }
268
408
  }
269
409
 
270
- // 3. Exactly one country makes the pair consistent, or we abstain. Two coherent countries would mean the geometry
271
- // genuinely does not decide, and guessing between them is precisely what this mechanism exists not to do.
272
- return coherent.length === 1 ? coherent[0]! : null
410
+ // 3. Exactly one country makes the pair consistent, or we fall through. Two coherent countries mean the geometry
411
+ // genuinely does not decide, and guessing between them is precisely what this mechanism exists not to do — so a
412
+ // TIE is a hard abstention, never a fall-through to the weaker rungs below.
413
+ if (coherent.length === 1) return coherent[0]!
414
+
415
+ if (coherent.length > 1) return null
416
+
417
+ // 4. No country makes the PAIR consistent. On the 2026-08-09 panel that happened 10 times for two opposite
418
+ // reasons, and in both the address's country was never in doubt — only unrepresentable as a pair:
419
+ //
420
+ // - the gazetteer holds no postcodes for the country at all (CH, BE), so the postcode half can never
421
+ // agree with anything no matter how good the locality evidence is; or
422
+ // - the locality is a name no admin gazetteer carries (`Praha 3`, `Praha 9` — municipal districts).
423
+ //
424
+ // So each half gets to speak alone, under two conditions that keep this from becoming a guess. First, the
425
+ // DEFAULT country must corroborate NEITHER half — if the address's own city or its own postcode exists at
426
+ // home, the address is domestically plausible and nothing foreign may be proposed (this is what holds
427
+ // `123 Main St, Vienna, VA 22180` in Virginia even though Wien is the vastly more prominent Vienna).
428
+ // Second, the speaking half must name EXACTLY ONE country in the entire gazetteer — the same uniqueness bar
429
+ // the pair rung uses, applied to one side.
430
+ if (pcHolders.has(defaultCountry)) return null
431
+
432
+ if (await holdsLocality(backend, locality, defaultCountry)) return null
433
+
434
+ // 4a. The locality names exactly one country. Stronger than the postcode rung — a place name is far more
435
+ // discriminative than a four-digit code — so it is tried first. It stands down when that country's OWN
436
+ // postcode row contradicts the locality (outside the gate): the two halves disagreeing inside one country
437
+ // is exactly what the pair test exists to catch, and a single-sided rung must not launder it.
438
+ const locHolders = await countriesHolding(backend, locality, "locality", LOCALITY_HOLDER_FETCH)
439
+
440
+ if (locHolders.size === 1) {
441
+ const [country, localityPlace] = [...locHolders.entries()][0]!
442
+ const ownPostcode = pcHolders.get(country)
443
+
444
+ const contradicted =
445
+ ownPostcode !== undefined &&
446
+ haversineKm(ownPostcode.lat, ownPostcode.lon, localityPlace.lat, localityPlace.lon) > gateKm
447
+
448
+ if (country !== defaultCountry && !contradicted) {
449
+ return { country, postcode, locality, evidence: "locality", localityPlace }
450
+ }
451
+ }
452
+
453
+ // 4b. The locality is in no gazetteer (or names several countries) and the postcode is held in exactly one.
454
+ // `Biskupcova 1843/3, 13000 Praha 3`: `13000` is a CZ code and nothing else, anywhere.
455
+ if (!locHolders.size && pcHolders.size === 1) {
456
+ const [country, postcodePlace] = [...pcHolders.entries()][0]!
457
+
458
+ if (country !== defaultCountry) {
459
+ return { country, postcode, locality, evidence: "postcode", postcodePlace }
460
+ }
461
+ }
462
+
463
+ return null
464
+ }
465
+
466
+ /**
467
+ * Does `country` hold an exact, coordinate-bearing locality row for `locality`? One scoped lookup — deliberately NOT
468
+ * read off the unscoped holder window, which is population-first and truncated, so a small domestic bearer could fall
469
+ * below its fold and let a foreign scope through.
470
+ */
471
+ async function holdsLocality(backend: ResolverBackend, locality: string, country: string): Promise<boolean> {
472
+ try {
473
+ const hits = await backend.findPlace({ text: locality, placetype: "locality", country, limit: 3 })
474
+
475
+ return hits.some((hit) => hit.exactMatch && hasCoord(hit))
476
+ } catch {
477
+ // A backend hiccup must not be read as "the default country has nothing" — that would license a foreign
478
+ // scope on no evidence. Treat it as corroboration and abstain.
479
+ return true
480
+ }
273
481
  }
274
482
 
275
483
  /**
@@ -290,7 +498,12 @@ export function stampPostcodeCountryScope(roots: readonly AddressNode[], scope:
290
498
  n.metadata = {
291
499
  ...n.metadata,
292
500
  postcode_country_scope: scope.country,
293
- postcode_country_scope_km: scope.distanceKm,
501
+ // WHICH rung spoke — a two-sided agreement and a one-sided uniqueness claim are different evidence,
502
+ // and a consumer that cannot tell them apart cannot weight them differently.
503
+ postcode_country_scope_evidence: scope.evidence,
504
+ // Only the `pair` rung measured a distance. Writing a 0 for the single-sided rungs would assert an
505
+ // agreement nobody tested.
506
+ ...(scope.distanceKm !== undefined ? { postcode_country_scope_km: scope.distanceKm } : {}),
294
507
  }
295
508
  }
296
509
  }
@@ -0,0 +1,165 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Postcode-prefix prior (#31, Mechanism 3) — the partial-code prior for postcodes the full-code
7
+ * gazetteer does not carry. #1480's abstention is the defect: a BT unit with no permissive source
8
+ * behind it (the NI half of Code-Point Open) misses the gazetteer, and the tree contributes
9
+ * NOTHING for it — no country scope, no district, no coordinate. This module derives the code's
10
+ * PREFIX and probes the PFX1 index (`postcode-prefix-<cc>.bin`), so the resolve "abstains on the
11
+ * UNIT and still contributes its DISTRICT": the node resolves from the prefix's centroid and/or
12
+ * ancestry, whichever the artifact carries.
13
+ *
14
+ * The index is a structural type (`PostcodePrefixIndexLike`, declared in `core/resolver/types.ts`),
15
+ * injected by the pipeline and never imported from `@mailwoman/neural` — B3-5: the probe touches
16
+ * zero model inputs. The loader lives in `@mailwoman/neural/postcode-prefix-index.ts` (PFX1 format:
17
+ * magic, header, dictionary, quantized i16 coordinates, `radiusP95Km`, ancestry); the resolver
18
+ * side only defines the derivation law and the probe.
19
+ *
20
+ * ## The derivation law (per artifact country)
21
+ *
22
+ * - **GB** — the OUTWARD code: the compact (whitespace-stripped) form minus its trailing 3 unit
23
+ * characters ("SW1A 2AA" → "SW1A", "BT9 5GS" → "BT9"). Never a greedy regex — the unit is
24
+ * exactly 3 chars in the compact form, and `outwardOf` in `mailwoman/gazetteer-pipeline/
25
+ * postcode-prefix.ts` is the build-side twin of this law.
26
+ * - **US** — the 3-digit section ("94043" → "940"). M-3 measured 3 digits as the first length
27
+ * where the ZIP prefix stops being free (145 km p95 median); a 5-digit artifact would be the
28
+ * full code the gazetteer already carries. No US artifact ships yet (B3-4 needs a ZCTA
29
+ * acquisition) — the branch exists so the law is tested before the data.
30
+ * - **Anything else** — abstain (null).
31
+ *
32
+ * ## The probe's country gate
33
+ *
34
+ * The index is country-specific EVIDENCE: it is only probed when its `country` matches the
35
+ * query's country scope (or the scope is absent). A GB index must not speak under a US scope —
36
+ * the pipeline passes the locale's index, and the walk's country filter is the caller's declared
37
+ * universe.
38
+ *
39
+ * ## Metadata contract (what the node carries afterward)
40
+ *
41
+ * - `postcode_prefix` — the prefix string that resolved it.
42
+ * - `postcode_prefix_ancestors` — the ancestry the prefix asserts (coarsest-first; GB outward
43
+ * nodes carry country → constituent-country → district).
44
+ * - `postcode_prefix_radius_p95_km` — the artifact's measured p95 radius, when the node carries a
45
+ * coordinate (M-3's receipt: a 1-digit US band and a GB outward code differ by 200×; never read
46
+ * a coordinate without its radius).
47
+ * - `coordinate_source: "postcode_prefix"` — ONLY when the node actually carries a coordinate.
48
+ * The ancestry-only tier (NI's 80 BT districts) stays coordinate-free — the meaning-of-zero
49
+ * rule, and the half that decides B3-3: inventing a BT centroid would reproduce the `BT3 9QQ` →
50
+ * Sheffield defect #1480 just fixed.
51
+ *
52
+ * **D-rule: opt-in behind `ResolveOpts.postcodePrefixPrior`, default-OFF** (the PCN1 posture:
53
+ * data + loader + offline probe, no decode wiring; the header ships without `delta` until a
54
+ * calibration measures one). Bars: B3-2 (≥60% of held-out units within 10 km, zero worse than the
55
+ * abstention arm), B3-3 (NI ≥95% country scope GB + NIR ancestry + correct district named, 0%
56
+ * coordinate), B3-5 (structural — no model inputs touched).
57
+ */
58
+
59
+ import type { PostcodePrefixIndexLike, PostcodePrefixNode, ResolvedPlace } from "@mailwoman/core/resolver"
60
+
61
+ /**
62
+ * A resolved place that may carry NO coordinate. `ResolvedPlace` requires `lat`/`lon` (every gazetteer row has a value,
63
+ * even the 0,0 unlocated sentinel), and the prefix prior's ancestry-only tier must express absence as `undefined`
64
+ * instead — B3-3: inventing a centroid would reproduce the `BT3 9QQ` → Sheffield defect #1480. `decorateNode` copies
65
+ * `lat`/`lon` onto the node verbatim, so an undefined coordinate stays absent on the node — the meaning-of-zero rule.
66
+ * Widened ONLY at this seam: gazetteer places (always coordinate-bearing) remain plain `ResolvedPlace`.
67
+ */
68
+ export type CoordinateOptionalPlace = Omit<ResolvedPlace, "lat" | "lon"> & { lat?: number; lon?: number }
69
+
70
+ /**
71
+ * The MINIMUM compact code length for a GB outward derivation — a shorter code has no 3-character unit to strip ("B3"
72
+ * is a GB area, not a unit-bearing code).
73
+ */
74
+ const MIN_GB_OUTWARD_CODE_LENGTH = 5
75
+
76
+ /**
77
+ * The MINIMUM code length for a US section derivation.
78
+ */
79
+ const MIN_US_SECTION_CODE_LENGTH = 3
80
+
81
+ /**
82
+ * Derive the prefix the index is keyed by, per the artifact's own country law. Returns null (abstain) for a country
83
+ * with no derivation law, or a code too short to carry a prefix.
84
+ */
85
+ export function derivePostcodePrefix(code: string, country?: string): string | null {
86
+ if (!code || !country) return null
87
+
88
+ const compact = code.replaceAll(/\s+/g, "")
89
+
90
+ switch (country.toUpperCase()) {
91
+ // The outward-code law: compact minus the trailing 3 unit characters ("SW1A2AA" → "SW1A",
92
+ // "BT93GS" → "BT9"). Exactly 3 — never a greedy regex, the build-side twin is `outwardOf`.
93
+ case "GB":
94
+ return compact.length >= MIN_GB_OUTWARD_CODE_LENGTH ? compact.slice(0, -3) : null
95
+ // The 3-digit section ("94043" → "940"). No US artifact ships yet (B3-4 is ZCTA acquisition);
96
+ // the law is tested ahead of the data.
97
+ case "US":
98
+ return compact.length >= MIN_US_SECTION_CODE_LENGTH ? compact.slice(0, 3) : null
99
+ default:
100
+ return null
101
+ }
102
+ }
103
+
104
+ /**
105
+ * The outcome of a successful prefix probe.
106
+ */
107
+ export interface PostcodePrefixProbeResult {
108
+ /**
109
+ * The prefix string that hit.
110
+ */
111
+ prefix: string
112
+ /**
113
+ * The index node — its `ancestors` and optional coordinate/radius are the prior's payload.
114
+ */
115
+ node: PostcodePrefixNode
116
+ }
117
+
118
+ /**
119
+ * Probe the index for `code`'s prefix. Two abstention gates, in order: the index's country must match the query's
120
+ * country scope (or the scope is absent), and the derivation law must yield a prefix the index carries. Returns null to
121
+ * abstain — never throws, never guesses.
122
+ */
123
+ export function probePostcodePrefix(
124
+ code: string,
125
+ index: PostcodePrefixIndexLike,
126
+ queryCountry?: string
127
+ ): PostcodePrefixProbeResult | null {
128
+ const indexCountry = index.country?.toUpperCase()
129
+
130
+ // Country gate: the index is evidence FOR its own country only. A GB index under a US scope stays
131
+ // silent — the walk's country filter is the caller's declared universe.
132
+ if (queryCountry && indexCountry && queryCountry.toUpperCase() !== indexCountry) return null
133
+
134
+ const prefix = derivePostcodePrefix(code, indexCountry)
135
+
136
+ if (!prefix) return null
137
+
138
+ const node = index.probe(prefix)
139
+
140
+ return node ? { prefix, node } : null
141
+ }
142
+
143
+ /**
144
+ * Build the synthetic `ResolvedPlace` a prefix hit resolves a `postalcode` node to. `id: 0` — it is NOT a gazetteer row
145
+ * (the same sentinel `applyPostcodeConsistency` uses for its displaced place, resolve.ts) — and the coordinate is
146
+ * present ONLY when the node carries one, so an ancestry-only hit stays coordinate-free by construction (B3-3's 0%
147
+ * half).
148
+ */
149
+ export function postcodePrefixResolvedPlace(
150
+ prefix: string,
151
+ node: PostcodePrefixNode,
152
+ index: PostcodePrefixIndexLike
153
+ ): CoordinateOptionalPlace {
154
+ return {
155
+ id: 0,
156
+ name: prefix,
157
+ placetype: "postalcode",
158
+ // `""` = country unknown — the same empty-string convention the candidate backend uses for a row
159
+ // whose country_id resolves to nothing.
160
+ country: index.country?.toUpperCase() ?? "",
161
+ ...(node.lat !== undefined && node.lon !== undefined ? { lat: node.lat, lon: node.lon } : {}),
162
+ score: 0,
163
+ exactMatch: false,
164
+ }
165
+ }