@mailwoman/core 8.6.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.
Files changed (238) hide show
  1. package/README.md +2 -2
  2. package/api/clock.ts +1 -1
  3. package/api/disk-storage.ts +7 -4
  4. package/api/test-clocks.ts +57 -9
  5. package/api/test-transport.ts +182 -0
  6. package/coarse-placer/coarse-placer.ts +2 -1
  7. package/coarse-placer/tools/build-dataset.ts +2 -2
  8. package/coarse-placer/tools/build-outlier-exposure.ts +2 -2
  9. package/coarse-placer/tools/build-outlier-latin.ts +3 -2
  10. package/coarse-placer/tools/build-outlier-oa.ts +3 -2
  11. package/coarse-placer/tools/eval-latin-offmap.ts +8 -8
  12. package/coarse-placer/tools/eval-openset.ts +20 -12
  13. package/coarse-placer/tools/eval-quant-compare.ts +8 -9
  14. package/coarse-placer/tools/eval.ts +30 -23
  15. package/coarse-placer/tools/probe-frontier.ts +9 -7
  16. package/coarse-placer/tools/quantize.ts +4 -2
  17. package/coarse-placer/tools/train.ts +10 -10
  18. package/collections.ts +2 -128
  19. package/crypto/node.ts +68 -0
  20. package/decoder/build-tree.ts +19 -0
  21. package/env/schema.ts +58 -2
  22. package/fs/zip.ts +297 -0
  23. package/identifiers.ts +48 -0
  24. package/layers/manifest.ts +2 -1
  25. package/locale/profiles/en-us.ts +2 -3
  26. package/locale/profiles/fr-fr.ts +1 -1
  27. package/locale/profiles/ja-jp.ts +7 -7
  28. package/objects.ts +40 -8
  29. package/out/api/clock.d.ts +1 -1
  30. package/out/api/clock.js +1 -1
  31. package/out/api/disk-storage.d.ts +1 -1
  32. package/out/api/disk-storage.d.ts.map +1 -1
  33. package/out/api/disk-storage.js +5 -5
  34. package/out/api/disk-storage.js.map +1 -1
  35. package/out/api/test-clocks.d.ts +2 -2
  36. package/out/api/test-clocks.d.ts.map +1 -1
  37. package/out/api/test-clocks.js +51 -9
  38. package/out/api/test-clocks.js.map +1 -1
  39. package/out/api/test-transport.d.ts +112 -0
  40. package/out/api/test-transport.d.ts.map +1 -0
  41. package/out/api/test-transport.js +84 -0
  42. package/out/api/test-transport.js.map +1 -0
  43. package/out/coarse-placer/coarse-placer.d.ts.map +1 -1
  44. package/out/coarse-placer/coarse-placer.js +2 -1
  45. package/out/coarse-placer/coarse-placer.js.map +1 -1
  46. package/out/coarse-placer/tools/build-dataset.js +1 -2
  47. package/out/coarse-placer/tools/build-dataset.js.map +1 -1
  48. package/out/coarse-placer/tools/build-outlier-exposure.js +1 -2
  49. package/out/coarse-placer/tools/build-outlier-exposure.js.map +1 -1
  50. package/out/coarse-placer/tools/build-outlier-latin.d.ts.map +1 -1
  51. package/out/coarse-placer/tools/build-outlier-latin.js +2 -2
  52. package/out/coarse-placer/tools/build-outlier-latin.js.map +1 -1
  53. package/out/coarse-placer/tools/build-outlier-oa.d.ts.map +1 -1
  54. package/out/coarse-placer/tools/build-outlier-oa.js +2 -2
  55. package/out/coarse-placer/tools/build-outlier-oa.js.map +1 -1
  56. package/out/coarse-placer/tools/eval-latin-offmap.d.ts.map +1 -1
  57. package/out/coarse-placer/tools/eval-latin-offmap.js +5 -8
  58. package/out/coarse-placer/tools/eval-latin-offmap.js.map +1 -1
  59. package/out/coarse-placer/tools/eval-openset.d.ts.map +1 -1
  60. package/out/coarse-placer/tools/eval-openset.js +12 -11
  61. package/out/coarse-placer/tools/eval-openset.js.map +1 -1
  62. package/out/coarse-placer/tools/eval-quant-compare.d.ts.map +1 -1
  63. package/out/coarse-placer/tools/eval-quant-compare.js +7 -9
  64. package/out/coarse-placer/tools/eval-quant-compare.js.map +1 -1
  65. package/out/coarse-placer/tools/eval.d.ts.map +1 -1
  66. package/out/coarse-placer/tools/eval.js +20 -21
  67. package/out/coarse-placer/tools/eval.js.map +1 -1
  68. package/out/coarse-placer/tools/probe-frontier.d.ts.map +1 -1
  69. package/out/coarse-placer/tools/probe-frontier.js +8 -8
  70. package/out/coarse-placer/tools/probe-frontier.js.map +1 -1
  71. package/out/coarse-placer/tools/quantize.d.ts.map +1 -1
  72. package/out/coarse-placer/tools/quantize.js +3 -2
  73. package/out/coarse-placer/tools/quantize.js.map +1 -1
  74. package/out/coarse-placer/tools/train.d.ts.map +1 -1
  75. package/out/coarse-placer/tools/train.js +7 -10
  76. package/out/coarse-placer/tools/train.js.map +1 -1
  77. package/out/collections.d.ts +1 -59
  78. package/out/collections.d.ts.map +1 -1
  79. package/out/collections.js +2 -90
  80. package/out/collections.js.map +1 -1
  81. package/out/crypto/node.d.ts +43 -0
  82. package/out/crypto/node.d.ts.map +1 -0
  83. package/out/crypto/node.js +43 -0
  84. package/out/crypto/node.js.map +1 -0
  85. package/out/decoder/build-tree.d.ts.map +1 -1
  86. package/out/decoder/build-tree.js +17 -0
  87. package/out/decoder/build-tree.js.map +1 -1
  88. package/out/env/index.d.ts +8 -0
  89. package/out/env/index.d.ts.map +1 -1
  90. package/out/env/schema.d.ts +9 -1
  91. package/out/env/schema.d.ts.map +1 -1
  92. package/out/env/schema.js +54 -2
  93. package/out/env/schema.js.map +1 -1
  94. package/out/fs/zip.d.ts +116 -0
  95. package/out/fs/zip.d.ts.map +1 -0
  96. package/out/fs/zip.js +216 -0
  97. package/out/fs/zip.js.map +1 -0
  98. package/out/identifiers.d.ts +23 -0
  99. package/out/identifiers.d.ts.map +1 -1
  100. package/out/identifiers.js +39 -0
  101. package/out/identifiers.js.map +1 -1
  102. package/out/layers/manifest.d.ts.map +1 -1
  103. package/out/layers/manifest.js +2 -1
  104. package/out/layers/manifest.js.map +1 -1
  105. package/out/locale/profiles/en-us.d.ts +2 -3
  106. package/out/locale/profiles/en-us.d.ts.map +1 -1
  107. package/out/locale/profiles/en-us.js +2 -3
  108. package/out/locale/profiles/en-us.js.map +1 -1
  109. package/out/locale/profiles/fr-fr.d.ts +1 -1
  110. package/out/locale/profiles/fr-fr.js +1 -1
  111. package/out/locale/profiles/ja-jp.d.ts +7 -7
  112. package/out/locale/profiles/ja-jp.js +7 -7
  113. package/out/objects.d.ts +18 -2
  114. package/out/objects.d.ts.map +1 -1
  115. package/out/objects.js +29 -3
  116. package/out/objects.js.map +1 -1
  117. package/out/pipeline/index.d.ts +2 -2
  118. package/out/pipeline/index.d.ts.map +1 -1
  119. package/out/pipeline/index.js +1 -1
  120. package/out/pipeline/index.js.map +1 -1
  121. package/out/pipeline/runtime-pipeline.d.ts +1 -1
  122. package/out/pipeline/runtime-pipeline.d.ts.map +1 -1
  123. package/out/pipeline/runtime-pipeline.js +74 -18
  124. package/out/pipeline/runtime-pipeline.js.map +1 -1
  125. package/out/pipeline/span-proposer.d.ts +24 -0
  126. package/out/pipeline/span-proposer.d.ts.map +1 -1
  127. package/out/pipeline/span-proposer.js +36 -1
  128. package/out/pipeline/span-proposer.js.map +1 -1
  129. package/out/pipeline/types.d.ts +155 -3
  130. package/out/pipeline/types.d.ts.map +1 -1
  131. package/out/pipeline/types.js +41 -1
  132. package/out/pipeline/types.js.map +1 -1
  133. package/out/resolver/index.d.ts +3 -1
  134. package/out/resolver/index.d.ts.map +1 -1
  135. package/out/resolver/index.js +1 -0
  136. package/out/resolver/index.js.map +1 -1
  137. package/out/resolver/referential.d.ts +73 -0
  138. package/out/resolver/referential.d.ts.map +1 -0
  139. package/out/resolver/referential.js +71 -0
  140. package/out/resolver/referential.js.map +1 -0
  141. package/out/resolver/types.d.ts +204 -0
  142. package/out/resolver/types.d.ts.map +1 -1
  143. package/out/resolver/types.js.map +1 -1
  144. package/out/resources/index.d.ts +0 -1
  145. package/out/resources/index.d.ts.map +1 -1
  146. package/out/resources/index.js +0 -1
  147. package/out/resources/index.js.map +1 -1
  148. package/out/resources/libpostal.d.ts.map +1 -1
  149. package/out/resources/libpostal.js +3 -4
  150. package/out/resources/libpostal.js.map +1 -1
  151. package/out/resources/whosonfirst/index.d.ts +1 -0
  152. package/out/resources/whosonfirst/index.d.ts.map +1 -1
  153. package/out/resources/whosonfirst/index.js +1 -0
  154. package/out/resources/whosonfirst/index.js.map +1 -1
  155. package/out/resources/whosonfirst/placetypes/Placetype.d.ts.map +1 -1
  156. package/out/resources/whosonfirst/placetypes/Placetype.js +6 -5
  157. package/out/resources/whosonfirst/placetypes/Placetype.js.map +1 -1
  158. package/out/resources/whosonfirst/placetypes/admin.d.ts +12 -3
  159. package/out/resources/whosonfirst/placetypes/admin.d.ts.map +1 -1
  160. package/out/resources/whosonfirst/placetypes/admin.js +1 -1
  161. package/out/resources/whosonfirst/placetypes/admin.js.map +1 -1
  162. package/out/resources/whosonfirst/sharded-repo.d.ts +28 -0
  163. package/out/resources/whosonfirst/sharded-repo.d.ts.map +1 -0
  164. package/out/resources/whosonfirst/sharded-repo.js +58 -0
  165. package/out/resources/whosonfirst/sharded-repo.js.map +1 -0
  166. package/out/scripting/utils/index.d.ts.map +1 -1
  167. package/out/scripting/utils/index.js +2 -2
  168. package/out/scripting/utils/index.js.map +1 -1
  169. package/out/tools/download-libpostal-resources.d.ts.map +1 -1
  170. package/out/tools/download-libpostal-resources.js +1 -0
  171. package/out/tools/download-libpostal-resources.js.map +1 -1
  172. package/out/tools/generate-language-types.d.ts.map +1 -1
  173. package/out/tools/generate-language-types.js +5 -11
  174. package/out/tools/generate-language-types.js.map +1 -1
  175. package/out/utils/data-root.d.ts +20 -6
  176. package/out/utils/data-root.d.ts.map +1 -1
  177. package/out/utils/data-root.js +24 -5
  178. package/out/utils/data-root.js.map +1 -1
  179. package/out/utils/hash.d.ts +6 -0
  180. package/out/utils/hash.d.ts.map +1 -1
  181. package/out/utils/hash.js +8 -0
  182. package/out/utils/hash.js.map +1 -1
  183. package/out/utils/index.d.ts +1 -0
  184. package/out/utils/index.d.ts.map +1 -1
  185. package/out/utils/index.js +1 -0
  186. package/out/utils/index.js.map +1 -1
  187. package/out/utils/jsonl.d.ts +17 -3
  188. package/out/utils/jsonl.d.ts.map +1 -1
  189. package/out/utils/jsonl.js +23 -6
  190. package/out/utils/jsonl.js.map +1 -1
  191. package/out/utils/python-json.d.ts +3 -3
  192. package/out/utils/python-json.js +9 -9
  193. package/out/utils/python-numeric.d.ts +33 -0
  194. package/out/utils/python-numeric.d.ts.map +1 -0
  195. package/out/utils/python-numeric.js +149 -0
  196. package/out/utils/python-numeric.js.map +1 -0
  197. package/out/utils/python-random.d.ts +26 -1
  198. package/out/utils/python-random.d.ts.map +1 -1
  199. package/out/utils/python-random.js +43 -7
  200. package/out/utils/python-random.js.map +1 -1
  201. package/out/utils/repo.d.ts.map +1 -1
  202. package/out/utils/repo.js +18 -0
  203. package/out/utils/repo.js.map +1 -1
  204. package/out/utils/sealed-db.d.ts +12 -0
  205. package/out/utils/sealed-db.d.ts.map +1 -1
  206. package/out/utils/sealed-db.js +32 -1
  207. package/out/utils/sealed-db.js.map +1 -1
  208. package/package.json +34 -7
  209. package/pipeline/index.ts +3 -1
  210. package/pipeline/runtime-pipeline.ts +88 -27
  211. package/pipeline/span-proposer.ts +64 -1
  212. package/pipeline/types.ts +160 -2
  213. package/resolver/index.ts +13 -0
  214. package/resolver/referential.ts +84 -0
  215. package/resolver/types.ts +207 -0
  216. package/resources/index.ts +0 -1
  217. package/resources/libpostal.ts +8 -7
  218. package/resources/whosonfirst/index.ts +1 -0
  219. package/resources/whosonfirst/placetypes/Placetype.ts +13 -8
  220. package/resources/whosonfirst/placetypes/admin.ts +12 -2
  221. package/resources/whosonfirst/sharded-repo.ts +69 -0
  222. package/scripting/utils/index.ts +2 -3
  223. package/tools/download-libpostal-resources.ts +1 -0
  224. package/tools/generate-language-types.ts +5 -14
  225. package/utils/data-root.ts +27 -6
  226. package/utils/hash.ts +9 -0
  227. package/utils/index.ts +1 -0
  228. package/utils/jsonl.ts +26 -7
  229. package/utils/python-json.ts +10 -10
  230. package/utils/python-numeric.ts +168 -0
  231. package/utils/python-random.ts +49 -8
  232. package/utils/repo.ts +18 -0
  233. package/utils/sealed-db.ts +38 -1
  234. package/out/resources/collections.d.ts +0 -22
  235. package/out/resources/collections.d.ts.map +0 -1
  236. package/out/resources/collections.js +0 -69
  237. package/out/resources/collections.js.map +0 -1
  238. package/resources/collections.ts +0 -96
@@ -9,7 +9,7 @@
9
9
  * injected; the coordinator handles composition, timing, fast-path routing, and graceful
10
10
  * degradation when stages are absent.
11
11
  *
12
- * Implementation contract per `docs/articles/plan/reference/STAGES.md`.
12
+ * Implementation contract per `docs/engineering/reference/STAGES.md`.
13
13
  */
14
14
 
15
15
  import type { AddressNode, AddressTree } from "../decoder/types.ts"
@@ -18,7 +18,7 @@ import { prefetchReconcileLookups } from "./reconcile-lookups.ts"
18
18
  import type { ClassifierCandidate } from "./reconcile.ts"
19
19
  import { reconcileSpans } from "./reconcile.ts"
20
20
  import { aggregateSpanLogits } from "./span-logit-aggregation.ts"
21
- import { WORD_CONSISTENCY_SHIP_DEFAULT, deriveInputMode } from "./types.ts"
21
+ import { PipelineFaultStage, WORD_CONSISTENCY_SHIP_DEFAULT, deriveInputMode } from "./types.ts"
22
22
  import type {
23
23
  AddressClassifier,
24
24
  ClassifierOpts,
@@ -28,9 +28,11 @@ import type {
28
28
  LocaleTag,
29
29
  NormalizedInputLite,
30
30
  PhraseProposal,
31
+ PipelineFault,
31
32
  PipelineOpts,
32
33
  PipelineResult,
33
34
  PlacetypePairPassthrough,
35
+ QueryIntentMarker,
34
36
  QueryKindResult,
35
37
  QueryShapeLite,
36
38
  RuntimePipelineStages,
@@ -308,6 +310,9 @@ export async function runPipeline(
308
310
  opts?: PipelineOpts
309
311
  ): Promise<PipelineResult> {
310
312
  const timing: Record<string, number> = {}
313
+ // One list per run, threaded into each `safe*` wrapper. Every return site below surfaces it, so an empty array is a
314
+ // positive statement ("no stage faulted"), not a field that happened not to be set.
315
+ const faults: PipelineFault[] = []
311
316
  const t0 = performance.now()
312
317
 
313
318
  const normalize = stages.normalize ?? identityNormalize
@@ -382,12 +387,26 @@ export async function runPipeline(
382
387
  const kind = await classifyKind(normalized, queryShape, locale)
383
388
  timing["kind-classifier"] = performance.now() - tKind
384
389
 
390
+ // ROAD_TO_V9 §4. The classifier OWNS marker derivation (it is the stage that knows which intent rule fired); the
391
+ // coordinator only lifts the optional field into an always-present array, so an empty array is this coordinator
392
+ // stating that the vocabulary looked. A classifier with no intent vocabulary — including `defaultClassifyKind`
393
+ // above — leaves the field unset and every result carries `[]`, which is the byte-stable pre-§4 behaviour.
394
+ //
395
+ // `declared_ambiguity` is deliberately ABSENT from this list: its trigger is the resolved candidate list's
396
+ // dominance margin, and the measured 0.5-log10 cut behind it lives in `mailwoman`'s eval harness, which core
397
+ // cannot import (the dependency runs the other way). `mailwoman/query-intent.ts` adds it on the geocode path.
398
+ const intentMarkers: QueryIntentMarker[] = kind.intentMarkers ? [...kind.intentMarkers] : []
399
+
385
400
  // POI branch (spec §3.1). Only reachable when a poi-aware kind classifier was wired (the
386
401
  // default classifier never emits `poi_query`), and only acts when the stage is present —
387
402
  // both absent by default, so the flag-off pipeline is byte-identical by construction. A
388
403
  // `null` outcome falls through to the full pipeline: a poi_query kind with no extractable
389
404
  // subject is a mis-detection, and the address path is the safe interpretation.
390
- if (kind.kind === "poi_query" && stages.poiIntent) {
405
+ // `poi_category` (ROAD_TO_V9 §4.4) is the ANCHORLESS subset of `poi_query` — same subject, no place to search
406
+ // near. It routes here identically on purpose: the branch condition is the only place the two would have diverged,
407
+ // and a bare "tacos" reaching the poi-intent stage under a different kind name would have been a routing change
408
+ // dressed up as a vocabulary addition.
409
+ if ((kind.kind === "poi_query" || kind.kind === "poi_category") && stages.poiIntent) {
391
410
  throwIfAborted(opts)
392
411
  const tPoi = performance.now()
393
412
  const poiOutcome = await stages.poiIntent(normalized, locale, effectiveOpts)
@@ -407,6 +426,8 @@ export async function runPipeline(
407
426
  tree,
408
427
  poiIntent: poiOutcome,
409
428
  timing,
429
+ faults,
430
+ intentMarkers,
410
431
  path: "poi",
411
432
  }
412
433
  }
@@ -422,7 +443,7 @@ export async function runPipeline(
422
443
  if (stages.resolver) {
423
444
  throwIfAborted(opts)
424
445
  const tResolve = performance.now()
425
- tree = await safeResolve(stages.resolver, tree, effectiveOpts)
446
+ tree = await safeResolve(faults, stages.resolver, tree, effectiveOpts)
426
447
  timing["resolve"] = performance.now() - tResolve
427
448
  }
428
449
 
@@ -435,6 +456,8 @@ export async function runPipeline(
435
456
  phraseProposals: [],
436
457
  tree,
437
458
  timing,
459
+ faults,
460
+ intentMarkers,
438
461
  path: "fast-path",
439
462
  }
440
463
  }
@@ -447,7 +470,7 @@ export async function runPipeline(
447
470
  if (stages.groupPhrases) {
448
471
  throwIfAborted(opts)
449
472
  const tGroup = performance.now()
450
- phraseProposals = await safeGroupPhrases(stages.groupPhrases, normalized, queryShape, locale)
473
+ phraseProposals = await safeGroupPhrases(faults, stages.groupPhrases, normalized, queryShape, locale)
451
474
  timing["phrase-grouper"] = performance.now() - tGroup
452
475
  }
453
476
 
@@ -553,17 +576,14 @@ export async function runPipeline(
553
576
  throwIfAborted(opts)
554
577
  const tClassify = performance.now()
555
578
 
556
- tree = await safeClassify(
557
- stages.classifier,
558
- normalized.normalized,
559
- queryShape,
560
- stages.fst,
561
- opts?.normalizeCase,
562
- opts?.placetypePair,
563
- stages.streetMorphology,
579
+ tree = await safeClassify(faults, stages.classifier, normalized.normalized, queryShape, {
580
+ fst: stages.fst,
581
+ normalizeCase: opts?.normalizeCase,
582
+ placetypePair: opts?.placetypePair,
583
+ streetMorphology: stages.streetMorphology,
564
584
  // Decision A: explicit caller register wins; otherwise the kind verdict decides. NEVER case-keyed.
565
- opts?.inputMode ?? deriveInputMode(kind.kind)
566
- )
585
+ inputMode: opts?.inputMode ?? deriveInputMode(kind.kind),
586
+ })
567
587
 
568
588
  timing["token-classify"] = performance.now() - tClassify
569
589
  }
@@ -584,7 +604,7 @@ export async function runPipeline(
584
604
  effectiveOpts = opts
585
605
  }
586
606
 
587
- tree = await safeResolve(stages.resolver, tree, effectiveOpts)
607
+ tree = await safeResolve(faults, stages.resolver, tree, effectiveOpts)
588
608
  timing["resolve"] = performance.now() - tResolve
589
609
  }
590
610
 
@@ -597,6 +617,8 @@ export async function runPipeline(
597
617
  phraseProposals,
598
618
  tree,
599
619
  timing,
620
+ faults,
621
+ intentMarkers,
600
622
  path: "full",
601
623
  }
602
624
  }
@@ -615,18 +637,47 @@ function throwIfAborted(opts?: PipelineOpts): void {
615
637
  }
616
638
 
617
639
  /**
618
- * Defensive wrapper: if the classifier throws, return an empty tree rather than abort the pipeline.
640
+ * Normalize a caught throw into a {@link PipelineFault} and append it to the run's fault list.
641
+ *
642
+ * The wrappers below all call this instead of `catch {}`. A bare `catch {}` is what made a classifier crash
643
+ * indistinguishable from a clean no-match (#40 / mailfail finding 4) — the tree came back empty, the grouper-audit
644
+ * refilled it from rule-based proposals, and the caller saw a tidy parse. Degrading is still the right behavior; doing
645
+ * it silently was not.
646
+ */
647
+ function recordFault(faults: PipelineFault[], stage: PipelineFaultStage, cause: unknown): void {
648
+ faults.push({
649
+ stage,
650
+ name: cause instanceof Error ? cause.name : "Error",
651
+ message: cause instanceof Error ? cause.message : String(cause),
652
+ cause,
653
+ })
654
+ }
655
+
656
+ /**
657
+ * Defensive wrapper: if the classifier throws, return an empty tree rather than abort the pipeline — and record the
658
+ * throw on `faults` so the degrade is visible to the caller.
659
+ *
660
+ * The measured reason this matters (mailfail, 2026-08-02): with the 128-piece `pieces`/`logits` desync live, 10 of 110
661
+ * probe inputs crashed the classifier while the pipeline reported success. `size-10kb` — 10 KB of repeated addresses —
662
+ * came back as `{"house_number":"350","street":"5th Ave","locality":"Ave","region":"NY","postcode":"10118"}` off a
663
+ * 3,031-node tree, which reads exactly like a correct parse of one address. The fault list is what lets a caller tell
664
+ * those apart without instrumenting the classifier.
619
665
  */
620
666
  async function safeClassify(
667
+ faults: PipelineFault[],
621
668
  classifier: AddressClassifier,
622
669
  text: string,
623
670
  queryShape: QueryShapeLite,
624
- fst?: FSTMatcherLike,
625
- normalizeCase?: boolean,
626
- placetypePair?: PlacetypePairPassthrough,
627
- streetMorphology?: FSTMatcherLike,
628
- inputMode?: InputMode
671
+ knobs: {
672
+ fst?: FSTMatcherLike
673
+ normalizeCase?: boolean
674
+ placetypePair?: PlacetypePairPassthrough
675
+ streetMorphology?: FSTMatcherLike
676
+ inputMode?: InputMode
677
+ } = {}
629
678
  ): Promise<AddressTree> {
679
+ const { fst, normalizeCase, placetypePair, streetMorphology, inputMode } = knobs
680
+
630
681
  try {
631
682
  // Postcode regex repair on by default (v0.7 #35, operator-signed). #690 normalizeCase forwards as-is —
632
683
  // default-ON at the classifier since #895 (unset runs it; explicit false pins the raw-case parse).
@@ -645,7 +696,9 @@ async function safeClassify(
645
696
  ...(placetypePair !== undefined ? { placetypePair } : {}),
646
697
  ...streetContextGateFor({ fst, streetMorphology }),
647
698
  })
648
- } catch {
699
+ } catch (error) {
700
+ recordFault(faults, PipelineFaultStage.Classifier, error)
701
+
649
702
  return { raw: text, roots: [] }
650
703
  }
651
704
  }
@@ -682,9 +735,10 @@ function streetContextGateFor(stages: { fst?: FSTMatcherLike; streetMorphology?:
682
735
  }
683
736
 
684
737
  /**
685
- * Defensive wrapper: a grouper failure returns an empty proposal list rather than abort.
738
+ * Defensive wrapper: a grouper failure returns an empty proposal list rather than abort, and records the throw.
686
739
  */
687
740
  async function safeGroupPhrases(
741
+ faults: PipelineFault[],
688
742
  groupPhrases: NonNullable<RuntimePipelineStages["groupPhrases"]>,
689
743
  normalized: NormalizedInputLite,
690
744
  shape: QueryShapeLite,
@@ -692,7 +746,9 @@ async function safeGroupPhrases(
692
746
  ): Promise<PhraseProposal[]> {
693
747
  try {
694
748
  return await groupPhrases(normalized, shape, locale)
695
- } catch {
749
+ } catch (error) {
750
+ recordFault(faults, PipelineFaultStage.PhraseGrouper, error)
751
+
696
752
  return []
697
753
  }
698
754
  }
@@ -829,16 +885,21 @@ export function grouperAudit(
829
885
  }
830
886
 
831
887
  /**
832
- * Defensive wrapper: a resolver failure leaves the classifier tree intact.
888
+ * Defensive wrapper: a resolver failure leaves the classifier tree intact, and records the throw. Unresolved-because-
889
+ * the-backend-threw and unresolved-because-nothing-matched produce the same tree, so without the fault the caller
890
+ * cannot tell a dead gazetteer from a genuine no-match.
833
891
  */
834
892
  async function safeResolve(
893
+ faults: PipelineFault[],
835
894
  resolver: NonNullable<RuntimePipelineStages["resolver"]>,
836
895
  tree: AddressTree,
837
896
  opts?: PipelineOpts
838
897
  ): Promise<AddressTree> {
839
898
  try {
840
899
  return await resolver.resolveTree(tree, opts?.resolveOpts)
841
- } catch {
900
+ } catch (error) {
901
+ recordFault(faults, PipelineFaultStage.Resolver, error)
902
+
842
903
  return tree
843
904
  }
844
905
  }
@@ -121,6 +121,30 @@ export interface SpanProposerLexicon {
121
121
  * rather than a unit ("[Building A]" describes; "[Suite 9]" addresses).
122
122
  */
123
123
  weakDesignators: ReadonlySet<string>
124
+ /**
125
+ * The subset of {@link unitDesignators} naming venue-INTERIOR structure ("concourse", "terminal", "wing", "gate", …)
126
+ * rather than a postal secondary unit. Sourced from WOF placetypes + OSM `aeroway`, never from a mail standard — see
127
+ * `@mailwoman/neural`'s `venue-structure.ts`.
128
+ *
129
+ * Membership is carried through to the proposal's `source` so the consuming prior can weight the two provenances
130
+ * differently. It has to: measured 2026-08-02, the model's margin against `I-unit` on a sub-venue IDENTIFIER runs
131
+ * 4.6–5.0 nats (`B` after `Concourse` scores `B-venue` 4.24 while `I-unit` sits 17th of 33), which the shipped
132
+ * unit-designator scale cannot reach — while raising that shared scale far enough drags quote marks and commas into
133
+ * unit spans elsewhere in the corpus. The two classes need different magnitudes because the model has different
134
+ * opinions about them, so the lexicon has to keep them distinguishable.
135
+ */
136
+ venueStructureDesignators: ReadonlySet<string>
137
+ /**
138
+ * Positional words that may PRECEDE a designator ("West Wing", "Upper Concourse") — the mirror of the
139
+ * designator+identifier shape, where the qualifier leads instead of following.
140
+ */
141
+ venueStructureModifiers: ReadonlySet<string>
142
+ /**
143
+ * The subset of {@link venueStructureDesignators} that may take a preceding modifier. Narrower than the full set
144
+ * because some designators form ordinary STREET names in exactly this shape — "East Gate" is a street, "West Wing" is
145
+ * not — so a rule spanning all of them converts correct street parses into sub-venue ones.
146
+ */
147
+ modifierEligibleStructureDesignators: ReadonlySet<string>
124
148
  /**
125
149
  * Global scan regex for delivery-service designator+identifier phrases, built from the codex po_box /
126
150
  * delivery-service tables. Must carry the `g` flag.
@@ -136,6 +160,9 @@ export const EMPTY_SPAN_PROPOSER_LEXICON: SpanProposerLexicon = {
136
160
  unitDesignators: new Set(),
137
161
  levelDesignators: new Set(),
138
162
  weakDesignators: new Set(),
163
+ venueStructureDesignators: new Set(),
164
+ venueStructureModifiers: new Set(),
165
+ modifierEligibleStructureDesignators: new Set(),
139
166
  }
140
167
 
141
168
  //#region Tokenization
@@ -381,13 +408,49 @@ function proposeDesignatorPhrases(
381
408
  // cue family 3 owns punctuated ids
382
409
  if (!isShortIdentifier(next.stripped)) continue
383
410
  const weak = lexicon.weakDesignators.has(lead)
411
+ // Provenance rides the source string: a venue-INTERIOR designator and a postal one produce the same
412
+ // span shape but face different model margins, and the consuming prior weights them apart on this.
413
+ const venueStructure = !isLevel && lexicon.venueStructureDesignators.has(lead)
384
414
 
385
415
  out.push({
386
416
  start: tokens[i]!.strippedStart,
387
417
  end: next.strippedEnd,
388
418
  kind: isLevel ? "LEVEL_PHRASE" : "UNIT_PHRASE",
389
419
  confidence: weak ? 0.5 : 0.85,
390
- source: `designator:${isLevel ? "level" : "unit"}`,
420
+ source: venueStructure ? "designator:venue-structure" : `designator:${isLevel ? "level" : "unit"}`,
421
+ })
422
+ }
423
+
424
+ // MODIFIER + DESIGNATOR ("West Wing", "Upper Concourse") — the mirror of the shape above, where the
425
+ // qualifier leads rather than follows. Emitted at a lower confidence: an identifier AFTER a designator is
426
+ // nearly unambiguous, while a positional word BEFORE one is a shape ordinary street names also take, so
427
+ // this proposal should lose to a confident encoder more readily than that one does.
428
+ for (let i = 1; i < tokens.length; i++) {
429
+ const designator = tokens[i]!.stripped.toLowerCase()
430
+
431
+ if (!lexicon.modifierEligibleStructureDesignators.has(designator)) continue
432
+
433
+ const modifier = tokens[i - 1]!.stripped.toLowerCase()
434
+
435
+ if (!lexicon.venueStructureModifiers.has(modifier)) continue
436
+
437
+ const beforeModifier = tokens[i - 2]
438
+
439
+ // A house number before the modifier makes this a STREET line — "12 East Gate" is an address on East
440
+ // Gate, not a sub-venue of anything. The number is the discriminator the surface itself provides.
441
+ if (beforeModifier && /^\d{1,6}[A-Za-z]?$/.test(beforeModifier.stripped)) continue
442
+
443
+ // A capitalized word before the modifier means the pair sits INSIDE a longer proper name rather than
444
+ // opening one: "Grand Central Terminal" contains "Central Terminal", and proposing that as a unit
445
+ // carves a sub-venue out of the venue's own name. Sub-venue lines lead their segment.
446
+ if (beforeModifier && /^\p{Lu}/u.test(beforeModifier.stripped)) continue
447
+
448
+ out.push({
449
+ start: tokens[i - 1]!.strippedStart,
450
+ end: tokens[i]!.strippedEnd,
451
+ kind: "UNIT_PHRASE",
452
+ confidence: 0.6,
453
+ source: "designator:venue-structure-modifier",
391
454
  })
392
455
  }
393
456
 
package/pipeline/types.ts CHANGED
@@ -10,7 +10,7 @@
10
10
  * query-shape / resolver packages while still composing them at runtime when callers wire them
11
11
  * up.
12
12
  *
13
- * See `docs/articles/plan/reference/STAGES.md` for the full contract this implements.
13
+ * See `docs/engineering/reference/STAGES.md` for the full contract this implements.
14
14
  */
15
15
 
16
16
  import type { AddressTree } from "../decoder/types.ts"
@@ -151,11 +151,113 @@ export type QueryKind =
151
151
  | "landmark"
152
152
  | "poi_query"
153
153
  | "vague"
154
+ /**
155
+ * ROAD_TO_V9 §4 — the query-INTENT vocabulary. Four kinds that describe what the user is ASKING FOR rather than what
156
+ * their string is shaped like. They are ordinary members of this union (intent is vocabulary of the existing Stage
157
+ * 2.5, never a new stage), and each one, when it fires, attaches a {@link QueryIntentMarker} to the result.
158
+ *
159
+ * Two of the four are deliberately RANKED BELOW their structural incumbent and therefore surface in
160
+ * {@link QueryKindResult.alternatives} rather than as the top kind — see the individual docstrings in
161
+ * `@mailwoman/kind-classifier`'s `intent-rules.ts`. That is the D-rule discharge: the top kind is the only thing the
162
+ * coordinator routes on (`deriveInputMode`, `canShortCircuit`, the POI branch), so leaving it untouched is what makes
163
+ * the addition provably answer-neutral on the populations those incumbents already own.
164
+ */
165
+ /**
166
+ * A single coherent place-name carrying no address grammar — no house number, no postcode, no street-type word. A
167
+ * strict REFINEMENT of `locality_only` (which also admits an admin tail: `Paris, FR`), scored just below it so the
168
+ * top kind never moves. Feeds the declared-ambiguity path: a bare toponym whose resolved candidates are not DECISIVE
169
+ * gets a `declared_ambiguity` marker at geocode time.
170
+ */
171
+ | "bare_toponym"
172
+ /**
173
+ * Two coherent toponyms with no address grammar between them — `Paris London`. Classification plus a DECLARED FORK,
174
+ * never a router (ROAD_TO_V9 §4.3): structure alone cannot separate a route pair from a comma-free locality+region
175
+ * fragment (`Moscow Idaho`), so both interpretations are named in the marker and neither wins.
176
+ */
177
+ | "route_pair"
178
+ /**
179
+ * Preposition/deictic locator with no anchor — `gas station near me`, `restaurants nearby`. The query names a
180
+ * category and a relation to the ASKER, and the asker's position is not in the string. Classification only in v9: the
181
+ * marker states that a focus point is required and absent.
182
+ */
183
+ | "near_me"
184
+ /**
185
+ * A bare POI category with nowhere to search — `tacos`, `grocery store`. The anchorless subset of `poi_query`,
186
+ * carrying the resolved `@mailwoman/poi-taxonomy` category id on its marker. Routes exactly as `poi_query` does (the
187
+ * coordinator's POI branch accepts both); resolution against `poi.db` is out of scope.
188
+ */
189
+ | "poi_category"
190
+
191
+ /**
192
+ * The advisory codes an intent kind can raise. Named per the suggestion-layer plan's rules
193
+ * (`docs/superpowers/plans/2026-08-05-suggestion-layer.md` § Naming): never `*Coherence` (that vocabulary belongs to
194
+ * the passes that decide what the answer IS), and never `correction`/`validation`. This surface only ever REPORTS.
195
+ */
196
+ export const QueryIntentCode = {
197
+ /**
198
+ * The query named a place, and the gazetteer's answer for that name is not decisive. Raised at RESOLVE time (the
199
+ * margin is a property of the candidate list, not of the string), so the classifier never emits it.
200
+ */
201
+ DeclaredAmbiguity: "declared_ambiguity",
202
+ /**
203
+ * The query admits two whole readings and the pipeline is not choosing between them. `evidence.interpretations` names
204
+ * both.
205
+ */
206
+ DeclaredFork: "declared_fork",
207
+ /**
208
+ * The query is relative to the asker and no focus point was supplied. `evidence.parameter` names the seam that would
209
+ * carry one.
210
+ */
211
+ FocusPointRequired: "focus_point_required",
212
+ /**
213
+ * The query resolved to a POI taxonomy category. `evidence.categoryID` carries it.
214
+ */
215
+ POICategory: "poi_category",
216
+ } as const
217
+
218
+ export type QueryIntentCode = (typeof QueryIntentCode)[keyof typeof QueryIntentCode]
219
+
220
+ /**
221
+ * One advisory the intent vocabulary raised about a query.
222
+ *
223
+ * Shaped after {@link PipelineFault} on purpose, and for the same reason: the caller needs to tell "the pipeline
224
+ * considered this and had something to say" apart from "the pipeline said nothing". A marker NEVER changes which answer
225
+ * wins — it is additive, attributed, and always accompanied by the ordinary result. `mechanism` follows the
226
+ * `family:rule` convention `PhraseProposal.source` established (`core/pipeline/span-proposer.ts`), so every marker
227
+ * names the rule that produced it rather than asserting itself.
228
+ */
229
+ export interface QueryIntentMarker {
230
+ /**
231
+ * The intent kind that raised this marker. Present in {@link QueryKindResult} as either the top `kind` or an entry in
232
+ * `alternatives` — a marker whose kind appears in neither is a bug in the producer.
233
+ */
234
+ kind: QueryKind
235
+ code: QueryIntentCode
236
+ /**
237
+ * `family:rule` — `kind:bare_toponym`, `kind:route_pair`, `resolver:dominance_margin`. Never `"unknown"`.
238
+ */
239
+ mechanism: string
240
+ /**
241
+ * Human-readable, for a surface that shows it. Not machine-stable; branch on `code`.
242
+ */
243
+ message: string
244
+ /**
245
+ * The measurement behind the marker, so it is auditable rather than assertive. Absent when the rule that fired had
246
+ * nothing to measure (meaning-of-zero: absent, never an empty object).
247
+ */
248
+ evidence?: Record<string, unknown>
249
+ }
154
250
 
155
251
  export interface QueryKindResult {
156
252
  kind: QueryKind
157
253
  confidence: number
158
254
  alternatives: ReadonlyArray<{ kind: QueryKind; confidence: number }>
255
+ /**
256
+ * Advisories raised by the intent vocabulary (ROAD_TO_V9 §4). Optional on this interface — a pre-intent classifier
257
+ * (including `runtime-pipeline.ts`'s built-in default) simply doesn't set it — but `PipelineResult.intentMarkers` is
258
+ * always an array, so a consumer reading the RESULT never has to distinguish "absent" from "empty".
259
+ */
260
+ intentMarkers?: ReadonlyArray<QueryIntentMarker>
159
261
  }
160
262
 
161
263
  /**
@@ -174,6 +276,10 @@ export type InputMode = "fragmented" | "formatted"
174
276
  * (`structured_address`/`po_box`/`intersection`) are the formatted register; single-thing lookups (postcode, locality,
175
277
  * landmark, POI, vague) are fragments. NEVER keyed on case — lowercase is the primary user register (operator
176
278
  * doctrine).
279
+ *
280
+ * The four ROAD_TO_V9 §4 intent kinds are all fragments and all reach the register through the `default` arm, which is
281
+ * why adding them changed no case in this switch: a bare toponym, a route pair, a `near me` and a bare POI category are
282
+ * each a person typing one thing into a search box, never a form submitting a postal record.
177
283
  */
178
284
  export function deriveInputMode(kind: QueryKind): InputMode {
179
285
  switch (kind) {
@@ -308,7 +414,7 @@ export interface FSTMatcherLike {
308
414
  prev: { stateID: number; depth: number },
309
415
  token: string
310
416
  ): { stateID: number; accepted: boolean; depth: number } | null
311
- accepting(stateID: number): Array<{ wofID: number; placetype: string; importance: number }>
417
+ accepting(stateID: number): Array<{ wofID: number; placetype: string; referential: number }>
312
418
  }
313
419
 
314
420
  export interface ClassifierOpts {
@@ -436,6 +542,42 @@ export interface RuntimePipelineStages {
436
542
 
437
543
  export type PipelineTiming = Record<string, number>
438
544
 
545
+ /**
546
+ * The stages whose defensive wrapper degrades instead of aborting the pipeline. One id per `safe*` wrapper in
547
+ * `runtime-pipeline.ts`; the ids are the wrapper's, not the timing map's, because a fault is about the injected stage
548
+ * (`classifier`), not the phase that ran it (`token-classify`).
549
+ */
550
+ export const PipelineFaultStage = {
551
+ Classifier: "classifier",
552
+ PhraseGrouper: "phrase-grouper",
553
+ Resolver: "resolver",
554
+ } as const
555
+
556
+ export type PipelineFaultStage = (typeof PipelineFaultStage)[keyof typeof PipelineFaultStage]
557
+
558
+ /**
559
+ * One stage crash the coordinator caught and degraded past.
560
+ *
561
+ * A fault is NOT an error return: `runPipeline` still resolves, and `tree` still carries whatever the remaining stages
562
+ * could prove. What the fault buys the caller is the ability to tell "the model faulted and the rule-based stages
563
+ * filled the tree back in" apart from "the model ran and found nothing" — which, before #40, was impossible from the
564
+ * outside. See the `safeClassify` docstring for the measured failure this was written against.
565
+ */
566
+ export interface PipelineFault {
567
+ stage: PipelineFaultStage
568
+ /**
569
+ * The thrown value's `name` (`TypeError`, `RangeError`, …), or `"Error"` when something that isn't an `Error` was
570
+ * thrown. Machine-stable enough to branch on; the `cause` carries the rest.
571
+ */
572
+ name: string
573
+ message: string
574
+ /**
575
+ * The value the stage threw, verbatim — kept so a caller can rethrow it or read its stack. Not JSON-serializable in
576
+ * the useful sense; serialize `stage`/`name`/`message` when you need this on a wire.
577
+ */
578
+ cause: unknown
579
+ }
580
+
439
581
  /**
440
582
  * Result of one `runPipeline` call.
441
583
  */
@@ -457,6 +599,22 @@ export interface PipelineResult {
457
599
  */
458
600
  poiIntent?: POIIntentOutcome
459
601
  timing: PipelineTiming
602
+ /**
603
+ * Every stage crash the coordinator caught and degraded past, in the order they happened. **Always present** — an
604
+ * empty array is the coordinator stating that no stage faulted, which is a different claim from a missing field.
605
+ * Non-empty means the tree you are holding was produced with at least one stage down; see {@link PipelineFault}.
606
+ */
607
+ faults: PipelineFault[]
608
+ /**
609
+ * Query-intent advisories (ROAD_TO_V9 §4), lifted from the kind classifier's verdict. **Always present** — an empty
610
+ * array is the coordinator stating that the intent vocabulary examined this query and had nothing to say, which is a
611
+ * different claim from a missing field (the {@link faults} discipline, same reasoning).
612
+ *
613
+ * Nothing here changed which answer won. The markers are advisory by construction: the two intent kinds that could
614
+ * have displaced a structural incumbent are scored below it, and the two that do win the top slot (`near_me`,
615
+ * `poi_category`) route exactly as their incumbents did.
616
+ */
617
+ intentMarkers: QueryIntentMarker[]
460
618
  /**
461
619
  * Which path the coordinator took. `"fast-path"` skipped stages 3-5; `"poi"` took the intent branch.
462
620
  */
package/resolver/index.ts CHANGED
@@ -11,6 +11,16 @@
11
11
  * `@mailwoman/codex`.
12
12
  */
13
13
 
14
+ export {
15
+ compareReferential,
16
+ REFERENTIAL_LOG2_SCALE,
17
+ REFERENTIAL_POPULATION_DIVISOR,
18
+ REFERENTIAL_SATURATION_POPULATION,
19
+ referentialFromPopulation,
20
+ } from "./referential.ts"
21
+
22
+ export type { ReferentiallyRankable } from "./referential.ts"
23
+
14
24
  export {
15
25
  DEFAULT_PLACETYPE_MAP,
16
26
  PLACETYPE_FILTER_GROUPS,
@@ -30,6 +40,9 @@ export type {
30
40
  InterpolatedPointHit,
31
41
  InterpolationLookup,
32
42
  PlacetypeMap,
43
+ PostcodePrefixAncestor,
44
+ PostcodePrefixIndexLike,
45
+ PostcodePrefixNode,
33
46
  ResolveOpts,
34
47
  ResolvedPlace,
35
48
  Resolver,
@@ -0,0 +1,84 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * The REFERENTIAL score and its comparator — the ranking half of the two-score split (ROAD_TO_V9 §2
7
+ * R1, ratified 2026-08-06).
8
+ *
9
+ * THE POLICY. "The importance of a knowledge-base article is not the probability that this is the
10
+ * place the user means." A geocoder ranks by REFERENTIAL likelihood; encyclopedic importance is
11
+ * carried as data and is never a ranking key. Saint-Denis is the canonical case: the
12
+ * Seine-Saint-Denis suburb (pop 96,128) carries encyclopedic 0.1173 and the Aude hamlet (pop 418)
13
+ * carries 0.5683, so encyclopedic ranking inverts the answer every user means, by 4.8x.
14
+ *
15
+ * WHY THIS LIVES IN `@mailwoman/core`. Three packages need the same number and must not drift:
16
+ * `@mailwoman/resolver` (backend-agnostic — it cannot import a backend),
17
+ * `@mailwoman/resolver-wof-sqlite` (the gazetteer schema + both lookups), and the FST builder that
18
+ * stamps referential scores into the decode-bias artifact. `core/resolver/types.ts` already owns the
19
+ * `ResolvedPlace` contract these three share, so the score that contract carries belongs beside it.
20
+ */
21
+
22
+ /**
23
+ * Population divisor in {@link referentialFromPopulation}. A 1,000-person place scores `log2(2)/14` — the curve starts
24
+ * counting at the scale where WOF actually records population.
25
+ */
26
+ export const REFERENTIAL_POPULATION_DIVISOR = 1000
27
+
28
+ /**
29
+ * Log2 denominator in {@link referentialFromPopulation}. 14 puts the ceiling at `2^14 · 1000` people.
30
+ */
31
+ export const REFERENTIAL_LOG2_SCALE = 14
32
+
33
+ /**
34
+ * The population at which {@link referentialFromPopulation} saturates at exactly 1.0: `(2^14 − 1) · 1000` = 16,383,000.
35
+ *
36
+ * Load-bearing, not trivia. Above this the score CLAMPS, so two megacities that population would order (Tokyo ~37 M vs
37
+ * Delhi ~33 M) tie at 1.0. Any ranking keyed on referential alone must break that tie on raw population to stay
38
+ * ordering-identical to the population-first path — which is exactly what {@link compareReferential} does, and why it
39
+ * exists rather than a bare subtraction at each call site.
40
+ */
41
+ export const REFERENTIAL_SATURATION_POPULATION = (2 ** REFERENTIAL_LOG2_SCALE - 1) * REFERENTIAL_POPULATION_DIVISOR
42
+
43
+ /**
44
+ * Population → referential likelihood in [0, 1].
45
+ *
46
+ * `min(1, log2(1 + pop/1000) / 14)` — the formula the FST builder has used for its population fallback since the FST
47
+ * shipped, and the one `gazetteer importance` used for its fallback rows. It is defined ONCE here so the decode-bias
48
+ * artifact's values, the gazetteer's `referential` column, and the resolver's ranking key are the same number by
49
+ * construction rather than by three matching copies.
50
+ *
51
+ * MEANING OF ZERO: an absent population row and a recorded population of 0 both return 0, and 0 means "no population
52
+ * evidence" — the ranking treats it as no boost, never a penalty. WOF carries population for roughly 15% of localities,
53
+ * so absence is the common case and must stay cheap.
54
+ */
55
+ export function referentialFromPopulation(population: number | null | undefined): number {
56
+ if (population === null || population === undefined || population <= 0) return 0
57
+
58
+ return Math.min(1, Math.log2(1 + population / REFERENTIAL_POPULATION_DIVISOR) / REFERENTIAL_LOG2_SCALE)
59
+ }
60
+
61
+ /**
62
+ * A thing that can be ranked referentially. Both fields optional — a candidate with neither sorts last, which is the
63
+ * same place a candidate with no population has always sorted.
64
+ */
65
+ export interface ReferentiallyRankable {
66
+ referential?: number
67
+ population?: number
68
+ }
69
+
70
+ /**
71
+ * The ranking comparator: referential DESC, raw population DESC as the tiebreak. Negative when `a` outranks `b`, so it
72
+ * drops straight into `Array#sort`.
73
+ *
74
+ * The population tiebreak is not a hedge — it is what makes "rank by referential" and "rank by population" the SAME
75
+ * ORDER on every input, because {@link referentialFromPopulation} is strictly increasing below
76
+ * {@link REFERENTIAL_SATURATION_POPULATION} and constant above it. Without the tiebreak this comparator would silently
77
+ * re-order the world's largest cities: a real behavior change, and the one the D-rule would catch.
78
+ *
79
+ * Encyclopedic importance is deliberately not a parameter. Ranking by it is the thing §2 forbids, and a comparator that
80
+ * cannot express it is a stronger guarantee than a comment asking nobody to.
81
+ */
82
+ export function compareReferential(a: ReferentiallyRankable, b: ReferentiallyRankable): number {
83
+ return (b.referential ?? 0) - (a.referential ?? 0) || (b.population ?? 0) - (a.population ?? 0)
84
+ }