@mailwoman/resolver 9.2.0 → 9.4.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 (143) hide show
  1. package/README.md +5 -5
  2. package/{admin-coherence-passes.ts → lib/admin/coherence-passes.ts} +87 -9
  3. package/{admin-containment.ts → lib/admin/containment.ts} +5 -14
  4. package/lib/admin/index.ts +10 -0
  5. package/lib/admin/jp-municipality.ts +97 -0
  6. package/{admin-winner.ts → lib/admin/winner.ts} +18 -2
  7. package/{backend-capabilities.ts → lib/backend-capabilities.ts} +3 -3
  8. package/{bare-toponym-race.ts → lib/bare-toponym-race.ts} +1 -1
  9. package/{decorate-node.ts → lib/decorate-node.ts} +2 -2
  10. package/{fold-name.ts → lib/fold-name.ts} +2 -2
  11. package/{index.ts → lib/index.ts} +16 -22
  12. package/{plausibility.ts → lib/plausibility.ts} +5 -4
  13. package/{postcode-country-coherence.ts → lib/postcode/country-coherence.ts} +27 -32
  14. package/lib/postcode/index.ts +9 -0
  15. package/{postcode-prefix.ts → lib/postcode/prefix.ts} +4 -4
  16. package/{postcode-shape-coherence.ts → lib/postcode/shape-coherence.ts} +10 -24
  17. package/{remote-resolver.ts → lib/remote-resolver.ts} +13 -4
  18. package/{rerank.ts → lib/rerank.ts} +2 -2
  19. package/{resolve.ts → lib/resolve/index.ts} +133 -602
  20. package/lib/resolve/passes.ts +544 -0
  21. package/{span-rescore.ts → lib/span-rescore.ts} +63 -97
  22. package/{street-evidence.ts → lib/street/evidence.ts} +39 -6
  23. package/lib/street/index.ts +8 -0
  24. package/{street-tier.ts → lib/street/tier.ts} +131 -110
  25. package/{toponym-prior.ts → lib/toponym-prior.ts} +8 -8
  26. package/out/{admin-coherence-passes.d.ts → admin/coherence-passes.d.ts} +29 -7
  27. package/out/admin/coherence-passes.d.ts.map +1 -0
  28. package/out/{admin-coherence-passes.js → admin/coherence-passes.js} +73 -9
  29. package/out/admin/coherence-passes.js.map +1 -0
  30. package/out/{admin-containment.d.ts → admin/containment.d.ts} +5 -5
  31. package/out/admin/containment.d.ts.map +1 -0
  32. package/out/{admin-containment.js → admin/containment.js} +6 -12
  33. package/out/admin/containment.js.map +1 -0
  34. package/out/admin/index.d.ts +10 -0
  35. package/out/admin/index.d.ts.map +1 -0
  36. package/out/admin/index.js +10 -0
  37. package/out/admin/index.js.map +1 -0
  38. package/out/admin/jp-municipality.d.ts +50 -0
  39. package/out/admin/jp-municipality.d.ts.map +1 -0
  40. package/out/admin/jp-municipality.js +54 -0
  41. package/out/admin/jp-municipality.js.map +1 -0
  42. package/out/{admin-winner.d.ts → admin/winner.d.ts} +11 -3
  43. package/out/admin/winner.d.ts.map +1 -0
  44. package/out/{admin-winner.js → admin/winner.js} +19 -3
  45. package/out/admin/winner.js.map +1 -0
  46. package/out/backend-capabilities.d.ts.map +1 -1
  47. package/out/backend-capabilities.js +3 -3
  48. package/out/backend-capabilities.js.map +1 -1
  49. package/out/bare-toponym-race.d.ts.map +1 -1
  50. package/out/bare-toponym-race.js +1 -1
  51. package/out/bare-toponym-race.js.map +1 -1
  52. package/out/decorate-node.d.ts +1 -1
  53. package/out/decorate-node.d.ts.map +1 -1
  54. package/out/decorate-node.js +1 -1
  55. package/out/decorate-node.js.map +1 -1
  56. package/out/fold-name.d.ts +2 -2
  57. package/out/fold-name.d.ts.map +1 -1
  58. package/out/fold-name.js +2 -2
  59. package/out/fold-name.js.map +1 -1
  60. package/out/index.d.ts +15 -16
  61. package/out/index.d.ts.map +1 -1
  62. package/out/index.js +9 -10
  63. package/out/index.js.map +1 -1
  64. package/out/plausibility.d.ts +5 -4
  65. package/out/plausibility.d.ts.map +1 -1
  66. package/out/plausibility.js +5 -4
  67. package/out/plausibility.js.map +1 -1
  68. package/out/{postcode-country-coherence.d.ts → postcode/country-coherence.d.ts} +16 -16
  69. package/out/postcode/country-coherence.d.ts.map +1 -0
  70. package/out/{postcode-country-coherence.js → postcode/country-coherence.js} +24 -25
  71. package/out/postcode/country-coherence.js.map +1 -0
  72. package/out/postcode/index.d.ts +9 -0
  73. package/out/postcode/index.d.ts.map +1 -0
  74. package/out/postcode/index.js +9 -0
  75. package/out/postcode/index.js.map +1 -0
  76. package/out/{postcode-prefix.d.ts → postcode/prefix.d.ts} +4 -4
  77. package/out/postcode/prefix.d.ts.map +1 -0
  78. package/out/{postcode-prefix.js → postcode/prefix.js} +4 -4
  79. package/out/postcode/prefix.js.map +1 -0
  80. package/out/{postcode-shape-coherence.d.ts → postcode/shape-coherence.d.ts} +3 -3
  81. package/out/postcode/shape-coherence.d.ts.map +1 -0
  82. package/out/{postcode-shape-coherence.js → postcode/shape-coherence.js} +11 -20
  83. package/out/postcode/shape-coherence.js.map +1 -0
  84. package/out/remote-resolver.d.ts +18 -3
  85. package/out/remote-resolver.d.ts.map +1 -1
  86. package/out/remote-resolver.js +2 -2
  87. package/out/remote-resolver.js.map +1 -1
  88. package/out/rerank.d.ts +1 -1
  89. package/out/rerank.d.ts.map +1 -1
  90. package/out/rerank.js +2 -2
  91. package/out/rerank.js.map +1 -1
  92. package/out/{resolve.d.ts → resolve/index.d.ts} +1 -1
  93. package/out/resolve/index.d.ts.map +1 -0
  94. package/out/{resolve.js → resolve/index.js} +100 -387
  95. package/out/resolve/index.js.map +1 -0
  96. package/out/resolve/passes.d.ts +218 -0
  97. package/out/resolve/passes.d.ts.map +1 -0
  98. package/out/resolve/passes.js +333 -0
  99. package/out/resolve/passes.js.map +1 -0
  100. package/out/span-rescore.d.ts +16 -16
  101. package/out/span-rescore.d.ts.map +1 -1
  102. package/out/span-rescore.js +43 -69
  103. package/out/span-rescore.js.map +1 -1
  104. package/out/{street-evidence.d.ts → street/evidence.d.ts} +18 -3
  105. package/out/street/evidence.d.ts.map +1 -0
  106. package/out/{street-evidence.js → street/evidence.js} +22 -6
  107. package/out/street/evidence.js.map +1 -0
  108. package/out/street/index.d.ts +8 -0
  109. package/out/street/index.d.ts.map +1 -0
  110. package/out/street/index.js +8 -0
  111. package/out/street/index.js.map +1 -0
  112. package/out/{street-tier.d.ts → street/tier.d.ts} +14 -3
  113. package/out/street/tier.d.ts.map +1 -0
  114. package/out/{street-tier.js → street/tier.js} +121 -99
  115. package/out/street/tier.js.map +1 -0
  116. package/out/toponym-prior.d.ts +8 -8
  117. package/out/toponym-prior.d.ts.map +1 -1
  118. package/out/toponym-prior.js +8 -8
  119. package/out/toponym-prior.js.map +1 -1
  120. package/package.json +116 -59
  121. package/vitest.config.ts +5 -6
  122. package/out/admin-coherence-passes.d.ts.map +0 -1
  123. package/out/admin-coherence-passes.js.map +0 -1
  124. package/out/admin-containment.d.ts.map +0 -1
  125. package/out/admin-containment.js.map +0 -1
  126. package/out/admin-winner.d.ts.map +0 -1
  127. package/out/admin-winner.js.map +0 -1
  128. package/out/postcode-country-coherence.d.ts.map +0 -1
  129. package/out/postcode-country-coherence.js.map +0 -1
  130. package/out/postcode-prefix.d.ts.map +0 -1
  131. package/out/postcode-prefix.js.map +0 -1
  132. package/out/postcode-shape-coherence.d.ts.map +0 -1
  133. package/out/postcode-shape-coherence.js.map +0 -1
  134. package/out/resolve.d.ts.map +0 -1
  135. package/out/resolve.js.map +0 -1
  136. package/out/street-evidence.d.ts.map +0 -1
  137. package/out/street-evidence.js.map +0 -1
  138. package/out/street-tier.d.ts.map +0 -1
  139. package/out/street-tier.js.map +0 -1
  140. package/out/vitest.config.d.ts +0 -16
  141. package/out/vitest.config.d.ts.map +0 -1
  142. package/out/vitest.config.js +0 -36
  143. package/out/vitest.config.js.map +0 -1
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Walk a parsed `AddressTree` and decide, for each span, which real place it names — then hand back the tree with coordinates, attribution and ancestry stamped on it.
4
4
 
5
- This is the half of [mailwoman](https://www.npmjs.com/package/mailwoman) that turns _"the model thinks this run of characters is a locality"_ into _"this is Springfield, Illinois, at 39.7973/-89.6455, and here is why."_ It owns the ranking, the coherence passes and the ordering rules; it owns no data. The gazetteer lives behind a `ResolverBackend` you supply.
5
+ This is the half of [mailwoman](https://www.npmjs.com/package/mailwoman) that turns _"the model assigns this run of characters to the locality label"_ into _"this is Springfield, Illinois, at 39.7973/-89.6455, and here is why."_ It owns the ranking, the coherence passes and the ordering rules; it owns no data. The gazetteer lives behind a `ResolverBackend` you supply.
6
6
 
7
7
  ## Installation
8
8
 
@@ -28,13 +28,13 @@ const decorated = await resolver.resolveTree(tree)
28
28
 
29
29
  `createWOFResolver` takes a `ResolverBackend` — a structural interface, not a class. `@mailwoman/resolver-wof-sqlite` implements it over `node:sqlite`, `@mailwoman/resolver-wof-wasm` over `@sqlite.org/sqlite-wasm` in a browser, and `RemoteResolver` over HTTP. Nothing here imports any of them.
30
30
 
31
- Backends differ in what they can answer, and that is visible rather than silent: `describeCapabilityGaps(backend)` reports which optional methods are missing, so a default-on feature that quietly no-ops on your backend says so instead of looking like a bad result.
31
+ Backends differ in what they can answer, and that is visible rather than silent: `describeCapabilityGaps(backend)` reports which optional methods are missing, so a default-on feature that no-ops without logging on your backend says so instead of looking like a bad result.
32
32
 
33
33
  ## Absence is a value
34
34
 
35
35
  Two rules run through this package, and both exist because their opposites shipped bugs.
36
36
 
37
- **A coordinate the gazetteer cannot supply is absent, never `0,0`.** `0,0` is the unlocated sentinel in every WOF-lineage shard, and the shards carry a great deal of it — 48,216 of 142,604 Japanese postcodes, 86,377 GB, 414 US. `decorateNode` leaves `lat`/`lon` unset for such a row, so the place still resolves and identifies itself while stating that it cannot say where it is. A consumer's `lat != null` check then means what it looks like it means.
37
+ **A coordinate the gazetteer cannot supply is absent, never `0,0`.** `0,0` is the unlocated sentinel in every WOF-lineage database, and those databases carry a great deal of it — 48,216 of 142,604 Japanese postcodes, 86,377 GB, 414 US. `decorateNode` leaves `lat`/`lon` unset for such a row, so the place still resolves and identifies itself while stating that it cannot say where it is. A consumer's `lat != null` check then means what it looks like it means.
38
38
 
39
39
  **A missing answer is not a wrong answer.** An unresolvable span is returned as parsed. Nothing here invents a centroid to fill a hole.
40
40
 
@@ -42,7 +42,7 @@ Two rules run through this package, and both exist because their opposites shipp
42
42
 
43
43
  `admin-winner.ts` owns one ordering, and it is the only one whose rungs are not fixed.
44
44
 
45
- `PLACETYPE_SPECIFICITY` ranks placetypes by how much ground they cover, which is the right question for most of them and the wrong one for `postalcode`. A GB unit postcode covers ~15 addresses and is tighter than any locality centroid; a French _code postal_ often spans several communes and is coarser than the one you want. One number cannot be both.
45
+ `PLACETYPE_SPECIFICITY` ranks placetypes by how much ground they cover, which is the right question for most of them and the wrong one for `postalcode`. A GB unit postcode covers ~15 addresses and is tighter than any locality centroid; a French _code postal_ can span several communes and be coarser than the one you want. One number cannot be both.
46
46
 
47
47
  So the rank of a resolved postcode is computed, from two independent routes:
48
48
 
@@ -68,7 +68,7 @@ Ranking a span in isolation gets Portland, Maine to Messina, Italy. These run ov
68
68
 
69
69
  | Pass | Question |
70
70
  | ---------------------------- | ------------------------------------------------------------------------------ |
71
- | `admin-coherence-passes` | Do the resolved places actually contain one another? |
71
+ | `admin-coherence-passes` | Do the resolved places contain one another? |
72
72
  | `postcode-country-coherence` | Does the postcode's shape agree with the country the rest of the tree implies? |
73
73
  | `postcode-shape-coherence` | Is this span a postcode at all, in any system the query could be in? |
74
74
  | `admin-containment` | Split candidates by whether they sit inside an established parent. |
@@ -11,9 +11,87 @@
11
11
 
12
12
  import { matchCountry, matchSubdivision } from "@mailwoman/codex/country"
13
13
  import type { AddressNode } from "@mailwoman/core/decoder"
14
- import type { ResolvedPlace, ResolverBackend } from "@mailwoman/core/resolver"
14
+ import { PLACETYPE_FILTER_GROUPS, type ResolvedPlace, type ResolverBackend } from "@mailwoman/core/resolver"
15
15
 
16
- import { decorateNode, isResolvedWithCoord } from "./decorate-node.ts"
16
+ import { decorateNode, isResolvedWithCoord } from "#decorate-node"
17
+
18
+ /**
19
+ * The region-band placetypes a lineage names a region by — `region` and its macro widening, the same set the lookup
20
+ * filter admits for a `region` request.
21
+ */
22
+ const REGION_LINEAGE_PLACETYPES: ReadonlySet<string> = new Set(PLACETYPE_FILTER_GROUPS["region"] ?? ["region"])
23
+
24
+ /**
25
+ * The numeric or string id behind a node's `placeID` (`wof:85679553` → `85679553`), or undefined when the node resolved
26
+ * to no place.
27
+ */
28
+ function placeIDValue(node: AddressNode): string | undefined {
29
+ const match = /^[a-z]+:(.+)$/u.exec(node.placeID ?? "")
30
+
31
+ return match?.[1]
32
+ }
33
+
34
+ /**
35
+ * Refuse a pick admitted from outside its parent's scope whose own lineage names a DIFFERENT region than the one the
36
+ * walk resolved above it.
37
+ *
38
+ * The walk scopes a child lookup to its resolved parent. When that scoped probe misses, two widenings exist so an
39
+ * incomplete hierarchy (a real place whose ancestor chain lacks its region) still resolves: the resolver's retry
40
+ * without the parent, and the candidate backend's interior region-scope fallback (#1731), which re-admits rows from
41
+ * outside the region and stamps them `regionScopeMiss`. Both also admit a namesake under another region: `臺南市北區`
42
+ * resolved 臺南市 (Tainan City), found no 北區 under it — the candidate table carries no Han key for Tainan's — and the
43
+ * widening answered Hsinchu's 北區, 214 km away, which the coherence report then marked `region: contradicted` while the
44
+ * point stood. Of the 289 held-out Taiwanese 鄉鎮市區, 21 resolved this way at 15.6–238 km when the register was read as
45
+ * bare `縣市鄉鎮市區` lines.
46
+ *
47
+ * The two cases a widening conflates are told apart by the pick's stamped ancestors: an incomplete chain names NO
48
+ * region and is kept, the case the widenings exist for; a chain that names a region other than the resolved parent is a
49
+ * different place and is un-resolved here, so the admin ladder answers the parent's own point rather than a namesake
50
+ * elsewhere. Only widened picks are examined (`metadata.parent_fallback`, stamped by the walk for either mechanism),
51
+ * and only when the parent region resolved to a place identity; no-op without the ancestor sidecar, since a chain that
52
+ * cannot be read is not a contradiction. The classifier attribution stays on the node; `parent_fallback_refused`
53
+ * records what happened.
54
+ */
55
+ export function applyParentFallbackContradiction(roots: readonly AddressNode[]): void {
56
+ const visit = (node: AddressNode, regionAncestor: AddressNode | null): void => {
57
+ const regionHere = node.tag === "region" && placeIDValue(node) !== undefined ? node : regionAncestor
58
+
59
+ if (regionHere && node !== regionHere && node.metadata?.["parent_fallback"] === true) {
60
+ const regionID = placeIDValue(regionHere)
61
+
62
+ const ancestors = node.metadata?.["ancestors"] as
63
+ | ReadonlyArray<{ id: number | string; placetype: string }>
64
+ | undefined
65
+
66
+ const regions = (ancestors ?? []).filter((a) => REGION_LINEAGE_PLACETYPES.has(a.placetype))
67
+
68
+ if (regionID !== undefined && regions.length && !regions.some((a) => String(a.id) === regionID)) {
69
+ delete node.lat
70
+ delete node.lon
71
+ delete node.placeID
72
+ delete node.alternatives
73
+
74
+ const kept: Record<string, unknown> = {}
75
+
76
+ for (const [key, value] of Object.entries(node.metadata ?? {})) {
77
+ if (!key.startsWith("resolver_") && key !== "ancestors" && key !== "resolution_quality") {
78
+ kept[key] = value
79
+ }
80
+ }
81
+
82
+ node.metadata = { ...kept, parent_fallback_refused: true }
83
+ }
84
+ }
85
+
86
+ for (const child of node.children) {
87
+ visit(child, regionHere)
88
+ }
89
+ }
90
+
91
+ for (const root of roots) {
92
+ visit(root, null)
93
+ }
94
+ }
17
95
 
18
96
  /**
19
97
  * Admin descendant-consistency (#263) — the joint-consistency resolve, scoped to the admin assignment. The greedy walk
@@ -320,11 +398,11 @@ async function reconcileExplicitCountry(
320
398
  * same-named locality under it? Only when BOTH hold does it swap the region and locality to the in-country pair.
321
399
  * Geography confirms; the subdivision table is a soft name→country prior, not a routing decision.
322
400
  *
323
- * Evidence-gated to stay byte-stable on the domestic path. It fires ONLY when (a) a default country is in force, (b)
324
- * the region node is UNRESOLVED (the default-country filter came up empty — a US region resolves fine under `US`, so a
325
- * well-formed US query never trips this), (c) the token is a subdivision of a DIFFERENT country than the default, and
326
- * (d) both the foreign region and a same-named foreign locality resolve. "Springfield, IL" / "Portland, ME": the region
327
- * resolves under `US`, so gate (b) fails and the tree is untouched. Costs one region + one locality lookup per
401
+ * Evidence-conditional to stay byte-stable on the domestic path. It fires ONLY when (a) a default country is in force,
402
+ * (b) the region node is UNRESOLVED (the default-country filter came up empty — a US region resolves fine under `US`,
403
+ * so a well-formed US query never trips this), (c) the token is a subdivision of a DIFFERENT country than the default,
404
+ * and (d) both the foreign region and a same-named foreign locality resolve. "Springfield, IL" / "Portland, ME": the
405
+ * region resolves under `US`, so check (b) fails and the tree is untouched. Costs one region + one locality lookup per
328
406
  * triggering pair. See `ResolveOpts.adminCoherence`.
329
407
  */
330
408
  export async function applyRegionCountryCoherence(
@@ -343,7 +421,7 @@ export async function applyRegionCountryCoherence(
343
421
  // Fire for an UNRESOLVED region (the default-country filter came up empty) whose companion locality node
344
422
  // exists — regardless of the locality's resolution state, so it covers both the resolved-but-foreign namesake
345
423
  // (Montreal → the greedy US pick, Montreal WI) and the unresolved locality the span-rescore tier would
346
- // otherwise back-fill with a US namesake. The in-country lookups below are the evidence gate.
424
+ // otherwise back-fill with a US namesake. The in-country lookups below are the evidence check.
347
425
  if (
348
426
  regionHere &&
349
427
  !isResolvedWithCoord(regionHere) &&
@@ -368,7 +446,7 @@ export async function applyRegionCountryCoherence(
368
446
  * default-country filter hid. `matchSubdivision` turns the region token into `{ name, country }` (null for anything
369
447
  * that isn't a US state or CA province → no-op); the region's full name then resolves it under that country (expanding
370
448
  * the abbreviation the gazetteer FTS index lacks), and the locality is re-scoped to the same country. Leaves both nodes
371
- * untouched unless every gate holds — the subdivision names a different country than the default, the region resolves
449
+ * untouched unless every check holds — the subdivision names a different country than the default, the region resolves
372
450
  * under it, and a same-named locality exists there — so the domestic path stays byte-identical.
373
451
  */
374
452
  async function reconcileRegionCountry(
@@ -9,30 +9,21 @@
9
9
  * before the limit window (so a contained candidate can reach the walk at all), and the resolver
10
10
  * walk partitions AGAIN after its fame/anchor re-ranks (so `rankByImportance` cannot hand the top
11
11
  * slot back to a more-famous uncontained namesake — Richmond VA outscores Richmond, North
12
- * Yorkshire on importance, and without the second partition the lever loses exactly where fame
12
+ * Yorkshire on importance, and without the second partition the change loses exactly where fame
13
13
  * disagrees with the qualifier). Two call sites, one function, one ordering.
14
14
  */
15
15
 
16
- import type { AddressNode } from "@mailwoman/core/decoder"
16
+ import { firstNodeWhere, type AddressNode } from "@mailwoman/core/decoder"
17
17
 
18
18
  /**
19
19
  * Find the first non-empty region-tagged span anywhere in a tree — the qualifier the walk threads onto locality
20
- * lookups. Deliberately the same node the admin-coherence VERDICTS read (the first `region` node), so the lever's
20
+ * lookups. Deliberately the same node the admin-coherence VERDICTS read (the first `region` node), so the change's
21
21
  * firing population and the flag's `contradicted` population are the same rows. A `region` slot can hold a country name
22
22
  * the parser mislabeled ("Moscow, Russia" parses region="Russia") — the backend's qualifier probe answers that too,
23
23
  * because containment is containment whatever tier the container sits at.
24
24
  */
25
25
  export function firstRegionQualifier(roots: readonly AddressNode[]): string | undefined {
26
- const stack = [...roots]
27
-
28
- while (stack.length) {
29
- const n = stack.pop()!
30
-
31
- if (n.tag === "region" && n.value.trim().length) return n.value.trim()
32
- stack.push(...n.children)
33
- }
34
-
35
- return undefined
26
+ return firstNodeWhere(roots, (n) => n.tag === "region" && n.value.trim().length > 0)?.value.trim()
36
27
  }
37
28
 
38
29
  /**
@@ -78,7 +69,7 @@ export function partitionByContainment<T>(
78
69
  }
79
70
 
80
71
  /**
81
- * The trace verdict for one locality pick under the lever — stamped as `metadata.admin_containment` so an inert
72
+ * The trace verdict for one locality pick under the change — stamped as `metadata.admin_containment` so an inert
82
73
  * mechanism is visible in the result rather than silently dead (#1719's rule). Derived from the candidates'
83
74
  * `containedByQualifier` stamps: any `true` → `"contained"`; stamps present but none true → `"no_contained_candidate"`;
84
75
  * no stamps at all → `"unavailable"` (the backend or artifact cannot answer — a pre-sidecar candidate.db, the FTS or
@@ -0,0 +1,10 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ */
6
+
7
+ export * from "#admin/coherence-passes"
8
+ export * from "#admin/containment"
9
+ export * from "#admin/jp-municipality"
10
+ export * from "#admin/winner"
@@ -0,0 +1,97 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ * @file A compound Japanese municipality split into the two units the gazetteer keys separately.
6
+ *
7
+ * The JP model tags `神戸市西区` (city + ward) and `猿島郡五霞町` (county + town) as ONE `municipality` span, which is
8
+ * the postal form, and WOF keys the city, the ward and the town — never the compound. Probed whole, the span misses
9
+ * and the coordinate falls to the prefecture centroid (25–52 km on the JP board). Probed as its trailing unit
10
+ * UNSCOPED it does worse: a bare `西区` resolves a namesake ward in another city (Kobe's answered Fukuoka's, 407 km;
11
+ * 251 of 300 rows against 271 whole). The split is therefore consumed by the resolver walk as a SCOPED pair: the
12
+ * head resolves first, the tail probes as its child, and a namesake outside the head is not admissible.
13
+ */
14
+
15
+ export interface CompoundMunicipality {
16
+ /**
17
+ * The containing unit: the city (`神戸市`) or the county (`猿島郡`).
18
+ */
19
+ head: string
20
+ /**
21
+ * The contained unit: the ward (`西区`) or the town / village (`五霞町`).
22
+ */
23
+ tail: string
24
+ shape: "city_ward" | "county_town"
25
+ }
26
+
27
+ const CITY_WARD = /^(.+?市)(.+区)$/u
28
+ const COUNTY_TOWN = /^(.+?郡)(.+[町村])$/u
29
+
30
+ /**
31
+ * The head and tail of a compound municipality, or null for a plain one (`都城市`, `千代田区`, `東村山市`).
32
+ */
33
+ export function compoundMunicipality(value: string): CompoundMunicipality | null {
34
+ const trimmed = value.trim()
35
+ const cityWard = CITY_WARD.exec(trimmed)
36
+
37
+ if (cityWard) {
38
+ return { head: cityWard[1]!, tail: cityWard[2]!, shape: "city_ward" }
39
+ }
40
+
41
+ const countyTown = COUNTY_TOWN.exec(trimmed)
42
+
43
+ if (countyTown) {
44
+ return { head: countyTown[1]!, tail: countyTown[2]!, shape: "county_town" }
45
+ }
46
+
47
+ return null
48
+ }
49
+
50
+ /**
51
+ * One probe of the gazetteer as the walk makes it: `value` under `scope`, with the parent fallback allowed or withheld.
52
+ */
53
+ export type CompoundMunicipalityProbe<Place, Pick extends { top: Place; metadata?: Record<string, unknown> }> = (
54
+ value: string,
55
+ scope: Place | null,
56
+ parentFallback: boolean
57
+ ) => Promise<Pick | null>
58
+
59
+ function stamp<Pick extends { metadata?: Record<string, unknown> }>(
60
+ pick: Pick | null,
61
+ split: CompoundMunicipality,
62
+ answered: "head" | "tail"
63
+ ): Pick | null {
64
+ return pick ? { ...pick, metadata: { ...pick.metadata, municipality_split: { ...split, answered } } } : null
65
+ }
66
+
67
+ /**
68
+ * A compound municipality probed as a SCOPED pair after the whole span missed: the head under the node's own parent
69
+ * with the walk's ordinary fallback, then the tail as the head's child with the parent fallback WITHHELD, so a namesake
70
+ * ward or town outside the head is never admissible — including one the backend re-admits through its own region-scope
71
+ * fallback (`regionScopeMiss`). A county head usually has no key; the tail then probes under the parent the walk
72
+ * already holds. Answers the tail when it hits, else the head, else null. Two probes at most, each drawn from the
73
+ * caller's budget (`hasBudget`).
74
+ */
75
+ export async function resolveCompoundMunicipality<
76
+ Place extends { regionScopeMiss?: boolean },
77
+ Pick extends { top: Place; metadata?: Record<string, unknown> },
78
+ >(
79
+ value: string,
80
+ parent: Place | null,
81
+ hasBudget: () => boolean,
82
+ probe: CompoundMunicipalityProbe<Place, Pick>
83
+ ): Promise<Pick | null> {
84
+ const split = compoundMunicipality(value)
85
+
86
+ if (!split || !hasBudget()) return null
87
+
88
+ const head = await probe(split.head, parent, true)
89
+
90
+ if (!hasBudget()) return stamp(head, split, "head")
91
+
92
+ const tail = await probe(split.tail, head?.top ?? parent, false)
93
+
94
+ if (tail && !tail.top.regionScopeMiss) return stamp(tail, split, "tail")
95
+
96
+ return stamp(head, split, "head")
97
+ }
@@ -20,26 +20,42 @@ import { PLACETYPE_SPECIFICITY } from "@mailwoman/core/resources/whosonfirst/spe
20
20
  /**
21
21
  * The admin fallback order when the postcode leads — a unit-grade exact hit, or an address system whose area-grade code
22
22
  * is still finer than its locality ({@link areaPostcodeLeadsLocality}).
23
+ *
24
+ * The JP rungs (`municipality`, `district`, `prefecture`) sit beside their Latin counterparts, and `municipality`
25
+ * stands ABOVE `district` on purpose. `subregion` (a county, a Korean 시군구) sits between the postcode and `region`:
26
+ * finer than the region it belongs to, coarser than any postcode. Absent from the ladder it was never the answer, and
27
+ * `부산광역시 해운대구 반송로 910-1` resolved both nodes and reported Busan's point, 3.3 km from the address, over Haeundae's. It
28
+ * stands ABOVE `district` on purpose: a district (大字 / 町名) resolves without its municipality as a parent more often
29
+ * than not, and the unscoped namesake it then picks can be another prefecture's (`市原市大作` → 921 km). Measured on 300 JP
30
+ * board rows @15 km: district-first 202 accepted, municipality-first 271.
23
31
  */
24
32
  export const ADMIN_LADDER_POSTCODE_FIRST: ReadonlyArray<string> = [
25
33
  "postcode",
26
34
  "locality",
35
+ "municipality",
27
36
  "dependent_locality",
37
+ "district",
38
+ "subregion",
28
39
  "region",
40
+ "prefecture",
29
41
  "country",
30
42
  ]
31
43
 
32
44
  /**
33
45
  * The admin fallback order everywhere else: the locality tiers lead and the postcode sits between them and `region`.
34
46
  *
35
- * This is the #945 epoch convention, and it is the DEFAULT rather than the universal answer — which address systems
36
- * leave it is `AREA_POSTCODE_FINER_THAN_LOCALITY`'s question, and that table carries the per-country measurement.
47
+ * This is the #945 epoch convention and the DEFAULT rather than the universal answer — which address systems leave it
48
+ * is `AREA_POSTCODE_FINER_THAN_LOCALITY`'s question, and that table carries the per-country measurement.
37
49
  */
38
50
  export const ADMIN_LADDER_LOCALITY_FIRST: ReadonlyArray<string> = [
39
51
  "locality",
52
+ "municipality",
40
53
  "dependent_locality",
54
+ "district",
41
55
  "postcode",
56
+ "subregion",
42
57
  "region",
58
+ "prefecture",
43
59
  "country",
44
60
  ]
45
61
 
@@ -27,14 +27,14 @@ import type { BackendCapabilityGap, ResolverBackend } from "@mailwoman/core/reso
27
27
  const CONSEQUENTIAL_CAPABILITIES: ReadonlyArray<Omit<BackendCapabilityGap, "backend">> = [
28
28
  {
29
29
  capability: "ancestors",
30
- gates: "hierarchyCompletion",
30
+ option: "hierarchyCompletion",
31
31
  defaultOn: true,
32
32
  degrades:
33
33
  "the containment lineage is never read: a parse that drops the locality of a city-state or dependent locality keeps the gap, and `metadata.ancestors` (the lineage the Nominatim and Photon drop-ins expose) is never populated",
34
34
  },
35
35
  {
36
36
  capability: "coincidentLocalitiesFor",
37
- gates: "hierarchyCompletion",
37
+ option: "hierarchyCompletion",
38
38
  defaultOn: true,
39
39
  degrades:
40
40
  "the dual-role pass never runs: a region that is also a locality under the same name resolves to one role only",
@@ -61,7 +61,7 @@ export function describeCapabilityGaps(backend: ResolverBackend): readonly Backe
61
61
  export function formatCapabilityGaps(gaps: readonly BackendCapabilityGap[]): string {
62
62
  const [first] = gaps
63
63
  const names = gaps.map((g) => `${g.capability}()`).join(", ")
64
- const options = [...new Set(gaps.map((g) => g.gates))].join(", ")
64
+ const options = [...new Set(gaps.map((g) => g.option))].join(", ")
65
65
  const posture = gaps.some((g) => g.defaultOn) ? "default-ON" : "opt-in"
66
66
 
67
67
  return `[resolver] ${first?.backend} lacks ${names} — ${options} (${posture}) silently no-ops; see docs/engineering/reference/resolver-backends.mdx`
@@ -87,7 +87,7 @@ export async function bareCountryCandidate(
87
87
 
88
88
  const top = hits[0]
89
89
 
90
- // The placetype check is load-bearing, not paranoia: a backend that ignores the filter
90
+ // The placetype check is required, not paranoia: a backend that ignores the filter
91
91
  // (several test stubs, and any future partial implementation) would otherwise hand this
92
92
  // race a LOCALITY row wearing a country costume, and the repick would demote the real pick.
93
93
  return top && top.placetype === "country" && top.exactMatch !== false ? top : null
@@ -11,7 +11,7 @@
11
11
  import type { AddressNode } from "@mailwoman/core/decoder"
12
12
  import type { ResolvedPlace } from "@mailwoman/core/resolver"
13
13
 
14
- import type { CoordinateOptionalPlace } from "./postcode-prefix.ts"
14
+ import type { CoordinateOptionalPlace } from "#postcode/prefix"
15
15
 
16
16
  /**
17
17
  * A resolved node carries a real coordinate (placeID set + non-zero lat/lon).
@@ -48,7 +48,7 @@ export function decorateNode(
48
48
  node.source = "resolver"
49
49
  node.sourceID = `${resolved.placetype}:${resolved.id}`
50
50
 
51
- // `0,0` is the gazetteer's UNLOCATED sentinel, not a location in the Gulf of Guinea. Shards carry a lot of it —
51
+ // `0,0` is the gazetteer's UNLOCATED sentinel, not a location in the Gulf of Guinea. Extracts carry a lot of it —
52
52
  // 48,216 of 142,604 JP postcodes, 86,377 GB, 9,708 intl, 414 US — and stamping it produces a node that answers
53
53
  // "yes" to every `lat != null` guard downstream, including the admin ladder's. Absence is the representable form
54
54
  // (`AddressNode.lat` is optional and {@link isResolvedWithCoord} already reads the sentinel this way), so the
@@ -7,7 +7,7 @@
7
7
  * locality comparison and by span-rescore's key guards. Its own module because those would
8
8
  * otherwise import each other for it.
9
9
  *
10
- * `@mailwoman/codex`'s `foldName` (`packages/codex/normalize.ts`) is a near twin and is also
10
+ * `@mailwoman/codex`'s `foldName` (`packages/codex/lib/normalize.ts`) is a near twin and is also
11
11
  * correct; it differs in collapsing every non-alphanumeric RUN, whitespace included. The two are
12
12
  * equivalent on the inputs either sees today. They are kept apart because this one answers to a
13
13
  * comparison contract the resolver owns, not because the codex copy is wrong.
@@ -19,7 +19,7 @@
19
19
  * Marks are DELETED, never spaced. `[^a-z0-9 ]` alone maps the combining cedilla that NFD has just produced to a SPACE,
20
20
  * so `Besançon` keys as `besanc on` and matches nothing it should. The gazetteer side of the same comparison deletes
21
21
  * them — 0 of 32,539 distinct `locality_base` keys in `street-centroids-fr.db` carry a mark — so spacing puts the two
22
- * halves of one comparison on different keys. Order is load-bearing: after the class filter the strip is a no-op.
22
+ * halves of one comparison on different keys. Order is required: after the class filter the strip is a no-op.
23
23
  *
24
24
  * Not fixed here, and worth knowing before trusting the fold on a non-Latin-1 name: a letter with no decomposition is
25
25
  * DROPPED rather than folded (`Łódź` → `odz`, `Đà Nẵng` → `a nang`). That needs a transliteration table, not a regex,
@@ -11,26 +11,21 @@
11
11
  * what used to be `@mailwoman/core/resolver`.
12
12
  */
13
13
 
14
- export { RemoteResolver, serializableResolveOpts } from "./remote-resolver.ts"
14
+ export { RemoteResolver, serializableResolveOpts } from "#remote-resolver"
15
15
 
16
16
  export type {
17
17
  RemoteResolverOpts,
18
18
  ResolveTreeRequest,
19
19
  ResolveTreeResponse,
20
20
  SerializableResolveOpts,
21
- } from "./remote-resolver.ts"
21
+ } from "#remote-resolver"
22
22
 
23
- export { createWOFResolver } from "./resolve.ts"
23
+ export { createWOFResolver } from "#resolve"
24
24
 
25
- export {
26
- COUNTRY_BBOX,
27
- finestResolvedCoordinate,
28
- isImplausibleResolution,
29
- outsideExpectedCountry,
30
- } from "./plausibility.ts"
25
+ export { COUNTRY_BBOX, finestResolvedCoordinate, isImplausibleResolution, outsideExpectedCountry } from "#plausibility"
31
26
 
32
- export type { PlausibilityOpts, PlausibilityVerdict, ResolvedCoordinate } from "./plausibility.ts"
33
- export { foldStreetSurface, isPureTypeVocabulary, pickByStreetEvidence } from "./street-evidence.ts"
27
+ export type { PlausibilityOpts, PlausibilityVerdict, ResolvedCoordinate } from "#plausibility"
28
+ export { foldStreetSurface, isPureTypeVocabulary, pickByStreetEvidence } from "#street/evidence"
34
29
 
35
30
  export type {
36
31
  PickByStreetEvidenceOpts,
@@ -38,20 +33,20 @@ export type {
38
33
  StreetEvidencePick,
39
34
  StreetEvidenceScope,
40
35
  StreetLocalityEvidence,
41
- } from "./street-evidence.ts"
36
+ } from "#street/evidence"
42
37
 
43
38
  export {
44
39
  findPostcodeCountryScope,
45
40
  firstLocalityValue,
46
41
  localityValuesInDocumentOrder,
47
- POSTCODE_COUNTRY_COHERENCE_GATE_KM,
42
+ POSTCODE_COUNTRY_COHERENCE_THRESHOLD_KM,
48
43
  stampPostcodeCountryScope,
49
- } from "./postcode-country-coherence.ts"
44
+ } from "#postcode/country-coherence"
50
45
 
51
- export type { PostcodeCountryScope, PostcodeCountryScopeOpts } from "./postcode-country-coherence.ts"
52
- export { findRescoreCandidate, hasResolvedPlace } from "./span-rescore.ts"
53
- export type { RescoreCandidate, SpanRescoreOptions } from "./span-rescore.ts"
54
- export { adminContainmentVerdict, partitionByContainment } from "./admin-containment.ts"
46
+ export type { PostcodeCountryScope, PostcodeCountryScopeOpts } from "#postcode/country-coherence"
47
+ export { findRescoreCandidate, hasResolvedPlace } from "#span-rescore"
48
+ export type { RescoreCandidate, SpanRescoreOptions } from "#span-rescore"
49
+ export { adminContainmentVerdict, partitionByContainment } from "#admin/containment"
55
50
 
56
51
  export {
57
52
  ADMIN_LADDER_LOCALITY_FIRST,
@@ -61,12 +56,11 @@ export {
61
56
  AREA_GRADE_POSTALCODE_SPECIFICITY,
62
57
  mostSpecificResolved,
63
58
  resolvedSpecificity,
64
- } from "./admin-winner.ts"
59
+ } from "#admin/winner"
65
60
 
66
- export type { ResolvedPostcodeHit, ResolvedSpecificityInput } from "./admin-winner.ts"
61
+ export type { ResolvedPostcodeHit, ResolvedSpecificityInput } from "#admin/winner"
67
62
 
68
63
  // The type contract + placetype helpers live in core (pure types, keep core a leaf). Re-export so
69
64
  // consumers get the whole surface from `@mailwoman/resolver`.
70
- export * from "@mailwoman/core/resolver"
71
65
 
72
- export * from "./rerank.ts"
66
+ export * from "#rerank"
@@ -188,10 +188,11 @@ export interface PlausibilityOpts {
188
188
  }
189
189
 
190
190
  /**
191
- * Decide whether a resolved tree's geocode is implausible for a structured address — the cheap guard the v7 hybrid gate
192
- * runs after routing an input to the neural parser (#38). Trips when the finest resolved place is a bare `country`
193
- * centroid (guard A), or — when the caller supplies `expectedCountry` — when the served coordinate falls outside that
194
- * country's coarse bbox (guard B). An unresolved tree (nothing to serve) is plausible: there is no garbage to serve.
191
+ * Decide whether a resolved tree's geocode is implausible for a structured address — the cheap guard the v7 hybrid
192
+ * check runs after routing an input to the neural parser (#38). Trips when the finest resolved place is a bare
193
+ * `country` centroid (guard A), or — when the caller supplies `expectedCountry` — when the served coordinate falls
194
+ * outside that country's coarse bbox (guard B). An unresolved tree (nothing to serve) is plausible: there is no garbage
195
+ * to serve.
195
196
  */
196
197
  export function isImplausibleResolution(tree: AddressTree, opts: PlausibilityOpts = {}): PlausibilityVerdict {
197
198
  const coordinate = finestResolvedCoordinate(tree)