@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,542 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * `reconcileSpans` — Stage 5 joint-decoding path.
7
+ *
8
+ * Today's runtime Stage 5 (in `runtime-pipeline.ts`) just keeps the classifier-emitted spans in
9
+ * start order. That fallback covers callers who don't yet have top-k inputs from Stages 2.7 / 3 /
10
+ * 6. This file is the **opt-in** joint-decoding path that turns Stage 5 from a sort into a
11
+ * reconciler: pick the parse tree that maximizes
12
+ *
13
+ * ```
14
+ * ∏ phrase_grouper_confidence
15
+ * × classifier_confidence
16
+ * × resolver_score
17
+ * × concordance_bonus(parent_id chain)
18
+ * ```
19
+ *
20
+ * Closes the kryptonite catalogue (`NY-NY Steakhouse, Houston, TX`, `Paris, Texas`, `Saint
21
+ * Petersburg, FL`, `Buffalo Buffalo`) where today's argmax-per-stage produces internally-
22
+ * inconsistent parses that the layer above can't repair.
23
+ *
24
+ * The implementation is a beam search over candidate slots — each slot is one `(phrase_span,
25
+ * classifier_tag, resolver_place)` triple. Three knobs prune the cross product: `kSpan` (de-duped
26
+ * phrase span proposals), `kTag` (classifier tag interpretations per span), and `kResolver`
27
+ * (resolver candidates per `(span, tag)`). Concordance scoring is incremental — when a slot is
28
+ * added, we check the new place's `parent_id` chain against the running admin assignment and
29
+ * adjust the running score before pruning.
30
+ *
31
+ * The Thread C-s classifier top-k contract is mocked locally for v0.5.0 (see `ClassifierCandidate`
32
+ * below). The real classifier output adapter ships with `@mailwoman/neural` once Thread C-s
33
+ * lands; the existing `ResolvedPlace` shape from `@mailwoman/core/resolver` is what backs the
34
+ * resolver-candidates axis (parent_id chains live there).
35
+ *
36
+ * See `docs/articles/plan/phases/PHASE_8_v0_5_0_fresh_slate.md` § D for the v0.5.0 context and
37
+ * `docs/articles/concepts/the-knowledge-ladder.md` § Reconcile for the design rationale.
38
+ */
39
+
40
+ import type { AddressNode, AddressTree, ComponentTag } from "../decoder/types.ts"
41
+ import type { ResolvedPlace } from "../resolver/types.ts"
42
+ import type { PhraseProposal } from "./types.ts"
43
+
44
+ /**
45
+ * One classifier interpretation for one input span. Pins the Thread C-s contract for the reconciler — the real
46
+ * classifier emits this directly once that thread lands. Until then, tests hand-build a list of these to simulate top-k
47
+ * output.
48
+ *
49
+ * The classifier may emit multiple candidates for the same span (different tag hypotheses); the reconciler treats those
50
+ * as the top-k tag axis. Candidates whose `span` does not exactly match a phrase proposal's span are ignored — the
51
+ * phrase grouper is the boundary-discovery authority.
52
+ */
53
+ export interface ClassifierCandidate {
54
+ span: { start: number; end: number }
55
+ tag: ComponentTag
56
+ /** Calibrated confidence in [0, 1]. */
57
+ score: number
58
+ }
59
+
60
+ /**
61
+ * Resolver lookup for the (span, tag) axis. In production wraps a `ResolverBackend` (Stage 6); in tests an in-memory
62
+ * table built per fixture. Returned candidates must already be sorted descending by score — the reconciler takes the
63
+ * top `kResolver` as-is.
64
+ */
65
+ export interface ResolverCandidatesLookup {
66
+ candidatesFor(span: { start: number; end: number }, tag: ComponentTag): ReadonlyArray<ResolvedPlace>
67
+ }
68
+
69
+ /**
70
+ * Parent-chain lookup for concordance scoring. WOF SQLite is the source of truth in production (Stage 6); tests pass a
71
+ * `Map`-backed mock. Returns the place's ancestors (order unimportant — the reconciler only checks membership).
72
+ */
73
+ export interface ParentChainLookup {
74
+ parentsOf(place: ResolvedPlace): ReadonlyArray<ResolvedPlace>
75
+ }
76
+
77
+ export interface ReconcileInputs {
78
+ /** Raw input text — used to materialize `value` strings on the resulting tree. */
79
+ raw: string
80
+ phraseProposals: ReadonlyArray<PhraseProposal>
81
+ /** Sorted descending by score. May be empty (returns an empty tree). */
82
+ classifierTopK: ReadonlyArray<ClassifierCandidate>
83
+ resolverCandidates?: ResolverCandidatesLookup
84
+ parentChain?: ParentChainLookup
85
+ opts?: ReconcileOpts
86
+ }
87
+
88
+ export interface ReconcileOpts {
89
+ /** Top-k phrase span proposals retained per (start, end) — default 3. */
90
+ kSpan?: number
91
+ /** Top-k classifier tag interpretations retained per span — default 3. */
92
+ kTag?: number
93
+ /** Top-k resolver candidates retained per (span, tag) — default 5. */
94
+ kResolver?: number
95
+ /**
96
+ * Concordance bonus multiplier. 1.0 weights chain-consistency equal to one classifier-score factor; lower values
97
+ * trust the classifier more, higher values trust the gazetteer more. Default 1.0.
98
+ */
99
+ concordanceWeight?: number
100
+ /** Beam width during search — default 16. */
101
+ beamWidth?: number
102
+ /** Runner-up parses returned alongside the winner — default 3. */
103
+ runnersUp?: number
104
+ }
105
+
106
+ export interface ScoreBreakdown {
107
+ phrase: number
108
+ classifier: number
109
+ resolver: number
110
+ concordance: number
111
+ /** Composite multiplicative score in real space, [0, ∞). */
112
+ total: number
113
+ }
114
+
115
+ export interface ParseTree {
116
+ tree: AddressTree
117
+ /** Softmaxed confidence in [0, 1] over the finalized beam. */
118
+ confidence: number
119
+ runnersUp: AddressTree[]
120
+ scoreBreakdown: ScoreBreakdown
121
+ }
122
+
123
+ const DEFAULTS = {
124
+ kSpan: 3,
125
+ kTag: 3,
126
+ kResolver: 5,
127
+ concordanceWeight: 1.0,
128
+ beamWidth: 16,
129
+ runnersUp: 3,
130
+ }
131
+
132
+ /**
133
+ * Log-space bonus per **word covered** by an accepted slot. Counterweight for the multiplicative penalty inherent in
134
+ * "score = ∏ confidences": each factor in [0, 1] strictly lowers the running score, which would otherwise make the
135
+ * empty parse always win. With per-word scaling, a slot is worth including when the per-word geometric mean of its
136
+ * factors exceeds 1/2.5 = 0.4; below that, the search prefers to skip.
137
+ *
138
+ * Why per-word and not per-slot: a constant per-slot bonus carries two structural biases, both measured on `"New York
139
+ * City"` (2026-06-11):
140
+ *
141
+ * 1. **Fragments beat coverage.** The per-token logit aggregation gives interior fragments inflated confidence (`City`
142
+ * aggregates I-locality mass → locality 0.92 vs 0.60 for the full span), and a per-slot bonus charges nothing for
143
+ * leaving the rest of the input unexplained — so the beam picked the bare `locality="City"` (+0.475) over
144
+ * `locality="New York City"` (+0.199) and the grouper-audit then promoted the orphaned `York` to a spurious
145
+ * `region`.
146
+ * 2. **More spans collect more bonuses.** For two interpretations covering the same words, the one split into more slots
147
+ * banked one bonus per slot — a fragmentation subsidy.
148
+ *
149
+ * Scaling the bonus by the slot's word count makes coverage the thing being rewarded: equal-coverage interpretations
150
+ * collect equal bonus (the classifier/phrase/resolver factors alone decide), and an interpretation that explains more
151
+ * of the input out-scores one that silently drops words unless the extra evidence is weak (per-word factor mean <
152
+ * 0.4).
153
+ *
154
+ * The choice of 2.5 is a tuning constant, not a free parameter we expose — exposing it would invite callers to disable
155
+ * inclusion entirely (defeating the purpose of the reconciler) and the sensible range is narrow. Lives here rather than
156
+ * `ReconcileOpts` for that reason. Words are whitespace-delimited; scripts without spaces (CJK) count as one word,
157
+ * which degrades to the old per-slot behavior rather than misbehaving.
158
+ */
159
+ const INCLUSION_LOG_BONUS = Math.log(2.5)
160
+
161
+ /**
162
+ * Admin levels from coarse to fine. Concordance scoring walks pairs (parent_level, child_level) and checks the child's
163
+ * parent_id chain for the parent's place id.
164
+ */
165
+ const ADMIN_LEVELS: ReadonlyArray<ComponentTag> = ["country", "region", "locality", "dependent_locality"]
166
+ const ADMIN_LEVEL_SET = new Set<ComponentTag>(ADMIN_LEVELS)
167
+
168
+ interface SlotChoice {
169
+ span: PhraseProposal["span"]
170
+ phraseConf: number
171
+ tag: ComponentTag
172
+ classifierScore: number
173
+ place: ResolvedPlace | null
174
+ resolverScore: number
175
+ /** Whitespace-delimited word count of the span's surface text — scales the inclusion bonus. */
176
+ wordCount: number
177
+ }
178
+
179
+ interface Beam {
180
+ assignments: SlotChoice[]
181
+ /** Log-space score combining phrase × classifier × resolver × concordance (running). */
182
+ logScore: number
183
+ /** Cached last-end so we can extend left-to-right without re-scanning assignments. */
184
+ lastEnd: number
185
+ }
186
+
187
+ /**
188
+ * Joint-decode the best parse tree from Stage 2.7 phrase proposals, Stage 3 classifier top-k, and Stage 6 resolver
189
+ * candidates. See file header for the scoring formula.
190
+ *
191
+ * The result tree's roots are the winning `(span, tag, place)` triples in source order. Each node's `placeID`, `lat`,
192
+ * `lon` come from the chosen resolver candidate; `confidence` reflects the per- factor score for that slot. `runnersUp`
193
+ * are the next-best parses for caller inspection.
194
+ *
195
+ * Empty `classifierTopK` short-circuits to an empty tree at confidence 0 — no joint decode is possible without tag
196
+ * interpretations. Callers without top-k should use the runtime-pipeline fallback (which keeps classifier-emitted spans
197
+ * sorted by start).
198
+ */
199
+ export function reconcileSpans(inputs: ReconcileInputs): ParseTree {
200
+ const opts = { ...DEFAULTS, ...inputs.opts }
201
+
202
+ const slots = buildSlots(inputs, opts)
203
+
204
+ if (slots.length === 0) {
205
+ return emptyParseTree(inputs.raw)
206
+ }
207
+
208
+ // Beam search over left-to-right slot inclusion. Each slot is either accepted (if non-
209
+ // overlapping with the beam's claimed range) or skipped. Beam pruning keeps the top
210
+ // `beamWidth` by running log-score.
211
+ const slotsByStart = slots.slice().sort((a, b) => a.span.start - b.span.start)
212
+ let beams: Beam[] = [{ assignments: [], logScore: 0, lastEnd: -1 }]
213
+
214
+ for (const slot of slotsByStart) {
215
+ const next: Beam[] = []
216
+
217
+ for (const beam of beams) {
218
+ next.push(beam)
219
+
220
+ if (slot.span.start >= beam.lastEnd) {
221
+ const concordanceDelta = concordanceDeltaFor(beam.assignments, slot, inputs, opts)
222
+
223
+ if (concordanceDelta === Number.NEGATIVE_INFINITY) continue
224
+ const slotLog =
225
+ logSafe(slot.phraseConf) +
226
+ logSafe(slot.classifierScore) +
227
+ logSafe(slot.resolverScore) +
228
+ concordanceDelta +
229
+ INCLUSION_LOG_BONUS * slot.wordCount
230
+ next.push({
231
+ assignments: [...beam.assignments, slot],
232
+ logScore: beam.logScore + slotLog,
233
+ lastEnd: slot.span.end,
234
+ })
235
+ }
236
+ }
237
+ next.sort((a, b) => b.logScore - a.logScore)
238
+ beams = next.slice(0, opts.beamWidth)
239
+ }
240
+
241
+ beams.sort((a, b) => b.logScore - a.logScore)
242
+ // Drop the empty beam if there's at least one non-empty competitor (the empty beam scores 0,
243
+ // which would otherwise dominate when all real candidates have very low log-scores).
244
+ const populated = beams.filter((b) => b.assignments.length > 0)
245
+ const ordered = populated.length > 0 ? populated : beams
246
+
247
+ const top = ordered[0]!
248
+ const runners = ordered.slice(1, 1 + opts.runnersUp)
249
+
250
+ const trees = ordered.map((b) => buildTree(b, inputs.raw))
251
+ const confidences = softmax(ordered.map((b) => b.logScore))
252
+
253
+ return {
254
+ tree: trees[0]!,
255
+ confidence: confidences[0]!,
256
+ runnersUp: runners.map((_, i) => trees[i + 1]!),
257
+ scoreBreakdown: breakdownFor(top, inputs, opts),
258
+ }
259
+ }
260
+
261
+ /**
262
+ * Build the candidate slot set: dedupe phrase proposals by (start, end), join with classifier top-k tag candidates,
263
+ * join with resolver places per (span, tag).
264
+ *
265
+ * Spans with no classifier candidate are dropped — the reconciler cannot tag them. Spans with no resolver candidate
266
+ * still survive; the resolver score defaults to 1 (neutral) and the slot's place is null (won't contribute to
267
+ * concordance).
268
+ */
269
+ function buildSlots(inputs: ReconcileInputs, opts: Required<ReconcileOpts>): SlotChoice[] {
270
+ const bySpanKey = new Map<string, PhraseProposal>()
271
+
272
+ for (const p of inputs.phraseProposals) {
273
+ const k = spanKey(p.span.start, p.span.end)
274
+ const cur = bySpanKey.get(k)
275
+
276
+ if (!cur || p.confidence > cur.confidence) {
277
+ bySpanKey.set(k, p)
278
+ }
279
+ }
280
+ // `kSpan` limits the number of overlapping proposals anchored at each start position — NOT a
281
+ // global cap on phrase proposals. Two phrases at different starts (e.g. `Houston` at 18 +
282
+ // `TX` at 27) are independent candidates and both must survive `kSpan = 3`. Without this per-
283
+ // start grouping, a low-confidence-but-correct proposal (e.g. `Houston` @ 0.65) is dropped
284
+ // just because the input has many higher-confidence proposals elsewhere.
285
+ const byStart = new Map<number, PhraseProposal[]>()
286
+
287
+ for (const p of bySpanKey.values()) {
288
+ const arr = byStart.get(p.span.start) ?? []
289
+ arr.push(p)
290
+ byStart.set(p.span.start, arr)
291
+ }
292
+ const spans: PhraseProposal[] = []
293
+
294
+ for (const arr of byStart.values()) {
295
+ spans.push(...topN(arr, opts.kSpan, (p) => p.confidence))
296
+ }
297
+
298
+ const tagsBySpan = new Map<string, ClassifierCandidate[]>()
299
+
300
+ for (const c of inputs.classifierTopK) {
301
+ const k = spanKey(c.span.start, c.span.end)
302
+ const arr = tagsBySpan.get(k) ?? []
303
+ arr.push(c)
304
+ tagsBySpan.set(k, arr)
305
+ }
306
+
307
+ const slots: SlotChoice[] = []
308
+
309
+ for (const phrase of spans) {
310
+ const key = spanKey(phrase.span.start, phrase.span.end)
311
+ const tagCandidates = topN(tagsBySpan.get(key) ?? [], opts.kTag, (c) => c.score)
312
+ const words = wordCountOf(inputs.raw, phrase.span)
313
+
314
+ for (const tagC of tagCandidates) {
315
+ const places = inputs.resolverCandidates
316
+ ? inputs.resolverCandidates.candidatesFor(tagC.span, tagC.tag).slice(0, opts.kResolver)
317
+ : []
318
+
319
+ if (places.length === 0) {
320
+ slots.push({
321
+ span: phrase.span,
322
+ phraseConf: phrase.confidence,
323
+ tag: tagC.tag,
324
+ classifierScore: tagC.score,
325
+ place: null,
326
+ resolverScore: 1,
327
+ wordCount: words,
328
+ })
329
+ continue
330
+ }
331
+
332
+ for (const place of places) {
333
+ slots.push({
334
+ span: phrase.span,
335
+ phraseConf: phrase.confidence,
336
+ tag: tagC.tag,
337
+ classifierScore: tagC.score,
338
+ place,
339
+ resolverScore: normalizeResolverScore(place.score),
340
+ wordCount: words,
341
+ })
342
+ }
343
+ }
344
+ }
345
+
346
+ return slots
347
+ }
348
+
349
+ /**
350
+ * Whitespace-delimited word count of a span's surface text, floor 1. Scales the per-slot inclusion bonus so coverage —
351
+ * not slot count — is what the search rewards (see `INCLUSION_LOG_BONUS`).
352
+ */
353
+ function wordCountOf(raw: string, span: { start: number; end: number }): number {
354
+ const text = raw.slice(span.start, span.end).trim()
355
+
356
+ if (text.length === 0) return 1
357
+
358
+ return text.split(/\s+/).length
359
+ }
360
+
361
+ /**
362
+ * Concordance delta for adding `slot` to an existing beam. Returns the log-space contribution to add to the beam's
363
+ * running score, or `-Infinity` if the slot introduces a hard contradiction (would be admissible into the beam's admin
364
+ * chain but explicitly disagrees).
365
+ *
366
+ * Behavior at the boundaries:
367
+ *
368
+ * - Slot has no place or is non-admin → 0 (no chain contribution).
369
+ * - No admin neighbors yet → 0 (nothing to agree with).
370
+ * - Admin chain agrees → `+ concordanceWeight × log(1 + match_ratio)`.
371
+ * - Some admin pairs cannot be verified (missing parents) → 0 contribution per neutral pair.
372
+ * - Admin chain has any explicit contradiction → `-Infinity` (hard veto).
373
+ */
374
+ function concordanceDeltaFor(
375
+ existing: SlotChoice[],
376
+ candidate: SlotChoice,
377
+ inputs: ReconcileInputs,
378
+ opts: Required<ReconcileOpts>
379
+ ): number {
380
+ if (!candidate.place || !ADMIN_LEVEL_SET.has(candidate.tag)) return 0
381
+ const chainOf = inputs.parentChain
382
+
383
+ if (!chainOf) return 0
384
+ const candIdx = ADMIN_LEVELS.indexOf(candidate.tag)
385
+ let matches = 0
386
+ let neutrals = 0
387
+ let pairs = 0
388
+
389
+ for (const prior of existing) {
390
+ if (!prior.place || !ADMIN_LEVEL_SET.has(prior.tag)) continue
391
+ const priorIdx = ADMIN_LEVELS.indexOf(prior.tag)
392
+ const child = priorIdx > candIdx ? prior : candidate
393
+ const parent = priorIdx > candIdx ? candidate : prior
394
+
395
+ if (child === parent) continue
396
+ const chain = chainOf.parentsOf(child.place!)
397
+ pairs++
398
+
399
+ if (chain.length === 0) {
400
+ neutrals++
401
+ continue
402
+ }
403
+ const hit = chain.some((p) => idsEqual(p.id, parent.place!.id))
404
+
405
+ if (hit) {
406
+ matches++
407
+ } else {
408
+ return Number.NEGATIVE_INFINITY
409
+ }
410
+ }
411
+
412
+ if (pairs === 0) return 0
413
+ const matchRatio = matches / pairs
414
+
415
+ // Linear in matchRatio so a fully-consistent chain contributes exactly `+concordanceWeight`
416
+ // log-space — the briefing's "+1 for fully consistent" reading. Matches contribute
417
+ // proportionally; neutrals (no chain data) don't penalize.
418
+ return opts.concordanceWeight * matchRatio
419
+ }
420
+
421
+ function idsEqual(a: number | string, b: number | string): boolean {
422
+ return String(a) === String(b)
423
+ }
424
+
425
+ /**
426
+ * Compute the per-factor breakdown for the winning beam. Independently of the search's `logScore` (which carries the
427
+ * inclusion-bonus prior), the breakdown surfaces the bare `phrase × classifier × resolver × concordance` product so
428
+ * callers can introspect why a tree won.
429
+ */
430
+ function breakdownFor(beam: Beam, inputs: ReconcileInputs, opts: Required<ReconcileOpts>): ScoreBreakdown {
431
+ let phrase = 1
432
+ let classifier = 1
433
+ let resolver = 1
434
+
435
+ for (const a of beam.assignments) {
436
+ phrase *= Math.max(a.phraseConf, 0)
437
+ classifier *= Math.max(a.classifierScore, 0)
438
+ resolver *= Math.max(a.resolverScore, 0)
439
+ }
440
+ const concordanceLog = totalConcordanceLog(beam.assignments, inputs, opts)
441
+ const concordance = Math.exp(concordanceLog)
442
+ const total = phrase * classifier * resolver * concordance
443
+
444
+ return { phrase, classifier, resolver, concordance, total }
445
+ }
446
+
447
+ /**
448
+ * Recompute the joint concordance contribution for the entire assignment list (vs the incremental `concordanceDeltaFor`
449
+ * used during search). Used by the breakdown.
450
+ */
451
+ function totalConcordanceLog(
452
+ assignments: SlotChoice[],
453
+ inputs: ReconcileInputs,
454
+ opts: Required<ReconcileOpts>
455
+ ): number {
456
+ if (!inputs.parentChain) return 0
457
+ let acc = 0
458
+
459
+ for (let i = 0; i < assignments.length; i++) {
460
+ const delta = concordanceDeltaFor(assignments.slice(0, i), assignments[i]!, inputs, opts)
461
+
462
+ if (delta === Number.NEGATIVE_INFINITY) return Number.NEGATIVE_INFINITY
463
+ acc += delta
464
+ }
465
+
466
+ return acc
467
+ }
468
+
469
+ function buildTree(beam: Beam, raw: string): AddressTree {
470
+ const roots: AddressNode[] = beam.assignments
471
+ .slice()
472
+ .sort((a, b) => a.span.start - b.span.start)
473
+ .map((slot) => ({
474
+ tag: slot.tag,
475
+ value: raw.slice(slot.span.start, slot.span.end),
476
+ start: slot.span.start,
477
+ end: slot.span.end,
478
+ confidence: slot.classifierScore * slot.phraseConf,
479
+ children: [],
480
+ source: "reconcile",
481
+ sourceID: "reconcile:stage-5-joint",
482
+ ...(slot.place
483
+ ? {
484
+ lat: slot.place.lat,
485
+ lon: slot.place.lon,
486
+ placeID: `${placeIDPrefix(slot.place)}:${slot.place.id}`,
487
+ }
488
+ : {}),
489
+ }))
490
+
491
+ return { raw, roots }
492
+ }
493
+
494
+ function emptyParseTree(raw: string): ParseTree {
495
+ return {
496
+ tree: { raw, roots: [] },
497
+ confidence: 0,
498
+ runnersUp: [],
499
+ scoreBreakdown: { phrase: 0, classifier: 0, resolver: 0, concordance: 1, total: 0 },
500
+ }
501
+ }
502
+
503
+ function placeIDPrefix(place: ResolvedPlace): string {
504
+ // Mirror the convention used by @mailwoman/core/resolver-wof-sqlite (`wof:<id>`). Resolver
505
+ // backends that don't carry an implicit vendor in `id` get a neutral `place:` prefix.
506
+ return typeof place.id === "number" ? "wof" : "place"
507
+ }
508
+
509
+ function spanKey(start: number, end: number): string {
510
+ return `${start}:${end}`
511
+ }
512
+
513
+ function topN<T>(items: ReadonlyArray<T>, n: number, key: (t: T) => number): T[] {
514
+ return items
515
+ .slice()
516
+ .sort((a, b) => key(b) - key(a))
517
+ .slice(0, n)
518
+ }
519
+
520
+ function logSafe(x: number): number {
521
+ return x > 0 ? Math.log(x) : -50
522
+ }
523
+
524
+ function normalizeResolverScore(score: number): number {
525
+ // Resolver score scale is implementation-defined; clamp to (0, 1] for the multiplicative
526
+ // combiner. A backend that returns 0 still counts as a candidate (e.g. a partial match) but
527
+ // contributes a tiny log-factor.
528
+ if (!Number.isFinite(score) || score <= 0) return 0.01
529
+
530
+ if (score > 1) return 1
531
+
532
+ return score
533
+ }
534
+
535
+ function softmax(scores: number[]): number[] {
536
+ if (scores.length === 0) return []
537
+ const max = Math.max(...scores)
538
+ const exps = scores.map((s) => Math.exp(s - max))
539
+ const sum = exps.reduce((a, b) => a + b, 0)
540
+
541
+ return exps.map((e) => e / sum)
542
+ }