@mailwoman/core 7.2.0 → 7.2.1

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 (129) hide show
  1. package/api/APIClient.ts +175 -0
  2. package/api/headless.ts +23 -0
  3. package/api/index.ts +11 -0
  4. package/api/responses.ts +135 -0
  5. package/coarse-placer/coarse-placer.ts +300 -0
  6. package/coarse-placer/featurize.ts +171 -0
  7. package/coarse-placer/tools/build-dataset.ts +223 -0
  8. package/coarse-placer/tools/build-outlier-exposure.ts +172 -0
  9. package/coarse-placer/tools/build-outlier-latin.ts +200 -0
  10. package/coarse-placer/tools/build-outlier-oa.ts +231 -0
  11. package/coarse-placer/tools/eval-latin-offmap.ts +140 -0
  12. package/coarse-placer/tools/eval-openset.ts +519 -0
  13. package/coarse-placer/tools/eval-quant-compare.ts +151 -0
  14. package/coarse-placer/tools/eval.ts +187 -0
  15. package/coarse-placer/tools/fnv-hash.ts +24 -0
  16. package/coarse-placer/tools/index.ts +23 -0
  17. package/coarse-placer/tools/probe-frontier.ts +216 -0
  18. package/coarse-placer/tools/quantize.ts +116 -0
  19. package/coarse-placer/tools/train.ts +244 -0
  20. package/collections.ts +134 -0
  21. package/db/schema.ts +21 -0
  22. package/decoder/build-tree.ts +228 -0
  23. package/decoder/calibration.ts +101 -0
  24. package/decoder/containment.ts +87 -0
  25. package/decoder/index.ts +17 -0
  26. package/decoder/proposals-to-tree.ts +83 -0
  27. package/decoder/resolve-proposal-overlaps.ts +79 -0
  28. package/decoder/serialize-json.ts +70 -0
  29. package/decoder/serialize-tuples.ts +61 -0
  30. package/decoder/serialize-xml.ts +209 -0
  31. package/decoder/types.ts +159 -0
  32. package/decoder/unknown-spans.ts +103 -0
  33. package/decoder/validate-tree.ts +100 -0
  34. package/env/index.ts +42 -0
  35. package/env/load.ts +14 -0
  36. package/env/paths.ts +40 -0
  37. package/env/schema.ts +125 -0
  38. package/errors/index.ts +9 -0
  39. package/errors/schema.ts +155 -0
  40. package/fs/node.ts +38 -0
  41. package/identifiers.ts +58 -0
  42. package/index.ts +13 -0
  43. package/kysley/adapter.ts +29 -0
  44. package/kysley/client.ts +30 -0
  45. package/kysley/dialect-config.ts +30 -0
  46. package/kysley/dialect.ts +67 -0
  47. package/kysley/driver.ts +175 -0
  48. package/layers/index.ts +12 -0
  49. package/layers/manifest.ts +154 -0
  50. package/layers/schema.ts +105 -0
  51. package/lifecycle/ServiceSymbol.ts +95 -0
  52. package/lifecycle/index.ts +11 -0
  53. package/lifecycle/lru-cache.ts +44 -0
  54. package/lifecycle/services.ts +322 -0
  55. package/locale/index.ts +9 -0
  56. package/locale/locale.ts +49 -0
  57. package/locale/profiles/en-us.ts +69 -0
  58. package/locale/profiles/fr-fr.ts +75 -0
  59. package/locale/profiles/index.ts +9 -0
  60. package/locale/profiles/ja-jp.ts +33 -0
  61. package/locale/registry.ts +68 -0
  62. package/logging/index.ts +8 -0
  63. package/logging/shared.ts +145 -0
  64. package/logging/utils.ts +46 -0
  65. package/objects.ts +211 -0
  66. package/package.json +195 -104
  67. package/pipeline/index.ts +46 -0
  68. package/pipeline/reconcile-lookups.ts +108 -0
  69. package/pipeline/reconcile.ts +542 -0
  70. package/pipeline/runtime-pipeline.ts +732 -0
  71. package/pipeline/span-logit-aggregation.ts +151 -0
  72. package/pipeline/span-proposer.ts +587 -0
  73. package/pipeline/types.ts +348 -0
  74. package/policy/defaults.ts +35 -0
  75. package/policy/index.ts +10 -0
  76. package/policy/policy.ts +60 -0
  77. package/policy/proposal-collection.ts +64 -0
  78. package/policy/registry.ts +149 -0
  79. package/resolver/index.ts +29 -0
  80. package/resolver/types.ts +584 -0
  81. package/resources/LocaleIndex.ts +124 -0
  82. package/resources/ResourceMapCache.ts +126 -0
  83. package/resources/collections.ts +93 -0
  84. package/resources/debugging.ts +19 -0
  85. package/resources/git.ts +54 -0
  86. package/resources/index.ts +17 -0
  87. package/resources/languages/index.ts +49 -0
  88. package/resources/languages/types.gen.ts +1368 -0
  89. package/resources/libaddressinput.ts +105 -0
  90. package/resources/libpostal.ts +182 -0
  91. package/resources/locale.ts +23 -0
  92. package/resources/set.ts +179 -0
  93. package/resources/whosonfirst/DataSourceCache.ts +72 -0
  94. package/resources/whosonfirst/PlacetypeDataSource.ts +199 -0
  95. package/resources/whosonfirst/index.ts +10 -0
  96. package/resources/whosonfirst/loader.ts +157 -0
  97. package/resources/whosonfirst/placetypes/Placetype.ts +438 -0
  98. package/resources/whosonfirst/placetypes/admin.ts +173 -0
  99. package/resources/whosonfirst/placetypes/definition.ts +135 -0
  100. package/resources/whosonfirst/placetypes/graph.ts +0 -0
  101. package/resources/whosonfirst/placetypes/index.ts +12 -0
  102. package/resources/whosonfirst/placetypes/mermaid.ts +168 -0
  103. package/resources/whosonfirst/placetypes/tree.ts +46 -0
  104. package/routing/index.ts +208 -0
  105. package/scripting/index.ts +40 -0
  106. package/scripting/utils/index.ts +106 -0
  107. package/tokenization/Graph.ts +50 -0
  108. package/tokenization/Span.ts +297 -0
  109. package/tokenization/index.ts +9 -0
  110. package/tokenization/normalizer.ts +123 -0
  111. package/tools/download-libpostal-resources.ts +98 -0
  112. package/tools/download-ssl-address.ts +99 -0
  113. package/tools/generate-language-types.ts +194 -0
  114. package/tools/index.ts +13 -0
  115. package/types/Classification.ts +211 -0
  116. package/types/classifier.ts +133 -0
  117. package/types/component.ts +75 -0
  118. package/types/index.ts +10 -0
  119. package/types/mapping.ts +81 -0
  120. package/utils/data-root.ts +56 -0
  121. package/utils/hash.ts +27 -0
  122. package/utils/index.ts +14 -0
  123. package/utils/jsonl.ts +43 -0
  124. package/utils/python-json.ts +105 -0
  125. package/utils/python-random.ts +90 -0
  126. package/utils/repo.ts +118 -0
  127. package/utils/sealed-db.ts +85 -0
  128. package/utils/stats.ts +32 -0
  129. package/vitest.config.ts +53 -0
@@ -0,0 +1,587 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Stage 2.7 span proposer — mechanisms M2 + M3 from the punctuation survey
7
+ * (`docs/articles/reviews/2026-06-11-punctuation-survey.md`), the structural half of the
8
+ * sub-premise direction note (`docs/articles/plan/2026-06-11-subpremise-proposer-direction.md`).
9
+ *
10
+ * A pure function over the raw input emitting TYPED span proposals from three cue families:
11
+ *
12
+ * 1. **Paired delimiters (M2)** — balanced `()`, `[]`, `""`, `«»`, `„“` groups propose
13
+ * `ANNOTATION_SPAN` / `QUOTED_SPAN`. Unbalanced delimiters of a class produce NO proposal
14
+ * for that class — the proposer never guesses a missing pair (graceful degradation to
15
+ * today's behavior, per the survey's unbalanced-class read).
16
+ * 2. **Designator + identifier** — the sub-premise grammar (`Apt 4B`, `Suite 500`, `PO Box 19`): a
17
+ * closed-vocabulary leader from the injected codex-backed lexicon followed by a short
18
+ * identifier proposes `UNIT_PHRASE` / `LEVEL_PHRASE` / `PO_BOX_PHRASE`.
19
+ * 3. **Dual-path numeric punctuation (M3, the Pelias PR #56 mechanism)** — `2/14`, `14-16`, `123 1/2`
20
+ * adjacent to a number context emit BOTH readings as alternatives sharing an
21
+ * `alternativeGroup`: the fused single-value reading (`FUSED_NUMBER`) AND the
22
+ * designator-split reading (`SPLIT_UNIT` + `SPLIT_HOUSE_NUMBER`), locale-conditioned by
23
+ * which codex systems the lexicon was built from (the AU/NZ `Flat 2/14` split exists only
24
+ * when those tables are loaded). The proposer never decides between readings — downstream
25
+ * consumers weigh them.
26
+ *
27
+ * The proposals are INFORMATION, not decisions (the #464 lesson): consumers treat them as phrase
28
+ * priors the classifier conditions on and as structural boundaries the decode-side span bridge
29
+ * must not merge across. The classifier can always disagree.
30
+ *
31
+ * Like the phrase grouper's rules, the cues here are structural + provenance-tracked vocabulary
32
+ * (codex tables injected by the caller) — no place names, no guessed designators. Core stays
33
+ * codex-free: `@mailwoman/neural` builds the {@link SpanProposerLexicon} from `@mailwoman/codex`
34
+ * (see `neural/span-proposer-lexicon.ts`).
35
+ */
36
+
37
+ /** Typed kinds a span proposal may carry. See the module doc for the three cue families. */
38
+ export type ProposedSpanKind =
39
+ /** A balanced `()`/`[]` group whose content reads as an aside about the address. */
40
+ | "ANNOTATION_SPAN"
41
+ /**
42
+ * A balanced quote group — the content is likely a NAME (venue/unit); typing is the classifier's job.
43
+ */
44
+ | "QUOTED_SPAN"
45
+ /** Delivery-service designator + identifier ("PO Box 19", "GPO Box 2890", "Private Bag 7"). */
46
+ | "PO_BOX_PHRASE"
47
+ /** Secondary-unit designator + identifier ("Apt 4B", "Suite 500"). */
48
+ | "UNIT_PHRASE"
49
+ /** Level-class designator + identifier ("Floor 3", "FL 12"). */
50
+ | "LEVEL_PHRASE"
51
+ /** Dual-path FUSED reading: the punctuated numeric is ONE value ("123 1/2", "69-10", "14/2"). */
52
+ | "FUSED_NUMBER"
53
+ /** Dual-path SPLIT reading, left side: the sub-premise ("Flat 2" of "Flat 2/14", "3" of "3/45"). */
54
+ | "SPLIT_UNIT"
55
+ /** Dual-path SPLIT reading, right side: the house number ("14" of "Flat 2/14"). */
56
+ | "SPLIT_HOUSE_NUMBER"
57
+
58
+ /** One typed span proposal. Char offsets into the raw input; `end` exclusive. */
59
+ export interface ProposedSpan {
60
+ start: number
61
+ end: number
62
+ kind: ProposedSpanKind
63
+ /** 0..1. Confidence is shape-derived; consumers weight or floor it (it is never a verdict). */
64
+ confidence: number
65
+ /**
66
+ * Alternative readings of ONE surface share a group id (M3 dual-path: the fused and split readings of `2/14` carry
67
+ * the same group). Absent for single-reading proposals.
68
+ */
69
+ alternativeGroup?: number
70
+ /**
71
+ * Provenance: which cue family + rule emitted this ("paired:()", "designator:unit", "slash:au-split").
72
+ */
73
+ source: string
74
+ }
75
+
76
+ /**
77
+ * Vocabulary the proposer conditions on — built from `@mailwoman/codex` tables by the caller (`buildCodexSpanLexicon`
78
+ * in `@mailwoman/neural`). All token sets are lowercase. An empty lexicon (the default) limits the proposer to the
79
+ * paired-delimiter cue family.
80
+ */
81
+ export interface SpanProposerLexicon {
82
+ /**
83
+ * Codex system codes the lexicon was built from ("us", "au", "nz", …) — drives M3 locale conditioning.
84
+ */
85
+ systems: ReadonlySet<string>
86
+ /** Leading secondary-unit designator tokens (USPS Pub-28 C2 variants: "apt", "ste", "unit", …). */
87
+ unitDesignators: ReadonlySet<string>
88
+ /** Level-class designator tokens ("floor", "fl", "bsmt", "ph", …) — typed LEVEL_PHRASE. */
89
+ levelDesignators: ReadonlySet<string>
90
+ /**
91
+ * Descriptive designators ("building", "rear", "side", …) that, inside a bracketed group, read as annotation content
92
+ * rather than a unit ("[Building A]" describes; "[Suite 9]" addresses).
93
+ */
94
+ weakDesignators: ReadonlySet<string>
95
+ /**
96
+ * Global scan regex for delivery-service designator+identifier phrases, built from the codex po_box /
97
+ * delivery-service tables. Must carry the `g` flag.
98
+ */
99
+ deliveryService?: RegExp
100
+ }
101
+
102
+ /** Empty lexicon — paired-delimiter proposals only. */
103
+ export const EMPTY_SPAN_PROPOSER_LEXICON: SpanProposerLexicon = {
104
+ systems: new Set(),
105
+ unitDesignators: new Set(),
106
+ levelDesignators: new Set(),
107
+ weakDesignators: new Set(),
108
+ }
109
+
110
+ // ---------------------------------------------------------------------------
111
+ // Tokenization (offset-preserving, punctuation-stripped match bodies)
112
+ // ---------------------------------------------------------------------------
113
+
114
+ interface RawToken {
115
+ /** Whitespace-delimited body as written. */
116
+ body: string
117
+ start: number
118
+ end: number
119
+ /** Body with leading/trailing punctuation stripped (for matching); offsets of the stripped core. */
120
+ stripped: string
121
+ strippedStart: number
122
+ strippedEnd: number
123
+ }
124
+
125
+ const EDGE_PUNCT = /[\s,;:.()[\]"'«»„“”]/
126
+
127
+ function tokenize(text: string): RawToken[] {
128
+ const out: RawToken[] = []
129
+ let i = 0
130
+
131
+ while (i < text.length) {
132
+ while (i < text.length && /\s/.test(text[i]!)) {
133
+ i++
134
+ }
135
+
136
+ if (i >= text.length) break
137
+ const start = i
138
+
139
+ while (i < text.length && !/\s/.test(text[i]!)) {
140
+ i++
141
+ }
142
+ const body = text.slice(start, i)
143
+ let s = 0
144
+ let e = body.length
145
+
146
+ while (s < e && EDGE_PUNCT.test(body[s]!)) {
147
+ s++
148
+ }
149
+
150
+ while (e > s && EDGE_PUNCT.test(body[e - 1]!)) {
151
+ e--
152
+ }
153
+ out.push({
154
+ body,
155
+ start,
156
+ end: i,
157
+ stripped: body.slice(s, e),
158
+ strippedStart: start + s,
159
+ strippedEnd: start + e,
160
+ })
161
+ }
162
+
163
+ return out
164
+ }
165
+
166
+ // ---------------------------------------------------------------------------
167
+ // Cue family 1 — paired delimiters (M2)
168
+ // ---------------------------------------------------------------------------
169
+
170
+ /**
171
+ * Find balanced pairs for one open/close class. Returns null when ANY delimiter of the class is unbalanced (stray
172
+ * opener or closer) — the caller emits nothing for the class.
173
+ */
174
+ function findBalancedPairs(text: string, open: string, close: string): Array<{ open: number; close: number }> | null {
175
+ const stack: number[] = []
176
+ const out: Array<{ open: number; close: number }> = []
177
+
178
+ for (let i = 0; i < text.length; i++) {
179
+ const ch = text[i]!
180
+
181
+ if (ch === open) {
182
+ stack.push(i)
183
+ } else if (ch === close) {
184
+ const o = stack.pop()
185
+
186
+ if (o === undefined) return null
187
+ out.push({ open: o, close: i })
188
+ }
189
+ }
190
+
191
+ return stack.length > 0 ? null : out
192
+ }
193
+
194
+ /** Same-character quote pairing ("…"): consecutive occurrences pair up; an odd count is unbalanced. */
195
+ function findSameCharPairs(text: string, ch: string): Array<{ open: number; close: number }> | null {
196
+ const positions: number[] = []
197
+
198
+ for (let i = 0; i < text.length; i++)
199
+ if (text[i] === ch) {
200
+ positions.push(i)
201
+ }
202
+
203
+ if (positions.length % 2 !== 0) return null
204
+ const out: Array<{ open: number; close: number }> = []
205
+
206
+ for (let i = 0; i < positions.length; i += 2) {
207
+ out.push({ open: positions[i]!, close: positions[i + 1]! })
208
+ }
209
+
210
+ return out
211
+ }
212
+
213
+ /**
214
+ * Shape-derived annotation confidence (M2: "confidence from balance + content shape"):
215
+ *
216
+ * - Content that is EXACTLY a strong designator + identifier ("Suite 9") is probably a real component written in brackets
217
+ * (gold convention 2) → very low annotation confidence, letting the designator cue own the span.
218
+ * - Lowercase- or digit-leading content ("rear entrance", "2nd floor", "code 2580") is the instruction/aside shape →
219
+ * high.
220
+ * - A short capitalized group at the very END of the input ("(Australia)", "[New Zealand]") is the trailing-component
221
+ * shape (often a country) → low, below typical consumer floors.
222
+ * - Everything else (capitalized mid-string: "[Building A]", "(The White House)") → moderate.
223
+ */
224
+ function annotationConfidence(content: string, atEndOfInput: boolean, lexicon: SpanProposerLexicon): number {
225
+ const tokens = content.split(/\s+/).filter(Boolean)
226
+
227
+ if (tokens.length === 0) return 0
228
+
229
+ if (tokens.length === 2) {
230
+ const lead = tokens[0]!.toLowerCase().replace(/\.$/, "")
231
+ const strong =
232
+ (lexicon.unitDesignators.has(lead) || lexicon.levelDesignators.has(lead)) && !lexicon.weakDesignators.has(lead)
233
+
234
+ if (strong && isShortIdentifier(tokens[1]!)) return 0.25
235
+ }
236
+
237
+ if (/^[\p{Ll}0-9]/u.test(content)) return 0.9
238
+
239
+ if (atEndOfInput && tokens.length <= 3) return 0.45
240
+
241
+ return 0.75
242
+ }
243
+
244
+ function proposePairedDelimiters(text: string, lexicon: SpanProposerLexicon): ProposedSpan[] {
245
+ const out: ProposedSpan[] = []
246
+ const lastNonSpace = text.trimEnd().length
247
+
248
+ const bracketClasses: Array<[string, string]> = [
249
+ ["(", ")"],
250
+ ["[", "]"],
251
+ ]
252
+
253
+ for (const [open, close] of bracketClasses) {
254
+ const pairs = findBalancedPairs(text, open, close)
255
+
256
+ if (!pairs) continue
257
+
258
+ // unbalanced — never guess the missing pair
259
+ for (const p of pairs) {
260
+ const content = text.slice(p.open + 1, p.close).trim()
261
+
262
+ if (!content) continue
263
+ const atEnd = p.close >= lastNonSpace - 1
264
+ out.push({
265
+ start: p.open,
266
+ end: p.close + 1,
267
+ kind: "ANNOTATION_SPAN",
268
+ confidence: annotationConfidence(content, atEnd, lexicon),
269
+ source: `paired:${open}${close}`,
270
+ })
271
+ }
272
+ }
273
+
274
+ const quotePairFinders: Array<() => Array<{ open: number; close: number }> | null> = [
275
+ () => findSameCharPairs(text, '"'),
276
+ () => findBalancedPairs(text, "“", "”"), // “ ”
277
+ () => findBalancedPairs(text, "«", "»"), // « »
278
+ // „…“ (low-9 opener, German/Czech): closes with “ — only scanned when a „ is present, so the
279
+ // “ ” class above (which would see a stray “) is skipped for such inputs.
280
+ ]
281
+ const hasLow9 = text.includes("„")
282
+
283
+ for (const [idx, find] of quotePairFinders.entries()) {
284
+ if (hasLow9 && idx === 1) continue
285
+ const pairs = find()
286
+
287
+ if (!pairs) continue
288
+
289
+ for (const p of pairs) {
290
+ const content = text.slice(p.open + 1, p.close).trim()
291
+
292
+ if (!content) continue
293
+ out.push({ start: p.open, end: p.close + 1, kind: "QUOTED_SPAN", confidence: 0.8, source: "paired:quote" })
294
+ }
295
+ }
296
+
297
+ if (hasLow9) {
298
+ const pairs = findBalancedPairs(text, "„", "“")
299
+
300
+ if (pairs) {
301
+ for (const p of pairs) {
302
+ const content = text.slice(p.open + 1, p.close).trim()
303
+
304
+ if (!content) continue
305
+ out.push({ start: p.open, end: p.close + 1, kind: "QUOTED_SPAN", confidence: 0.8, source: "paired:quote" })
306
+ }
307
+ }
308
+ }
309
+
310
+ return out
311
+ }
312
+
313
+ // ---------------------------------------------------------------------------
314
+ // Cue family 2 — designator + identifier (the sub-premise grammar)
315
+ // ---------------------------------------------------------------------------
316
+
317
+ /** Short identifier shapes per the designator grammar: "4B", "500", "#104", "B", "B99". */
318
+ function isShortIdentifier(body: string): boolean {
319
+ return /^#?\d{1,6}[A-Za-z]{0,2}$/.test(body) || /^[A-Za-z]$/.test(body) || /^[A-Za-z]\d{1,4}$/.test(body)
320
+ }
321
+
322
+ function proposeDesignatorPhrases(
323
+ text: string,
324
+ tokens: readonly RawToken[],
325
+ lexicon: SpanProposerLexicon
326
+ ): ProposedSpan[] {
327
+ const out: ProposedSpan[] = []
328
+
329
+ for (let i = 0; i < tokens.length - 1; i++) {
330
+ const lead = tokens[i]!.stripped.toLowerCase()
331
+ const isUnit = lexicon.unitDesignators.has(lead)
332
+ const isLevel = lexicon.levelDesignators.has(lead)
333
+
334
+ if (!isUnit && !isLevel) continue
335
+ const next = tokens[i + 1]!
336
+
337
+ if (next.stripped.includes("/") || next.stripped.includes("-")) continue
338
+
339
+ // cue family 3 owns punctuated ids
340
+ if (!isShortIdentifier(next.stripped)) continue
341
+ const weak = lexicon.weakDesignators.has(lead)
342
+ out.push({
343
+ start: tokens[i]!.strippedStart,
344
+ end: next.strippedEnd,
345
+ kind: isLevel ? "LEVEL_PHRASE" : "UNIT_PHRASE",
346
+ confidence: weak ? 0.5 : 0.85,
347
+ source: `designator:${isLevel ? "level" : "unit"}`,
348
+ })
349
+ }
350
+
351
+ if (lexicon.deliveryService) {
352
+ // Fresh lastIndex per call — the lexicon regex is shared.
353
+ const re = new RegExp(lexicon.deliveryService.source, lexicon.deliveryService.flags)
354
+
355
+ for (const m of text.matchAll(re)) {
356
+ out.push({
357
+ start: m.index,
358
+ end: m.index + m[0].length,
359
+ kind: "PO_BOX_PHRASE",
360
+ confidence: 0.9,
361
+ source: "designator:delivery-service",
362
+ })
363
+ }
364
+ }
365
+
366
+ return out
367
+ }
368
+
369
+ // ---------------------------------------------------------------------------
370
+ // Cue family 3 — dual-path numeric punctuation (M3)
371
+ // ---------------------------------------------------------------------------
372
+
373
+ const SLASH_COMPOUND = /^(\d{1,4}[A-Za-z]?)\/(\d{1,5}[A-Za-z]?)$/
374
+ const HYPHEN_COMPOUND = /^(\d{1,4})-(\d{1,5})$/
375
+ const FRACTION = /^\d\/\d$/
376
+
377
+ /**
378
+ * #481 item 7: the "plausible but genuinely ambiguous" proposal confidence — a FUSED_NUMBER reading that is real but
379
+ * not the only reading of the token (a trailing-fused slash compound, a hyphen at house-number position). Deliberately
380
+ * BELOW the confident readings (0.8–0.9) and above coin-flip, and the same operating point as the phrase grouper's
381
+ * `NEUTRAL_PROPOSAL_CONFIDENCE` — both stages express "emit, but don't let this outrank a confident reading" alike.
382
+ */
383
+ const AMBIGUOUS_PROPOSAL_CONFIDENCE = 0.55
384
+
385
+ /**
386
+ * Words that lead NUMBERED ROADS ("Hwy 50/89", "Route 1/9", "I-95") — a bounded structural category (road-type
387
+ * leaders), mirroring the phrase grouper's street-type sets. The leading-designator-shape fallback must not read them
388
+ * as sub-premise designators: a slash after a road leader is a route concurrency, not an AU unit/house split.
389
+ */
390
+ const ROAD_LEADERS: ReadonlySet<string> = new Set(["hwy", "highway", "route", "rte", "sr", "cr", "interstate", "loop"])
391
+
392
+ function proposeNumericReadings(
393
+ tokens: readonly RawToken[],
394
+ lexicon: SpanProposerLexicon,
395
+ nextGroup: () => number
396
+ ): ProposedSpan[] {
397
+ const out: ProposedSpan[] = []
398
+ const hasAuNz = lexicon.systems.has("au") || lexicon.systems.has("nz")
399
+
400
+ for (let i = 0; i < tokens.length; i++) {
401
+ const t = tokens[i]!
402
+ const prev = i > 0 ? tokens[i - 1] : undefined
403
+ const prevLead = prev?.stripped.toLowerCase() ?? ""
404
+ const prevIsDesignator = lexicon.unitDesignators.has(prevLead) || lexicon.levelDesignators.has(prevLead)
405
+
406
+ // USPS half address: "123 1/2" — the fraction belongs to house_number (one fused value).
407
+ if (lexicon.systems.has("us") && FRACTION.test(t.stripped) && prev && /^\d{1,5}$/.test(prev.stripped)) {
408
+ out.push({
409
+ start: prev.strippedStart,
410
+ end: t.strippedEnd,
411
+ kind: "FUSED_NUMBER",
412
+ confidence: 0.85,
413
+ source: "fraction:usps-half-address",
414
+ })
415
+ continue
416
+ }
417
+
418
+ const slash = SLASH_COMPOUND.exec(t.stripped)
419
+
420
+ if (slash) {
421
+ const leftEnd = t.strippedStart + slash[1]!.length
422
+ const rightStart = leftEnd + 1
423
+ // Reading A context: a unit/level designator leads ("Unit 4/22", "Flat 2/14" via the
424
+ // leading-shape fallback below). Reading B context: the compound itself leads the address
425
+ // ("3/45 Wattle St" — the AU/NZ bare sub-premise shape, only proposed when those codex
426
+ // systems are loaded).
427
+ const leadingShape =
428
+ !prevIsDesignator &&
429
+ prev !== undefined &&
430
+ i === 1 &&
431
+ /^\p{Lu}[\p{L}]{1,7}$/u.test(prev.stripped) &&
432
+ !ROAD_LEADERS.has(prevLead) &&
433
+ hasAuNz
434
+
435
+ if (prevIsDesignator || leadingShape) {
436
+ const group = nextGroup()
437
+ const conf = prevIsDesignator ? (hasAuNz ? 0.85 : 0.6) : 0.7
438
+ out.push({
439
+ start: prev!.strippedStart,
440
+ end: leftEnd,
441
+ kind: "SPLIT_UNIT",
442
+ confidence: conf,
443
+ alternativeGroup: group,
444
+ source: prevIsDesignator ? "slash:designator-split" : "slash:leading-designator-shape",
445
+ })
446
+ out.push({
447
+ start: rightStart,
448
+ end: t.strippedEnd,
449
+ kind: "SPLIT_HOUSE_NUMBER",
450
+ confidence: conf,
451
+ alternativeGroup: group,
452
+ source: "slash:designator-split",
453
+ })
454
+ out.push({
455
+ start: t.strippedStart,
456
+ end: t.strippedEnd,
457
+ kind: "FUSED_NUMBER",
458
+ confidence: 0.3,
459
+ alternativeGroup: group,
460
+ source: "slash:fused-alternative",
461
+ })
462
+ } else if (i === 0 && hasAuNz && tokens.length > 1) {
463
+ const group = nextGroup()
464
+ out.push({
465
+ start: t.strippedStart,
466
+ end: leftEnd,
467
+ kind: "SPLIT_UNIT",
468
+ confidence: 0.75,
469
+ alternativeGroup: group,
470
+ source: "slash:bare-leading-split",
471
+ })
472
+ out.push({
473
+ start: rightStart,
474
+ end: t.strippedEnd,
475
+ kind: "SPLIT_HOUSE_NUMBER",
476
+ confidence: 0.75,
477
+ alternativeGroup: group,
478
+ source: "slash:bare-leading-split",
479
+ })
480
+ out.push({
481
+ start: t.strippedStart,
482
+ end: t.strippedEnd,
483
+ kind: "FUSED_NUMBER",
484
+ confidence: 0.45,
485
+ alternativeGroup: group,
486
+ source: "slash:fused-alternative",
487
+ })
488
+ } else if (prev && /^\p{Lu}[\p{L}]{3,}$/u.test(prev.stripped)) {
489
+ // Trailing European form ("Hauptstraße 14/2") — one fused value after the street name.
490
+ // The ≥4-char guard keeps short street-type leaders ("Hwy 50/89") out of this reading.
491
+ out.push({
492
+ start: t.strippedStart,
493
+ end: t.strippedEnd,
494
+ kind: "FUSED_NUMBER",
495
+ confidence: AMBIGUOUS_PROPOSAL_CONFIDENCE,
496
+ source: "slash:trailing-fused",
497
+ })
498
+ }
499
+ continue
500
+ }
501
+
502
+ const hyphen = HYPHEN_COMPOUND.exec(t.stripped)
503
+
504
+ if (hyphen) {
505
+ // ZIP+4 shape is a postcode, not a house number — never propose a reading for it.
506
+ if (hyphen[1]!.length === 5) continue
507
+ const next = i + 1 < tokens.length ? tokens[i + 1] : undefined
508
+ const leftEnd = t.strippedStart + hyphen[1]!.length
509
+
510
+ if (prevIsDesignator) {
511
+ const group = nextGroup()
512
+ out.push({
513
+ start: prev!.strippedStart,
514
+ end: leftEnd,
515
+ kind: "SPLIT_UNIT",
516
+ confidence: 0.45,
517
+ alternativeGroup: group,
518
+ source: "hyphen:designator-split",
519
+ })
520
+ out.push({
521
+ start: leftEnd + 1,
522
+ end: t.strippedEnd,
523
+ kind: "SPLIT_HOUSE_NUMBER",
524
+ confidence: 0.45,
525
+ alternativeGroup: group,
526
+ source: "hyphen:designator-split",
527
+ })
528
+ out.push({
529
+ start: t.strippedStart,
530
+ end: t.strippedEnd,
531
+ kind: "FUSED_NUMBER",
532
+ confidence: 0.6,
533
+ alternativeGroup: group,
534
+ source: "hyphen:fused-alternative",
535
+ })
536
+ } else if (next && (/^\p{Lu}/u.test(next.stripped) || /^\d{1,4}(?:st|nd|rd|th)$/i.test(next.stripped))) {
537
+ // House-number position (a street follows — capitalized or ordinal): "69-10 47th Ave",
538
+ // "14-16 Smith St".
539
+ // Fused only — whether it is a Queens label or a range is not the parser's call (OSM
540
+ // models the difference with a separate tag, not syntax).
541
+ out.push({
542
+ start: t.strippedStart,
543
+ end: t.strippedEnd,
544
+ kind: "FUSED_NUMBER",
545
+ confidence: AMBIGUOUS_PROPOSAL_CONFIDENCE,
546
+ source: "hyphen:house-number-position",
547
+ })
548
+ }
549
+ }
550
+ }
551
+
552
+ return out
553
+ }
554
+
555
+ // ---------------------------------------------------------------------------
556
+ // Entry point
557
+ // ---------------------------------------------------------------------------
558
+
559
+ /**
560
+ * Propose typed spans over `text`. Pure and synchronous; safe to run on every parse. Proposals may overlap freely
561
+ * ("possibilities not constraints"); alternatives of one surface share an `alternativeGroup`. Sorted by `start`, then
562
+ * descending confidence.
563
+ *
564
+ * Designator and numeric proposals fully inside a confident (≥ 0.6) `ANNOTATION_SPAN` are suppressed — bracketed asides
565
+ * describe the address ("(Apt 4 around back)"), and the annotation proposal already carries the span. Content inside
566
+ * QUOTED_SPANs is NOT suppressed (quotes wrap names, not asides).
567
+ */
568
+ export function proposeSpans(text: string, lexicon: SpanProposerLexicon = EMPTY_SPAN_PROPOSER_LEXICON): ProposedSpan[] {
569
+ if (text.length === 0) return []
570
+ let groupCounter = 0
571
+ const nextGroup = (): number => groupCounter++
572
+
573
+ const paired = proposePairedDelimiters(text, lexicon)
574
+ const tokens = tokenize(text)
575
+ const inner = [
576
+ ...proposeDesignatorPhrases(text, tokens, lexicon),
577
+ ...proposeNumericReadings(tokens, lexicon, nextGroup),
578
+ ]
579
+
580
+ const confidentAnnotations = paired.filter((p) => p.kind === "ANNOTATION_SPAN" && p.confidence >= 0.6)
581
+ const survivors = inner.filter((p) => !confidentAnnotations.some((a) => p.start >= a.start && p.end <= a.end))
582
+
583
+ const out = [...paired, ...survivors]
584
+ out.sort((a, b) => (a.start !== b.start ? a.start - b.start : b.confidence - a.confidence))
585
+
586
+ return out
587
+ }