@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,209 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * XML projection — nested mixed-content with attributes.
7
+ *
8
+ * Each component is one element. The element's _direct text node_ is the component's own value
9
+ * (e.g. `<locality>Paris…</locality>` — "Paris" is the locality's text). Children are nested as
10
+ * sub-elements representing geographic / structural containment.
11
+ *
12
+ * Attributes:
13
+ *
14
+ * - `conf` — aggregated confidence in [0, 1], two decimal places.
15
+ * - `start` / `end` — character offsets in the raw input. Preserves source order alongside the
16
+ * containment-derived element order.
17
+ * - `src` — provenance for the assertion. Formatted as `<source>:<sourceID>` when both fields are
18
+ * present on the node, `<source>` when only the broad category is set, omitted when neither
19
+ * is. Phase 4.1 surfaces classifier provenance (`rule:whos_on_first`, `neural:v0.3.1-en-us`);
20
+ * Phase 4.3 overlays resolver provenance (`resolver:wof-admin:101751119`).
21
+ * - `lat` / `lon` — resolver-supplied centroid (Phase 4.3). Emitted only when both are set.
22
+ * - `place` — resolver-supplied normalized place URI like `wof:101751119` (Phase 4.3). Emitted only
23
+ * when `node.placeID` is set; distinct from `src` so callers that want the bare place id
24
+ * without the vendor prefix have a direct attribute to read.
25
+ * - Root `<address>` carries `raw` — the full input string for round-trip.
26
+ *
27
+ * ⚠ DOM gotcha: `element.textContent` on a mixed-content node returns the concatenation of all
28
+ * descendant text (parent value + children values). Use `Array.from(el.childNodes).filter(n =>
29
+ * n.nodeType === 3).map(n => n.nodeValue).join('').trim()` or XPath `text()` to get just the
30
+ * parent's own value. Documented in the package README.
31
+ */
32
+
33
+ import type { AddressNode, AddressTree } from "./types.ts"
34
+ import { unknownSpans } from "./unknown-spans.ts"
35
+
36
+ export interface SerializeXMLOpts {
37
+ /** Pretty-print with line breaks and indentation. Default true. */
38
+ pretty?: boolean
39
+ /** Include `conf` attribute on every component. Default true. */
40
+ includeConf?: boolean
41
+ /** Include `start` + `end` char-offset attributes. Default true. */
42
+ includeOffsets?: boolean
43
+ /** Include `src` provenance attribute when the node carries source info. Default true. */
44
+ includeSrc?: boolean
45
+ /** Include `lat` + `lon` resolver-supplied centroid attrs when set on the node. Default true. */
46
+ includeGeo?: boolean
47
+ /** Include `place` resolver-supplied normalized place URI when set. Default true. */
48
+ includePlace?: boolean
49
+ /**
50
+ * Include `<alternative>` child elements for each runner-up resolver candidate on the node. When set +
51
+ * node.alternatives is populated, each runner-up is emitted as a self-closing element with `place`, `name`, `lat`,
52
+ * `lon`, `score` attributes. Default false — keeps output libpostal-compat when not explicitly requested
53
+ * (Springfield-class disambiguation surfaces only when the caller asks).
54
+ */
55
+ includeAlternatives?: boolean
56
+ /**
57
+ * Emit `<unknown start end>…</unknown>` elements for the all-O runs no node covers — the input the model left
58
+ * unclassified (#493 lossless decomposition). Interleaved with the root components in source order, so the
59
+ * `<address>` children tile the raw input exactly. Default false — keeps output libpostal-compat / the existing shape
60
+ * when not explicitly requested (same posture as {@link includeAlternatives}).
61
+ */
62
+ includeUnknown?: boolean
63
+ }
64
+
65
+ function escapeXml(s: string): string {
66
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;")
67
+ }
68
+
69
+ function srcAttrValue(node: AddressNode): string | null {
70
+ if (node.source && node.sourceID) return `${node.source}:${node.sourceID}`
71
+
72
+ if (node.source) return node.source
73
+
74
+ if (node.sourceID) return node.sourceID
75
+
76
+ return null
77
+ }
78
+
79
+ /**
80
+ * Centroid precision for resolver-supplied lat/lon. 6 decimal places is ~11 cm at the equator — more than enough for
81
+ * any postal-address resolver and short enough to stay readable.
82
+ */
83
+ const GEO_PRECISION = 6
84
+
85
+ function attrs(node: AddressNode, opts: Required<SerializeXMLOpts>): string {
86
+ const parts: string[] = []
87
+
88
+ if (opts.includeOffsets) {
89
+ parts.push(`start="${node.start}"`, `end="${node.end}"`)
90
+ }
91
+
92
+ if (opts.includeConf) {
93
+ parts.push(`conf="${node.confidence.toFixed(2)}"`)
94
+ }
95
+
96
+ if (opts.includeSrc) {
97
+ const src = srcAttrValue(node)
98
+
99
+ if (src !== null) {
100
+ parts.push(`src="${escapeXml(src)}"`)
101
+ }
102
+ }
103
+
104
+ // Emit lat + lon together — a centroid is meaningless with only one coordinate. Resolvers that
105
+ // can produce one but not the other shouldn't decorate the node at all.
106
+ if (opts.includeGeo && node.lat !== undefined && node.lon !== undefined) {
107
+ parts.push(`lat="${node.lat.toFixed(GEO_PRECISION)}"`, `lon="${node.lon.toFixed(GEO_PRECISION)}"`)
108
+ }
109
+
110
+ if (opts.includePlace && node.placeID !== undefined) {
111
+ parts.push(`place="${escapeXml(node.placeID)}"`)
112
+ }
113
+
114
+ // Multi-role node (#413): a city-state span tagged `region` that also plays `locality` lists every
115
+ // role it holds, primary first — `roles="region locality"`. Emitted only when extra roles exist.
116
+ if (node.interpretations && node.interpretations.length > 0) {
117
+ const roles = [node.tag, ...node.interpretations.map((i) => i.tag)]
118
+ parts.push(`roles="${escapeXml(roles.join(" "))}"`)
119
+ }
120
+
121
+ return parts.length === 0 ? "" : " " + parts.join(" ")
122
+ }
123
+
124
+ interface AlternativeLike {
125
+ id: number | string
126
+ name: string
127
+ placetype: string
128
+ lat: number
129
+ lon: number
130
+ score: number
131
+ }
132
+
133
+ function serializeAlternatives(node: AddressNode, indent: string): string {
134
+ if (!node.alternatives || node.alternatives.length === 0) return ""
135
+ const lines = node.alternatives.map((raw) => {
136
+ const alt = raw as AlternativeLike
137
+ const place = `wof:${alt.id}`
138
+ const parts = [
139
+ `place="${escapeXml(place)}"`,
140
+ `name="${escapeXml(alt.name)}"`,
141
+ `placetype="${escapeXml(alt.placetype)}"`,
142
+ `lat="${alt.lat.toFixed(GEO_PRECISION)}"`,
143
+ `lon="${alt.lon.toFixed(GEO_PRECISION)}"`,
144
+ `score="${alt.score.toFixed(3)}"`,
145
+ ]
146
+
147
+ return `${indent}<alternative ${parts.join(" ")} />`
148
+ })
149
+
150
+ return lines.join("\n")
151
+ }
152
+
153
+ function serializeNode(node: AddressNode, indent: string, opts: Required<SerializeXMLOpts>): string {
154
+ const a = attrs(node, opts)
155
+ const text = escapeXml(node.value)
156
+ const nl = opts.pretty ? "\n" : ""
157
+ const childIndent = opts.pretty ? indent + "\t" : ""
158
+
159
+ const altsBlock = opts.includeAlternatives ? serializeAlternatives(node, childIndent) : ""
160
+ const hasChildren = node.children.length > 0
161
+ const hasAlts = altsBlock.length > 0
162
+
163
+ if (!hasChildren && !hasAlts) {
164
+ return `${indent}<${node.tag}${a}>${text}</${node.tag}>`
165
+ }
166
+
167
+ const childrenStr = node.children.map((c) => serializeNode(c, childIndent, opts)).join(nl)
168
+ const inner = [childrenStr, altsBlock].filter(Boolean).join(nl)
169
+
170
+ return `${indent}<${node.tag}${a}>${text}${nl}${inner}${nl}${indent}</${node.tag}>`
171
+ }
172
+
173
+ /** Project an `AddressTree` to nested XML with optional confidence/offset attributes. */
174
+ export function decodeAsXML(tree: AddressTree, opts: SerializeXMLOpts = {}): string {
175
+ const full: Required<SerializeXMLOpts> = {
176
+ pretty: opts.pretty ?? true,
177
+ includeConf: opts.includeConf ?? true,
178
+ includeOffsets: opts.includeOffsets ?? true,
179
+ includeSrc: opts.includeSrc ?? true,
180
+ includeGeo: opts.includeGeo ?? true,
181
+ includePlace: opts.includePlace ?? true,
182
+ includeAlternatives: opts.includeAlternatives ?? false,
183
+ includeUnknown: opts.includeUnknown ?? false,
184
+ }
185
+ const rawAttr = escapeXml(tree.raw)
186
+ const nl = full.pretty ? "\n" : ""
187
+ const indent = full.pretty ? "\t" : ""
188
+
189
+ // Source-ordered XML for the root components. When includeUnknown is set, interleave the all-O gaps as
190
+ // `<unknown>` elements by start offset so the children tile the raw input losslessly.
191
+ const entries: Array<{ start: number; xml: string }> = tree.roots.map((r) => ({
192
+ start: r.start,
193
+ xml: serializeNode(r, indent, full),
194
+ }))
195
+
196
+ if (full.includeUnknown) {
197
+ for (const u of unknownSpans(tree)) {
198
+ entries.push({
199
+ start: u.start,
200
+ xml: `${indent}<unknown start="${u.start}" end="${u.end}">${escapeXml(u.value)}</unknown>`,
201
+ })
202
+ }
203
+ entries.sort((a, b) => a.start - b.start)
204
+ }
205
+
206
+ const children = entries.map((e) => e.xml).join(nl)
207
+
208
+ return `<address raw="${rawAttr}">${nl}${children}${nl}</address>`
209
+ }
@@ -0,0 +1,159 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Output-shape types for the neural classifier decoder.
7
+ *
8
+ * The decoder turns a flat stream of BIO-labeled tokens (the raw output of the sequence model) into
9
+ * an `AddressTree` — a containment-nested representation that downstream code projects into JSON
10
+ * (libpostal-compat), tuple pairs (order-preserving), or XML (hierarchy + attributes).
11
+ *
12
+ * Why three shapes:
13
+ *
14
+ * - JSON is the libpostal-compat surface; downstream users with existing pipelines.
15
+ * - Tuples preserve repetition + source order — fixes the lossy cases JSON can't handle.
16
+ * - XML preserves containment hierarchy and per-node attributes (conf today, src in Phase 4 when the
17
+ * Resolver lands). XML chosen over S-expression for LLM-tooling alignment and off-the-shelf
18
+ * parser availability.
19
+ *
20
+ * See `containment.ts` for the parent-of mapping that drives nesting.
21
+ *
22
+ * Phase 4.1 added optional `source` / `sourceID` on `AddressNode` so the XML serializer can emit
23
+ * provenance via `src="<source>:<sourceID>"`. The neural pipeline stamps these via
24
+ * `BuildTreeOpts`; the proposal-derived path threads them through from `ClassificationProposal`.
25
+ * JSON / tuple projections deliberately do not surface provenance — libpostal compat is
26
+ * essential.
27
+ */
28
+
29
+ import type { BIOLabel, ComponentTag } from "../types/component.ts"
30
+
31
+ export type { BIOLabel, ComponentTag }
32
+
33
+ /**
34
+ * A single token emitted by the model, paired with its predicted label and confidence.
35
+ *
36
+ * `start`/`end` are character offsets into the original raw input. The tokenizer is responsible for producing these
37
+ * (SentencePiece's `encode` returns offsets); they are NOT recomputed by the decoder.
38
+ */
39
+ export interface DecoderToken {
40
+ /** The token piece as the tokenizer emitted it (with any leading-space sentinel preserved). */
41
+ piece: string
42
+ /** Inclusive start char offset in the original raw text. */
43
+ start: number
44
+ /** Exclusive end char offset in the original raw text. */
45
+ end: number
46
+ /** The argmax BIO label for this token. */
47
+ label: BIOLabel
48
+ /** Softmax confidence for the chosen label, in [0, 1]. */
49
+ confidence: number
50
+ }
51
+
52
+ /**
53
+ * One node of the address tree — a component span plus any nested child components.
54
+ *
55
+ * `value` is the raw text covered by this span, sliced from the original input by `[start, end)`. `confidence` is
56
+ * aggregated across the span's tokens (currently mean; see `build-tree.ts`). `children` are tagged subcomponents whose
57
+ * spans fall within this node's span AND whose tag's containment rule names this node's tag as a permitted parent.
58
+ */
59
+ export interface AddressNode {
60
+ tag: ComponentTag
61
+ value: string
62
+ start: number
63
+ end: number
64
+ confidence: number
65
+ children: AddressNode[]
66
+ /**
67
+ * Broad category of the assertion's origin. `"rule"` and `"neural"` come from classifier proposals; `"resolver"` is
68
+ * set by Phase 4.3's resolver when it overwrites the classifier attribution (the displaced classifier source lands in
69
+ * `metadata.classifier_source`).
70
+ */
71
+ source?: string
72
+ /**
73
+ * Specific identifier within `source`: a rule classifier id like `"whos_on_first"`, a neural model card version like
74
+ * `"neural-v0.3.1-en-us"`, or a resolver-supplied place id like `"wof-admin:101751119"`.
75
+ */
76
+ sourceID?: string
77
+ /** Resolver-supplied centroid latitude (Phase 4.3). Optional — only set when a resolver wins. */
78
+ lat?: number
79
+ /** Resolver-supplied centroid longitude (Phase 4.3). Optional — only set when a resolver wins. */
80
+ lon?: number
81
+ /**
82
+ * Resolver-supplied normalized place URI (Phase 4.3) — `"wof:101751119"` for a WOF place. Distinct from `sourceID`
83
+ * (which includes the resolver vendor) so consumers that want the canonical place id without the vendor prefix have
84
+ * one.
85
+ */
86
+ placeID?: string
87
+ /**
88
+ * Opaque per-node metadata bag. Phase 4.3 uses keys `classifier_source` and `classifier_source_id` to preserve the
89
+ * displaced classifier attribution when a resolver wins. Never consulted by the decoder or serializers — debugging +
90
+ * downstream telemetry only.
91
+ */
92
+ metadata?: Record<string, unknown>
93
+ /**
94
+ * Top-k alternative resolutions for this node, ranked by score (highest first). The winning candidate is reflected in
95
+ * `placeID` / `lat` / `lon` / `sourceID`. Surfaced for failure mode #8 (Springfield-class ambiguity) — callers
96
+ * needing disambiguation see the runners-up. Empty / absent when the resolver returned a single candidate.
97
+ *
98
+ * Typed as `unknown[]` here to avoid a circular import on `ResolvedPlace`; resolver-emitting code sets the concrete
99
+ * shape, consumers may cast to `ResolvedPlace[]` from `@mailwoman/core/resolver`.
100
+ */
101
+ alternatives?: ReadonlyArray<unknown>
102
+ /**
103
+ * ADDITIONAL roles this single span plays, beyond `tag` (#413). A place can hold multiple admin tiers under one name
104
+ * — a city-state (Berlin is region AND locality) or a capital-seat province (Milano province ~ Milano comune). Rather
105
+ * than synthesize a second node with a borrowed span, the resolver records the extra role(s) here, so one node = one
106
+ * span = many roles (the model Google's `address_components[].types` uses). `tag`/`placeID`/`lat`/`lon` remain the
107
+ * PRIMARY role; each interpretation is a distinct secondary role with its own resolved place. Serializers surface
108
+ * every role (a city-state emits both `region` and `locality`). Distinct from `alternatives` — those are same-role
109
+ * runner-up places (Springfield IL vs MA); interpretations are DIFFERENT tags, same span. Empty / absent for the
110
+ * common single-role node. Both completion (#415) and a future concordance decode write into this one slot.
111
+ */
112
+ interpretations?: ReadonlyArray<Interpretation>
113
+ }
114
+
115
+ /** One additional role a span plays (#413) — see {@link AddressNode.interpretations}. */
116
+ export interface Interpretation {
117
+ tag: ComponentTag
118
+ /** Resolver-supplied normalized place URI for this role (e.g. `wof:101909779`). */
119
+ placeID?: string
120
+ sourceID?: string
121
+ /** Centroid for this role's place (a capital-seat comune differs from its province). */
122
+ lat?: number
123
+ lon?: number
124
+ confidence?: number
125
+ metadata?: Record<string, unknown>
126
+ }
127
+
128
+ /**
129
+ * The full decoded tree for one parsed address.
130
+ *
131
+ * `roots` is the list of top-level components in source order. Components that don't have a containing parent in the
132
+ * labeled output become roots themselves (e.g. a bare "house_number" with no labeled street parent).
133
+ */
134
+ export interface AddressTree {
135
+ /** The original raw input text — preserved for round-trip and XML root @raw attribute. */
136
+ raw: string
137
+ roots: AddressNode[]
138
+ /**
139
+ * The addressing SYSTEM this tree was decoded under, which selects the containment hierarchy
140
+ * (`containmentFor(system)` in `./containment.ts`). Absent means the default Western hierarchy (`house_number →
141
+ * street → locality → …`).
142
+ *
143
+ * This is forward-compat insurance, not yet a behavioral switch: every system currently resolves to the same map, so
144
+ * an absent or present `system` produces identical trees today. It exists so that when a distinct system lands (e.g.
145
+ * Japanese block addressing, where `building_number` nests under `sub_block`/`block` with no `street` parent),
146
+ * consumers and the tree builder already carry the discriminator — no `AddressTree` shape change later. A locale
147
+ * pre-classifier (Phase 6+) is the intended source of this value.
148
+ */
149
+ system?: AddressSystem
150
+ }
151
+
152
+ /**
153
+ * The addressing system a tree was decoded under — selects the containment hierarchy. Western covers
154
+ * US/EU/most-Latin-script street addressing (`house_number → street → locality`). `japanese` is declared for
155
+ * forward-compat (block addressing: `building_number → sub_block → block → district`, no street); it currently shares
156
+ * the Western map until Phase 6 gives it a distinct one. Open string union so a new system can be added without a
157
+ * breaking enum change.
158
+ */
159
+ export type AddressSystem = "western" | "japanese" | (string & {})
@@ -0,0 +1,103 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Lossless decomposition (#493) — the typed-`unknown`-span primitive. Every byte of the input belongs to
7
+ * exactly one segment: a span some node covers, or an `unknown` run the model left all-O. Those all-O runs
8
+ * are what `decodeAsJSON` silently drops (the JSON-hides-gaps trap) — surfacing them lets a consumer route
9
+ * them to fallback logic, display them, or aggregate them as the self-reporting corpus-gap detector.
10
+ *
11
+ * This is the PURE primitive: it reads `tree.raw` + node `[start,end)` ranges and returns the complement.
12
+ * It mutates nothing and changes no serializer — wiring `unknown` into the JSON/XML/tuple contracts + the
13
+ * demo is the focused follow-up (#493). Byte-stable by construction, so it ships ahead of that work.
14
+ */
15
+ import type { AddressNode, AddressTree } from "./types.ts"
16
+
17
+ export interface UnknownSpan {
18
+ kind: "unknown"
19
+ value: string
20
+ /** Inclusive start char offset into `tree.raw`. */
21
+ start: number
22
+ /** Exclusive end char offset into `tree.raw`. */
23
+ end: number
24
+ }
25
+
26
+ /** One tile of the lossless decomposition: a run that some node covers, or an `unknown` gap. */
27
+ export interface LosslessSegment {
28
+ kind: "covered" | "unknown"
29
+ value: string
30
+ start: number
31
+ end: number
32
+ }
33
+
34
+ /** Mark every char index `tree.raw` that any node's `[start,end)` covers (nesting overlaps merge naturally). */
35
+ function coveredMask(tree: AddressTree): Uint8Array {
36
+ const len = tree.raw.length
37
+ const covered = new Uint8Array(len)
38
+ const stack: AddressNode[] = [...tree.roots]
39
+
40
+ while (stack.length > 0) {
41
+ const n = stack.pop()!
42
+ const lo = Math.max(0, n.start)
43
+ const hi = Math.min(len, n.end)
44
+
45
+ for (let i = lo; i < hi; i++) {
46
+ covered[i] = 1
47
+ }
48
+
49
+ for (const c of n.children) {
50
+ stack.push(c)
51
+ }
52
+ }
53
+
54
+ return covered
55
+ }
56
+
57
+ /**
58
+ * Tile `tree.raw` into maximal covered/unknown runs, in source order. The concatenation of the segment values
59
+ * reproduces `tree.raw` exactly — that is the #493 round-trip invariant ({@link isLossless}).
60
+ */
61
+ export function losslessSegments(tree: AddressTree): LosslessSegment[] {
62
+ const len = tree.raw.length
63
+
64
+ if (len === 0) return []
65
+ const covered = coveredMask(tree)
66
+ const out: LosslessSegment[] = []
67
+ let i = 0
68
+
69
+ while (i < len) {
70
+ const kind = covered[i] ? "covered" : "unknown"
71
+ let j = i + 1
72
+
73
+ while (j < len && !!covered[j] === !!covered[i]) {
74
+ j++
75
+ }
76
+ out.push({ kind, value: tree.raw.slice(i, j), start: i, end: j })
77
+ i = j
78
+ }
79
+
80
+ return out
81
+ }
82
+
83
+ /**
84
+ * The all-O runs no node covers, as typed `unknown` spans, in source order. The complement of the node coverage over
85
+ * `tree.raw`.
86
+ */
87
+ export function unknownSpans(tree: AddressTree): UnknownSpan[] {
88
+ return losslessSegments(tree)
89
+ .filter((s) => s.kind === "unknown")
90
+ .map((s) => ({ kind: "unknown" as const, value: s.value, start: s.start, end: s.end }))
91
+ }
92
+
93
+ /**
94
+ * The #493 round-trip guarantee: concatenating the lossless segments (covered + unknown), in order, reproduces the
95
+ * original input. Holds by construction unless a node span overshoots the input bounds.
96
+ */
97
+ export function isLossless(tree: AddressTree): boolean {
98
+ return (
99
+ losslessSegments(tree)
100
+ .map((s) => s.value)
101
+ .join("") === tree.raw
102
+ )
103
+ }
@@ -0,0 +1,100 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Structural-validity checker for the decoded `AddressTree` — v0.7 task #37.
7
+ *
8
+ * The postcode-only harness scores an address as "pass" on exact component match, but a parse can
9
+ * match a component and still be STRUCTURALLY incoherent — e.g. a `house_number` or
10
+ * `street_suffix` floating with no `street` anywhere, an `attention` with no `venue`. These
11
+ * orphan fragments are the signature of the overconfident hallucinations the v0.6.x cycle fought.
12
+ * This checker lifts the harness from "address-level pass" to "address-level pass AND
13
+ * structurally valid."
14
+ *
15
+ * Two checks:
16
+ *
17
+ * 1. **illegal-edge** — invariant: a non-root node's parent tag must appear in its `PARENT_OF` list.
18
+ * (The tree builder enforces this by construction; the check guards against regressions in
19
+ * build-tree.ts.)
20
+ * 2. **stranded-dependent** — a STRICT dependent tag (one that is meaningless without a structural
21
+ * anchor) whose anchor type is entirely ABSENT from the tree. Geographic containers
22
+ * (postcode / locality / region / street / venue / po_box) are deliberately NOT checked: a
23
+ * postcode-only or city-only input is a degenerate-but-valid parse, not a violation.
24
+ */
25
+
26
+ import type { ComponentTag } from "../types/component.ts"
27
+ import { containmentFor } from "./containment.ts"
28
+ import type { AddressNode, AddressTree } from "./types.ts"
29
+
30
+ /**
31
+ * Tags that cannot stand alone: each is a sub-component of a specific structural anchor (street / locality / venue /
32
+ * postcode). If none of a tag's allowed parents appear anywhere in the tree, the node is an orphan fragment.
33
+ */
34
+ const STRICT_DEPENDENTS: ReadonlySet<ComponentTag> = new Set<ComponentTag>([
35
+ "street_prefix",
36
+ "street_prefix_particle",
37
+ "street_suffix",
38
+ "house_number",
39
+ "unit",
40
+ "dependent_locality",
41
+ "attention",
42
+ "cedex",
43
+ "intersection_a",
44
+ "intersection_b",
45
+ ])
46
+
47
+ export interface TreeViolation {
48
+ type: "illegal-edge" | "stranded-dependent"
49
+ tag: ComponentTag
50
+ value: string
51
+ detail: string
52
+ }
53
+
54
+ export interface TreeValidity {
55
+ valid: boolean
56
+ violations: TreeViolation[]
57
+ }
58
+
59
+ /** Validate an `AddressTree`'s structural coherence. See module docstring. */
60
+ export function validateTree(tree: AddressTree): TreeValidity {
61
+ const violations: TreeViolation[] = []
62
+ // Validate against the tree's own addressing system's hierarchy (defaults to Western).
63
+ const parentOf = containmentFor(tree.system)
64
+
65
+ const present = new Set<ComponentTag>()
66
+ const collect = (n: AddressNode): void => {
67
+ present.add(n.tag)
68
+ n.children.forEach(collect)
69
+ }
70
+ tree.roots.forEach(collect)
71
+
72
+ const walk = (node: AddressNode, parent: AddressNode | null): void => {
73
+ const allowed = parentOf[node.tag]
74
+
75
+ // 1. Edge invariant.
76
+ if (parent && (!allowed || !allowed.includes(parent.tag))) {
77
+ violations.push({
78
+ type: "illegal-edge",
79
+ tag: node.tag,
80
+ value: node.value,
81
+ detail: `${node.tag} nested under ${parent.tag}; allowed parents: [${(allowed ?? []).join(", ")}]`,
82
+ })
83
+ }
84
+
85
+ // 2. Stranded strict-dependent.
86
+ if (STRICT_DEPENDENTS.has(node.tag) && allowed && !allowed.some((t) => present.has(t))) {
87
+ violations.push({
88
+ type: "stranded-dependent",
89
+ tag: node.tag,
90
+ value: node.value,
91
+ detail: `${node.tag} has no anchor (none of [${allowed.join(", ")}] present in the parse)`,
92
+ })
93
+ }
94
+
95
+ node.children.forEach((c) => walk(c, node))
96
+ }
97
+ tree.roots.forEach((r) => walk(r, null))
98
+
99
+ return { valid: violations.length === 0, violations }
100
+ }
package/env/index.ts ADDED
@@ -0,0 +1,42 @@
1
+ import { z } from "zod"
2
+
3
+ import { loadEnvFile } from "./load.ts"
4
+ import { cwdPathBuilder } from "./paths.ts"
5
+ import { PrivateEnvSchema, PublicEnvSchema } from "./schema.ts"
6
+
7
+ // The optional `.env` is read once (it can't change mid-process); the real environment is layered on top
8
+ // LIVE. `process.env` can change during a process — a test stubbing a var, a late setter — and `$public` /
9
+ // `$private` must reflect it, exactly like `process.env` itself. So each key is a getter that re-parses the
10
+ // current `{ ...dotEnv, ...process.env }` on access. The schemas enumerate the keys we know about; `z.object`
11
+ // strips the rest of `process.env`, so only declared keys ever surface, typed.
12
+ const dotEnv = loadEnvFile(cwdPathBuilder(".env"))
13
+
14
+ function liveEnv<Shape extends z.ZodRawShape>(schema: z.ZodObject<Shape>): z.infer<z.ZodObject<Shape>> {
15
+ const view = {} as z.infer<z.ZodObject<Shape>>
16
+
17
+ for (const key of Object.keys(schema.shape)) {
18
+ Object.defineProperty(view, key, {
19
+ enumerable: true,
20
+ // oxlint-disable-next-line sister-software/no-process-globals
21
+ get: () => schema.parse({ ...dotEnv, ...process.env })[key as keyof z.infer<z.ZodObject<Shape>>],
22
+ })
23
+ }
24
+
25
+ return view
26
+ }
27
+
28
+ /**
29
+ * Publicly accessible environment — non-secret operational config (DB paths, batch tuning, `NODE_ENV`). Safe to log. A
30
+ * live, typed view over `process.env` layered on an optional `.env`; only keys in {@link PublicEnvSchema} appear.
31
+ *
32
+ * @see {@link $private} for secrets (tokens, upload credentials).
33
+ */
34
+ export const $public = liveEnv(PublicEnvSchema)
35
+
36
+ /**
37
+ * Privately accessible environment — secrets and credentials (HF token, API keys, rclone S3 creds). Do NOT log. A live,
38
+ * typed view over `process.env` layered on an optional `.env`; only keys in {@link PrivateEnvSchema} appear.
39
+ *
40
+ * @see {@link $public} for non-secret operational config.
41
+ */
42
+ export const $private = liveEnv(PrivateEnvSchema)
package/env/load.ts ADDED
@@ -0,0 +1,14 @@
1
+ import { existsSync, type PathLike, readFileSync } from "node:fs"
2
+ import { parseEnv } from "node:util"
3
+
4
+ /**
5
+ * Parse a `.env` file into a record. Returns `{}` when the file is absent (a `.env` is optional — the real environment
6
+ * is the source of truth; see {@link file://./index.ts}). Values are strings, as written.
7
+ */
8
+ export function loadEnvFile<T extends object = object>(envFilePath: PathLike): T {
9
+ if (!existsSync(envFilePath)) return {} as T
10
+
11
+ const envFileContent = readFileSync(envFilePath, "utf-8")
12
+
13
+ return parseEnv(envFileContent) as T
14
+ }
package/env/paths.ts ADDED
@@ -0,0 +1,40 @@
1
+ import { existsSync } from "node:fs"
2
+ import { homedir } from "node:os"
3
+ import { dirname, resolve } from "node:path"
4
+
5
+ /**
6
+ * Resolve a path relative to the directory Claude Code is running in (cwd).
7
+ *
8
+ * @param paths Path segments to join onto cwd.
9
+ */
10
+ export function cwdPathBuilder(...paths: string[]): string {
11
+ return resolve(process.cwd(), ...paths)
12
+ }
13
+
14
+ /**
15
+ * Find all `.env` files from the current working directory up to the home directory or repo root.
16
+ *
17
+ * @returns An array of `.env` file paths, ordered from shallowest to deepest (cwd last).
18
+ */
19
+ export function cwdEnvPaths(): string[] {
20
+ const found: string[] = []
21
+ let dir = process.cwd()
22
+ const home = homedir()
23
+
24
+ while (true) {
25
+ const candidate = resolve(dir, ".env")
26
+
27
+ if (existsSync(candidate)) {
28
+ found.push(candidate)
29
+ }
30
+
31
+ const parent = dirname(dir)
32
+ const atRepoRoot = existsSync(resolve(dir, ".git"))
33
+
34
+ if (atRepoRoot || dir === home || parent === dir) break
35
+ dir = parent
36
+ }
37
+
38
+ // `found` is deepest-first (cwd first); reverse so cwd is applied last and wins.
39
+ return found.reverse()
40
+ }