@mailwoman/core 7.2.0 → 7.3.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 (150) 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/locale/index.ts +9 -0
  52. package/locale/locale.ts +49 -0
  53. package/locale/profiles/en-us.ts +69 -0
  54. package/locale/profiles/fr-fr.ts +75 -0
  55. package/locale/profiles/index.ts +9 -0
  56. package/locale/profiles/ja-jp.ts +33 -0
  57. package/locale/registry.ts +68 -0
  58. package/logging/index.ts +8 -0
  59. package/logging/shared.ts +145 -0
  60. package/logging/utils.ts +46 -0
  61. package/objects.ts +211 -0
  62. package/out/api/APIClient.d.ts.map +1 -1
  63. package/out/api/APIClient.js +2 -2
  64. package/out/api/APIClient.js.map +1 -1
  65. package/out/pipeline/types.d.ts +13 -0
  66. package/out/pipeline/types.d.ts.map +1 -1
  67. package/out/pipeline/types.js.map +1 -1
  68. package/out/scripting/utils/index.d.ts.map +1 -1
  69. package/out/scripting/utils/index.js +3 -5
  70. package/out/scripting/utils/index.js.map +1 -1
  71. package/package.json +190 -107
  72. package/pipeline/index.ts +46 -0
  73. package/pipeline/reconcile-lookups.ts +108 -0
  74. package/pipeline/reconcile.ts +542 -0
  75. package/pipeline/runtime-pipeline.ts +732 -0
  76. package/pipeline/span-logit-aggregation.ts +151 -0
  77. package/pipeline/span-proposer.ts +587 -0
  78. package/pipeline/types.ts +357 -0
  79. package/policy/defaults.ts +35 -0
  80. package/policy/index.ts +10 -0
  81. package/policy/policy.ts +60 -0
  82. package/policy/proposal-collection.ts +64 -0
  83. package/policy/registry.ts +149 -0
  84. package/resolver/index.ts +29 -0
  85. package/resolver/types.ts +584 -0
  86. package/resources/LocaleIndex.ts +124 -0
  87. package/resources/ResourceMapCache.ts +126 -0
  88. package/resources/collections.ts +93 -0
  89. package/resources/debugging.ts +19 -0
  90. package/resources/git.ts +54 -0
  91. package/resources/index.ts +17 -0
  92. package/resources/languages/index.ts +49 -0
  93. package/resources/languages/types.gen.ts +1368 -0
  94. package/resources/libaddressinput.ts +105 -0
  95. package/resources/libpostal.ts +182 -0
  96. package/resources/locale.ts +23 -0
  97. package/resources/set.ts +179 -0
  98. package/resources/whosonfirst/DataSourceCache.ts +72 -0
  99. package/resources/whosonfirst/PlacetypeDataSource.ts +199 -0
  100. package/resources/whosonfirst/index.ts +10 -0
  101. package/resources/whosonfirst/loader.ts +157 -0
  102. package/resources/whosonfirst/placetypes/Placetype.ts +438 -0
  103. package/resources/whosonfirst/placetypes/admin.ts +173 -0
  104. package/resources/whosonfirst/placetypes/definition.ts +135 -0
  105. package/resources/whosonfirst/placetypes/graph.ts +0 -0
  106. package/resources/whosonfirst/placetypes/index.ts +12 -0
  107. package/resources/whosonfirst/placetypes/mermaid.ts +168 -0
  108. package/resources/whosonfirst/placetypes/tree.ts +46 -0
  109. package/routing/index.ts +208 -0
  110. package/scripting/index.ts +40 -0
  111. package/scripting/utils/index.ts +103 -0
  112. package/tokenization/Graph.ts +50 -0
  113. package/tokenization/Span.ts +297 -0
  114. package/tokenization/index.ts +9 -0
  115. package/tokenization/normalizer.ts +123 -0
  116. package/tools/download-libpostal-resources.ts +98 -0
  117. package/tools/download-ssl-address.ts +99 -0
  118. package/tools/generate-language-types.ts +194 -0
  119. package/tools/index.ts +13 -0
  120. package/types/Classification.ts +211 -0
  121. package/types/classifier.ts +133 -0
  122. package/types/component.ts +75 -0
  123. package/types/index.ts +10 -0
  124. package/types/mapping.ts +81 -0
  125. package/utils/data-root.ts +56 -0
  126. package/utils/hash.ts +27 -0
  127. package/utils/index.ts +14 -0
  128. package/utils/jsonl.ts +43 -0
  129. package/utils/python-json.ts +105 -0
  130. package/utils/python-random.ts +90 -0
  131. package/utils/repo.ts +118 -0
  132. package/utils/sealed-db.ts +85 -0
  133. package/utils/stats.ts +32 -0
  134. package/vitest.config.ts +53 -0
  135. package/out/lifecycle/ServiceSymbol.d.ts +0 -57
  136. package/out/lifecycle/ServiceSymbol.d.ts.map +0 -1
  137. package/out/lifecycle/ServiceSymbol.js +0 -60
  138. package/out/lifecycle/ServiceSymbol.js.map +0 -1
  139. package/out/lifecycle/index.d.ts +0 -11
  140. package/out/lifecycle/index.d.ts.map +0 -1
  141. package/out/lifecycle/index.js +0 -11
  142. package/out/lifecycle/index.js.map +0 -1
  143. package/out/lifecycle/lru-cache.d.ts +0 -22
  144. package/out/lifecycle/lru-cache.d.ts.map +0 -1
  145. package/out/lifecycle/lru-cache.js +0 -31
  146. package/out/lifecycle/lru-cache.js.map +0 -1
  147. package/out/lifecycle/services.d.ts +0 -144
  148. package/out/lifecycle/services.d.ts.map +0 -1
  149. package/out/lifecycle/services.js +0 -191
  150. package/out/lifecycle/services.js.map +0 -1
@@ -0,0 +1,244 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Train the #244 coarse-placer: a multinomial logistic-regression over the hashed char-n-gram +
7
+ * script features ({@link featurize}), via plain SGD. CPU-only, a few minutes — no GPU/Modal.
8
+ * After training, fits a single temperature on val (NLL minimization) for calibrated confidence.
9
+ * Writes a `meta.json` + `weights.bin` (Float32, row-major [class][feature]) artifact.
10
+ *
11
+ * Run: `mailwoman placer train [--epochs 12] [--lr 0.1] [--l2 1e-6] [--out
12
+ * $MAILWOMAN_DATA_ROOT/coarse-placer/model]`
13
+ */
14
+
15
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs"
16
+ import * as path from "node:path"
17
+
18
+ import { dataRootPath } from "../../utils/data-root.ts"
19
+ import { repoRootPath } from "../../utils/repo.ts"
20
+ import { COARSE_CLASSES, FEATURE_DIM, featurize } from "../featurize.ts"
21
+
22
+ interface Sample {
23
+ x: Int32Array
24
+ y: number
25
+ }
26
+
27
+ /** Options for {@linkcode trainCoarsePlacer}. */
28
+ export interface TrainCoarsePlacerOptions {
29
+ /** SGD epochs. Default 12. */
30
+ epochs?: number
31
+ /** Initial learning rate (decays per epoch). Default 0.1. */
32
+ lr?: number
33
+ /** L2 regularization. Default 1e-6. */
34
+ l2?: number
35
+ /** Artifact output dir. Default `$MAILWOMAN_DATA_ROOT/coarse-placer/model`. */
36
+ out?: string
37
+ /** Dataset dir (`{train,val}.jsonl`). Default `<repo>/data/coarse-placer`. */
38
+ data?: string
39
+ }
40
+
41
+ /** Result of {@linkcode trainCoarsePlacer}. */
42
+ export interface TrainCoarsePlacerResult {
43
+ outDir: string
44
+ trainRows: number
45
+ valRows: number
46
+ temperature: number
47
+ valNLL: number
48
+ }
49
+
50
+ /** Coarse-placer SGD trainer — see the module doc. */
51
+ export async function trainCoarsePlacer(
52
+ options: TrainCoarsePlacerOptions = {},
53
+ report?: (line: string) => void
54
+ ): Promise<TrainCoarsePlacerResult> {
55
+ const epochs = options.epochs ?? 12
56
+ const lr0 = options.lr ?? 0.1
57
+ const l2 = options.l2 ?? 0.000001
58
+ const outDir = options.out || dataRootPath("coarse-placer", "model")
59
+ const dataDir = options.data || repoRootPath("data", "coarse-placer")
60
+
61
+ const C = COARSE_CLASSES.length
62
+ const D = FEATURE_DIM
63
+ const classIdx = new Map<string, number>(COARSE_CLASSES.map((c, i): [string, number] => [c, i]))
64
+
65
+ function load(split: string): Sample[] {
66
+ const rows = readFileSync(path.join(dataDir, `${split}.jsonl`), "utf8")
67
+ .trim()
68
+ .split("\n")
69
+ .map((l) => JSON.parse(l) as { raw: string; country: string })
70
+ // Precompute features once: Int32Array of active indices + label id per row.
71
+ const out: Sample[] = []
72
+
73
+ for (const r of rows) {
74
+ const y = classIdx.get(r.country)
75
+
76
+ if (y === undefined) continue
77
+ out.push({ x: Int32Array.from(featurize(r.raw)), y })
78
+ }
79
+
80
+ return out
81
+ }
82
+
83
+ report?.("featurizing…")
84
+ const train = load("train")
85
+ const val = load("val")
86
+ report?.(`train ${train.length} val ${val.length} classes ${C} dim ${D}`)
87
+
88
+ const W = new Float32Array(C * D)
89
+ const b = new Float32Array(C)
90
+
91
+ // Deterministic LCG shuffle (no Math.random → reproducible runs).
92
+ // NOTE(phase4b): deliberately NOT `SeededRandom.shuffle` — that's mulberry32; this LCG stream is
93
+ // what every shipped model was trained on, and swapping the RNG changes the shuffle order (a
94
+ // silent retrain-reproducibility break).
95
+ let rng = 1234567
96
+ const rand = (): number => (rng = (Math.imul(rng, 1103515245) + 12345) & 0x7fffffff) / 0x7fffffff
97
+ function shuffle(arr: Sample[]): void {
98
+ for (let i = arr.length - 1; i > 0; i--) {
99
+ const j = Math.floor(rand() * (i + 1))
100
+ ;[arr[i], arr[j]] = [arr[j]!, arr[i]!]
101
+ }
102
+ }
103
+
104
+ const logits = new Float32Array(C)
105
+ const probs = new Float32Array(C)
106
+ function forward(x: Int32Array): void {
107
+ for (let c = 0; c < C; c++) {
108
+ let s = b[c]!
109
+ const base = c * D
110
+
111
+ for (let k = 0; k < x.length; k++) {
112
+ s += W[base + x[k]!]!
113
+ }
114
+ logits[c] = s
115
+ }
116
+ let mx = -Infinity
117
+
118
+ for (let c = 0; c < C; c++)
119
+ if (logits[c]! > mx) {
120
+ mx = logits[c]!
121
+ }
122
+ let sum = 0
123
+
124
+ for (let c = 0; c < C; c++) {
125
+ const e = Math.exp(logits[c]! - mx)
126
+ probs[c] = e
127
+ sum += e
128
+ }
129
+
130
+ for (let c = 0; c < C; c++) {
131
+ probs[c] = probs[c]! / sum
132
+ }
133
+ }
134
+
135
+ function accuracy(set: Sample[]): number {
136
+ let ok = 0
137
+
138
+ for (const { x, y } of set) {
139
+ forward(x)
140
+ let top = 0
141
+
142
+ for (let c = 1; c < C; c++)
143
+ if (probs[c]! > probs[top]!) {
144
+ top = c
145
+ }
146
+
147
+ if (top === y) {
148
+ ok++
149
+ }
150
+ }
151
+
152
+ return ok / set.length
153
+ }
154
+
155
+ for (let ep = 0; ep < epochs; ep++) {
156
+ shuffle(train)
157
+ const lr = lr0 / (1 + 0.5 * ep)
158
+
159
+ // simple decay
160
+ for (const { x, y } of train) {
161
+ forward(x)
162
+
163
+ for (let c = 0; c < C; c++) {
164
+ const g = probs[c]! - (c === y ? 1 : 0)
165
+
166
+ if (g === 0 && c !== y) continue
167
+ b[c] = b[c]! - lr * g
168
+ const base = c * D
169
+
170
+ for (let k = 0; k < x.length; k++) {
171
+ const idx = base + x[k]!
172
+ W[idx] = W[idx]! - lr * (g + l2 * W[idx]!)
173
+ }
174
+ }
175
+ }
176
+ report?.(
177
+ `epoch ${ep + 1}/${epochs} lr=${lr.toFixed(4)} train_acc=${accuracy(train.slice(0, 5000)).toFixed(4)} val_acc=${accuracy(val).toFixed(4)}`
178
+ )
179
+ }
180
+
181
+ // --- Temperature calibration: minimize val NLL over T by coarse-then-fine 1-D search. ---
182
+ function valNLL(T: number): number {
183
+ let nll = 0
184
+
185
+ for (const { x, y } of val) {
186
+ for (let c = 0; c < C; c++) {
187
+ let s = b[c]!
188
+ const base = c * D
189
+
190
+ for (let k = 0; k < x.length; k++) {
191
+ s += W[base + x[k]!]!
192
+ }
193
+ logits[c] = s / T
194
+ }
195
+ let mx = -Infinity
196
+
197
+ for (let c = 0; c < C; c++)
198
+ if (logits[c]! > mx) {
199
+ mx = logits[c]!
200
+ }
201
+ let sum = 0
202
+
203
+ for (let c = 0; c < C; c++) {
204
+ sum += Math.exp(logits[c]! - mx)
205
+ }
206
+ nll += -(logits[y]! - mx - Math.log(sum))
207
+ }
208
+
209
+ return nll / val.length
210
+ }
211
+ let bestT = 1
212
+ let bestNLL = Infinity
213
+
214
+ for (let T = 0.5; T <= 4.01; T += 0.1) {
215
+ const nll = valNLL(T)
216
+
217
+ if (nll < bestNLL) {
218
+ bestNLL = nll
219
+ bestT = T
220
+ }
221
+ }
222
+ report?.(`temperature=${bestT.toFixed(2)} val_NLL=${bestNLL.toFixed(4)}`)
223
+
224
+ mkdirSync(outDir, { recursive: true })
225
+ writeFileSync(
226
+ path.join(outDir, "meta.json"),
227
+ JSON.stringify(
228
+ {
229
+ classes: [...COARSE_CLASSES],
230
+ featureDim: D,
231
+ temperature: bestT,
232
+ bias: [...b],
233
+ trainedAt: null,
234
+ trainRows: train.length,
235
+ },
236
+ null,
237
+ 2
238
+ )
239
+ )
240
+ writeFileSync(path.join(outDir, "weights.bin"), Buffer.from(W.buffer))
241
+ report?.(`→ ${outDir}/meta.json + weights.bin (${(W.byteLength / 1e6).toFixed(1)} MB fp32)`)
242
+
243
+ return { outDir, trainRows: train.length, valRows: val.length, temperature: bestT, valNLL: bestNLL }
244
+ }
package/collections.ts ADDED
@@ -0,0 +1,134 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ */
6
+
7
+ /**
8
+ * Extracts the property keys of an object that are of type `number`.
9
+ */
10
+ export type NumericProperties<T> = {
11
+ [K in keyof T]: T[K] extends number ? K : never
12
+ }[keyof T]
13
+
14
+ /**
15
+ * Given an iterable of objects, returns the sum of the specified property.
16
+ */
17
+ export function sumOf<T extends object>(iterable: Iterable<T>, prop: NumericProperties<T>): number {
18
+ let total = 0
19
+
20
+ for (const item of iterable) {
21
+ total += item[prop] as number
22
+ }
23
+
24
+ return total
25
+ }
26
+
27
+ /**
28
+ * Given an iterable, returns an array of arrays of the specified size.
29
+ *
30
+ * This is useful for batching asynchronous operations.
31
+ *
32
+ * @param collection The collection to batch.
33
+ * @param batchSize The size of each batch.
34
+ *
35
+ * @returns An iterable of arrays of the specified size.
36
+ */
37
+ export function* take<T>(collection: Iterable<T>, batchSize: number): Iterable<T[]> {
38
+ const batch: T[] = []
39
+
40
+ for (const item of collection) {
41
+ batch.push(item)
42
+
43
+ if (batch.length === batchSize) {
44
+ yield batch
45
+
46
+ batch.length = 0
47
+ }
48
+ }
49
+
50
+ if (batch.length > 0) {
51
+ yield batch
52
+ }
53
+ }
54
+
55
+ /**
56
+ * Convenience function to await an async iterable.
57
+ */
58
+ export async function iterateInParallel<T>(asyncIterable: AsyncIterable<T>): Promise<void> {
59
+ for await (const _ of asyncIterable) {
60
+ /* empty */
61
+ }
62
+ }
63
+
64
+ /**
65
+ * Given an iterable of values, maps each value to a record of the value and the result of the callback.
66
+ *
67
+ * This is a convenience function when an iterable needs mapping to an object-like structure.
68
+ *
69
+ * @category Collections
70
+ * @category Object
71
+ */
72
+ export function pivot<T extends PropertyKey, C extends (value: T) => Promise<unknown> | unknown>(
73
+ /**
74
+ * The iterable to pivot.
75
+ */
76
+ iterable: Iterable<T>,
77
+ /**
78
+ * The callback to transform each value.
79
+ */
80
+ callback: C
81
+ ): ReturnType<C> extends PromiseLike<infer U> ? Promise<Record<T, U>> : Record<T, ReturnType<C>> {
82
+ const entries: Array<[T, ReturnType<C>]> = []
83
+ let foundThenable = false
84
+
85
+ for (const value of iterable) {
86
+ const result = callback(value)
87
+
88
+ if (result && typeof result === "object" && "then" in result) {
89
+ foundThenable = true
90
+ }
91
+
92
+ entries.push([value, result as ReturnType<C>])
93
+ }
94
+
95
+ if (foundThenable) {
96
+ return Promise.all(
97
+ entries.map(([key, value]) => {
98
+ return Promise.resolve(value).then((resolvedValue) => [key, resolvedValue] as const)
99
+ })
100
+ ).then(Object.fromEntries) as unknown as ReturnType<C> extends PromiseLike<infer U>
101
+ ? Promise<Record<T, U>>
102
+ : Record<T, ReturnType<C>>
103
+ }
104
+
105
+ const pivotedRecord = Object.fromEntries(entries)
106
+
107
+ return pivotedRecord as unknown as ReturnType<C> extends PromiseLike<infer U>
108
+ ? Promise<Record<T, U>>
109
+ : Record<T, ReturnType<C>>
110
+ }
111
+
112
+ /**
113
+ * Type-predicate for checking if a value is iterable.
114
+ *
115
+ * @category Type Guard
116
+ * @category Object
117
+ */
118
+ export function isIterable<T>(input: unknown): input is Iterable<T> {
119
+ return Symbol.iterator in Object(input)
120
+ }
121
+
122
+ /**
123
+ * Iterable that can be checked for the existence of a member.
124
+ */
125
+ export interface IndexedIterable<T = unknown> extends Iterable<T> {
126
+ has(value: T): boolean
127
+ }
128
+
129
+ /**
130
+ * Type-predicate for checking if an member within an iterable can be checked for existence.
131
+ */
132
+ export function isIndexedIterable<T>(value: Iterable<T>): value is IndexedIterable<T> {
133
+ return value && typeof (value as IndexedIterable).has === "function"
134
+ }
package/db/schema.ts ADDED
@@ -0,0 +1,21 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Shared `Database` typing for the Kysely client at `core/kysley/client.ts`.
7
+ *
8
+ * This file intentionally ships an empty schema. Consumers that want compile-time table typing
9
+ * should extend `Kysely<TheirSchema>` directly rather than baking a schema into core — the WOF
10
+ * resolver (Phase 4.2), corpus adapters, and any future consumer all touch different tables.
11
+ *
12
+ * The exported `Database` interface exists so `client.ts` has a target for `Kysely<Database>` and
13
+ * the boilerplate compiles without forcing a concrete schema commitment.
14
+ */
15
+
16
+ /**
17
+ * Empty schema marker. Consumers declare their own schema interface and pass it directly to `new
18
+ * Kysely<MySchema>({...})` or instantiate `new DatabaseClient<MySchema>(...)` once `DatabaseClient` becomes generic
19
+ * (Phase 4.2 work).
20
+ */
21
+ export type Database = Record<string, never>
@@ -0,0 +1,228 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * BIO-stream → AddressTree.
7
+ *
8
+ * Two passes:
9
+ *
10
+ * 1. Span emission — walk the token stream, group `B-X` followed by `I-X*` into one span. Lenient on
11
+ * hanging `I-X` (treat as new span). A `B-X` that is whitespace-adjacent to an already-open
12
+ * `X` span is also folded in (spurious-boundary repair for multi-word values the model
13
+ * fragments, e.g. "Saint Paul" → B-locality B-locality); a comma/separator between them
14
+ * keeps them distinct. Span `value` is sliced from `raw` by [start, end), NOT concatenated
15
+ * from `piece` — this avoids SentencePiece's synthetic leading-space markers in the output.
16
+ * 2. Parent attachment — for each span, find the nearest labeled span whose tag is the
17
+ * highest-priority entry in this span's `PARENT_OF` list. Distance is the tiebreaker only.
18
+ * Spans with no found parent become roots.
19
+ *
20
+ * The "nearest" rule (vs "most-recent-prior") is intentional: it makes the decoder independent of
21
+ * source ordering — e.g. "75004 Paris" attaches postcode to locality even though postcode came
22
+ * first. Source order is still preserved in the `start`/`end` fields, which the XML serializer
23
+ * exposes as attributes.
24
+ */
25
+
26
+ import type { BIOLabel, ComponentTag } from "../types/component.ts"
27
+ import type { Calibrator } from "./calibration.ts"
28
+ import { containmentFor } from "./containment.ts"
29
+ import type { AddressNode, AddressSystem, AddressTree, DecoderToken } from "./types.ts"
30
+
31
+ /**
32
+ * Optional caller-supplied attribution stamped on every emitted node. The BIO stream comes from a single model, so
33
+ * there's no per-span variation — one source for the whole tree.
34
+ *
35
+ * Phase 4.3 may overlay a resolver-derived attribution per node on top of this baseline.
36
+ */
37
+ export interface BuildTreeOpts {
38
+ source?: string
39
+ sourceID?: string
40
+ /**
41
+ * Addressing system to decode under — selects the containment hierarchy via `containmentFor`. Stamped onto the
42
+ * returned `AddressTree.system`. Omit for the default Western hierarchy. Today all systems share one map, so this
43
+ * only records intent + threads the discriminator; it becomes behavioral when a system-specific map lands (Phase 6
44
+ * JP). See `containment.ts`.
45
+ */
46
+ system?: AddressSystem
47
+ /**
48
+ * Optional confidence calibrator (task #59). When provided, each span's mean-of-token-softmax confidence is mapped
49
+ * through it before being stamped on the node, so `conf=` reports a calibrated probability of correctness rather than
50
+ * the raw softmax. OPT-IN — omit for the byte-stable default. Build one via `createCalibrator` (`./calibration.ts`).
51
+ */
52
+ calibrate?: Calibrator
53
+ }
54
+
55
+ interface OpenSpan {
56
+ tag: ComponentTag
57
+ start: number
58
+ end: number
59
+ confidences: number[]
60
+ }
61
+
62
+ function bioParts(label: BIOLabel): { prefix: "B" | "I" | "O"; tag: ComponentTag | null } {
63
+ if (label === "O") return { prefix: "O", tag: null }
64
+ const dash = label.indexOf("-")
65
+
66
+ return { prefix: label.slice(0, dash) as "B" | "I", tag: label.slice(dash + 1) as ComponentTag }
67
+ }
68
+
69
+ // Unicode-aware boundary trim: shrink (start, end) past leading/trailing chars that aren't letters
70
+ // or numbers. Reason: BIO span boundaries from the model occasionally include a preceding comma+
71
+ // space or trailing punctuation token (the "boundary slip" diagnosed in v0.4.0 — see PHASE_2's
72
+ // v0.4.0 entry). The model's tag attribution is correct, only the boundary is fuzzy. Trimming
73
+ // produces a clean canonical value AND clean start/end offsets so downstream consumers slicing
74
+ // raw[start:end] get the same string as node.value.
75
+ function trimBoundary(raw: string, start: number, end: number): { start: number; end: number } {
76
+ let s = start
77
+ let e = end
78
+ const isWordChar = (i: number): boolean => /[\p{L}\p{N}]/u.test(raw[i] ?? "")
79
+
80
+ while (s < e && !isWordChar(s)) {
81
+ s++
82
+ }
83
+
84
+ while (e > s && !isWordChar(e - 1)) {
85
+ e--
86
+ }
87
+
88
+ return { start: s, end: e }
89
+ }
90
+
91
+ function flush(open: OpenSpan | null, raw: string, out: AddressNode[], attribution: BuildTreeOpts): null {
92
+ if (!open) return null
93
+ const { start, end } = trimBoundary(raw, open.start, open.end)
94
+
95
+ // A span that trims to empty (all-punctuation) is meaningless — drop it. Confidence is moot.
96
+ if (start >= end) return null
97
+ const value = raw.slice(start, end)
98
+ const rawConfidence = open.confidences.reduce((a, b) => a + b, 0) / open.confidences.length
99
+ const confidence = attribution.calibrate ? attribution.calibrate(rawConfidence) : rawConfidence
100
+ const node: AddressNode = { tag: open.tag, start, end, value, confidence, children: [] }
101
+
102
+ if (attribution.source !== undefined) {
103
+ node.source = attribution.source
104
+ }
105
+
106
+ if (attribution.sourceID !== undefined) {
107
+ node.sourceID = attribution.sourceID
108
+ }
109
+ out.push(node)
110
+
111
+ return null
112
+ }
113
+
114
+ function emitSpans(raw: string, tokens: DecoderToken[], attribution: BuildTreeOpts): AddressNode[] {
115
+ const out: AddressNode[] = []
116
+ let open: OpenSpan | null = null
117
+
118
+ for (const tok of tokens) {
119
+ const { prefix, tag } = bioParts(tok.label)
120
+
121
+ if (prefix === "O") {
122
+ // A zero-width or whitespace-only `O` piece is a tokenizer artifact — SentencePiece emits a
123
+ // standalone `▁` word-boundary marker between words and the model labels it `O` (e.g.
124
+ // "Saint Paul" → "▁Saint"[B-loc], "▁"[O, zero-width], "Paul"[B-loc]). It is NOT a real
125
+ // component boundary, so it must not flush the open span; keeping the span alive lets the
126
+ // following same-tag `B-` token merge in (see the spurious-boundary repair below). A
127
+ // non-whitespace `O` (comma, slash, …) is a genuine separator and still flushes.
128
+ if (open !== null && /^\s*$/.test(raw.slice(tok.start, tok.end))) continue
129
+ open = flush(open, raw, out, attribution)
130
+ continue
131
+ }
132
+
133
+ if (prefix === "B" || open === null || open.tag !== tag) {
134
+ // Spurious-boundary repair: a `B-X` token that is whitespace-adjacent to an already-open
135
+ // `X` span is the model fragmenting a multi-word value — e.g. "Saint Paul" emitted as
136
+ // B-locality B-locality instead of B-locality I-locality (a real, decode-agnostic
137
+ // emission bug; see scripts/diagnostic/diag-saintalbans.ts). Fold it into the open span.
138
+ //
139
+ // Guard: only merge when the text in `raw` between the two spans is whitespace-only. A
140
+ // comma or any other separator keeps them distinct, and an intervening O/different-tag
141
+ // token already nulls/replaces `open` above — so two separate same-tag spans
142
+ // (e.g. "Springfield, Chicago") are never merged.
143
+ if (prefix === "B" && open !== null && open.tag === tag && /^\s*$/.test(raw.slice(open.end, tok.start))) {
144
+ open.end = tok.end
145
+ open.confidences.push(tok.confidence)
146
+ continue
147
+ }
148
+ open = flush(open, raw, out, attribution)
149
+ open = { tag: tag!, start: tok.start, end: tok.end, confidences: [tok.confidence] }
150
+ continue
151
+ }
152
+
153
+ // I- continuation of same tag.
154
+ open.end = tok.end
155
+ open.confidences.push(tok.confidence)
156
+ }
157
+
158
+ flush(open, raw, out, attribution)
159
+
160
+ return out
161
+ }
162
+
163
+ function distance(a: AddressNode, b: AddressNode): number {
164
+ if (a.end <= b.start) return b.start - a.end
165
+
166
+ if (b.end <= a.start) return a.start - b.end
167
+
168
+ return 0
169
+ }
170
+
171
+ function findParent(
172
+ span: AddressNode,
173
+ all: AddressNode[],
174
+ parentOf: Partial<Record<ComponentTag, ComponentTag[]>>
175
+ ): AddressNode | null {
176
+ const candidates = parentOf[span.tag] ?? []
177
+
178
+ for (const parentTag of candidates) {
179
+ const matches = all.filter((s) => s !== span && s.tag === parentTag)
180
+
181
+ if (matches.length === 0) continue
182
+
183
+ return matches.reduce((best, cur) => (distance(cur, span) < distance(best, span) ? cur : best))
184
+ }
185
+
186
+ return null
187
+ }
188
+
189
+ function sortByStart(nodes: AddressNode[]): void {
190
+ nodes.sort((a, b) => a.start - b.start)
191
+
192
+ for (const n of nodes) {
193
+ sortByStart(n.children)
194
+ }
195
+ }
196
+
197
+ /**
198
+ * Build an `AddressTree` from a raw input string and the token stream produced by the model.
199
+ *
200
+ * @param raw The original input as fed to the tokenizer.
201
+ * @param tokens Model output: one entry per piece with predicted BIO label + confidence.
202
+ * @param opts Optional attribution stamped on every emitted node. Callers in the neural pipeline pass `{ source:
203
+ * "neural", sourceID: <model-card-version> }` to mark provenance for the XML serializer's `src` attribute.
204
+ */
205
+ export function buildAddressTree(raw: string, tokens: DecoderToken[], opts: BuildTreeOpts = {}): AddressTree {
206
+ const spans = emitSpans(raw, tokens, opts)
207
+ const roots: AddressNode[] = []
208
+ const parentOf = containmentFor(opts.system)
209
+
210
+ for (const span of spans) {
211
+ const parent = findParent(span, spans, parentOf)
212
+
213
+ if (parent) {
214
+ parent.children.push(span)
215
+ } else {
216
+ roots.push(span)
217
+ }
218
+ }
219
+
220
+ sortByStart(roots)
221
+ const tree: AddressTree = { raw, roots }
222
+
223
+ if (opts.system !== undefined) {
224
+ tree.system = opts.system
225
+ }
226
+
227
+ return tree
228
+ }