vibedgames 0.10.0 → 0.10.2

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 (175) hide show
  1. package/assets/rebuild-object/.cache/spec-search/core_3d.json +1 -0
  2. package/assets/rebuild-object/.cache/spec-search/cs2.json +1 -0
  3. package/assets/rebuild-object/LICENSE +201 -0
  4. package/assets/rebuild-object/NOTICE +7 -0
  5. package/assets/rebuild-object/docs/materials/material-reference.json +2324 -0
  6. package/assets/rebuild-object/docs/specs/render-profile.v2.example.json +63 -0
  7. package/assets/rebuild-object/docs/specs/render-profile.v2.schema.json +56 -0
  8. package/assets/rebuild-object/docs/specs/vocabulary/README.md +86 -0
  9. package/assets/rebuild-object/docs/specs/vocabulary/core_3d.jsonl +12 -0
  10. package/assets/rebuild-object/docs/specs/vocabulary/core_3d_reconstruction.jsonl +37 -0
  11. package/assets/rebuild-object/docs/specs/vocabulary/cs2.jsonl +8 -0
  12. package/assets/rebuild-object/docs/specs/vocabulary/cs2_reconstruction.jsonl +62 -0
  13. package/assets/rebuild-object/forge/_shared/artifact_cache.py +54 -0
  14. package/assets/rebuild-object/forge/_shared/chirality.py +272 -0
  15. package/assets/rebuild-object/forge/_shared/color_metrics.py +107 -0
  16. package/assets/rebuild-object/forge/_shared/feature_acceptance_policy.py +113 -0
  17. package/assets/rebuild-object/forge/_shared/image_hash.py +113 -0
  18. package/assets/rebuild-object/forge/_shared/jpeg.py +448 -0
  19. package/assets/rebuild-object/forge/_shared/material_physics.py +253 -0
  20. package/assets/rebuild-object/forge/_shared/pipeline_routing.py +177 -0
  21. package/assets/rebuild-object/forge/_shared/scalp_field.py +302 -0
  22. package/assets/rebuild-object/forge/_shared/sdf_primitives.py +172 -0
  23. package/assets/rebuild-object/forge/_shared/spec_search.py +1792 -0
  24. package/assets/rebuild-object/forge/_shared/spec_search_profiles.json +58 -0
  25. package/assets/rebuild-object/forge/_shared/status_banner.py +35 -0
  26. package/assets/rebuild-object/forge/_shared/subdivision.py +232 -0
  27. package/assets/rebuild-object/forge/_shared/vertex_paint.py +236 -0
  28. package/assets/rebuild-object/forge/_shared/workflow_state.py +406 -0
  29. package/assets/rebuild-object/forge/materials/__init__.py +17 -0
  30. package/assets/rebuild-object/forge/materials/compatibility.py +106 -0
  31. package/assets/rebuild-object/forge/materials/reference.py +240 -0
  32. package/assets/rebuild-object/forge/next.py +116 -0
  33. package/assets/rebuild-object/forge/report.py +38 -0
  34. package/assets/rebuild-object/forge/requirements.txt +6 -0
  35. package/assets/rebuild-object/forge/stage1_intake/analyze_texture.py +255 -0
  36. package/assets/rebuild-object/forge/stage1_intake/bind_detail_properties.py +99 -0
  37. package/assets/rebuild-object/forge/stage1_intake/build_detail_inventory.py +349 -0
  38. package/assets/rebuild-object/forge/stage1_intake/camera_fitting_math.py +133 -0
  39. package/assets/rebuild-object/forge/stage1_intake/camera_fitting_solver.py +197 -0
  40. package/assets/rebuild-object/forge/stage1_intake/camera_fitting_types.py +291 -0
  41. package/assets/rebuild-object/forge/stage1_intake/camera_image_helpers.py +133 -0
  42. package/assets/rebuild-object/forge/stage1_intake/check_intake_correctness.py +116 -0
  43. package/assets/rebuild-object/forge/stage1_intake/check_reference_admission.py +203 -0
  44. package/assets/rebuild-object/forge/stage1_intake/cs2_foundation.py +139 -0
  45. package/assets/rebuild-object/forge/stage1_intake/cs2_manifest.py +230 -0
  46. package/assets/rebuild-object/forge/stage1_intake/cs2_review_contract.py +42 -0
  47. package/assets/rebuild-object/forge/stage1_intake/delight_albedo.py +352 -0
  48. package/assets/rebuild-object/forge/stage1_intake/detect_cs2.py +276 -0
  49. package/assets/rebuild-object/forge/stage1_intake/detect_reference_effects.py +275 -0
  50. package/assets/rebuild-object/forge/stage1_intake/extract_cs2_textures.py +126 -0
  51. package/assets/rebuild-object/forge/stage1_intake/extract_gradient_stops.py +149 -0
  52. package/assets/rebuild-object/forge/stage1_intake/extract_hair_evidence.py +385 -0
  53. package/assets/rebuild-object/forge/stage1_intake/extract_landmarks.py +456 -0
  54. package/assets/rebuild-object/forge/stage1_intake/extract_part_color_recipe.py +496 -0
  55. package/assets/rebuild-object/forge/stage1_intake/extract_pbr_evidence.py +843 -0
  56. package/assets/rebuild-object/forge/stage1_intake/fetch_cs2_metadata.py +147 -0
  57. package/assets/rebuild-object/forge/stage1_intake/label_glb_nodes.py +318 -0
  58. package/assets/rebuild-object/forge/stage1_intake/locate_cs2_vpk.py +73 -0
  59. package/assets/rebuild-object/forge/stage1_intake/material_region_analysis.py +227 -0
  60. package/assets/rebuild-object/forge/stage1_intake/probe_glb.py +357 -0
  61. package/assets/rebuild-object/forge/stage1_intake/probe_image.py +168 -0
  62. package/assets/rebuild-object/forge/stage1_intake/run_vision_adapter.py +45 -0
  63. package/assets/rebuild-object/forge/stage1_intake/search_specs.py +258 -0
  64. package/assets/rebuild-object/forge/stage1_intake/semantic_decomposition.py +119 -0
  65. package/assets/rebuild-object/forge/stage1_intake/solve_camera_pose.py +254 -0
  66. package/assets/rebuild-object/forge/stage2_spec/apply_material_analysis.py +192 -0
  67. package/assets/rebuild-object/forge/stage2_spec/cs2_adapters.py +62 -0
  68. package/assets/rebuild-object/forge/stage2_spec/derive_geometry.py +118 -0
  69. package/assets/rebuild-object/forge/stage2_spec/hair_profile.py +306 -0
  70. package/assets/rebuild-object/forge/stage2_spec/humanoid_proportions.py +214 -0
  71. package/assets/rebuild-object/forge/stage2_spec/new_pre_spec_assessment.py +343 -0
  72. package/assets/rebuild-object/forge/stage2_spec/new_sculpt_spec.py +2396 -0
  73. package/assets/rebuild-object/forge/stage2_spec/validate_sculpt_spec.py +2871 -0
  74. package/assets/rebuild-object/forge/stage3_build/bake_projected_texture.py +181 -0
  75. package/assets/rebuild-object/forge/stage3_build/decimate.py +272 -0
  76. package/assets/rebuild-object/forge/stage3_build/generate_threejs_factory.py +4099 -0
  77. package/assets/rebuild-object/forge/stage3_build/module_cache.py +155 -0
  78. package/assets/rebuild-object/forge/stage3_build/morph_targets.py +178 -0
  79. package/assets/rebuild-object/forge/stage3_build/orchestrate_passes.py +653 -0
  80. package/assets/rebuild-object/forge/stage3_build/uv_unwrap.py +622 -0
  81. package/assets/rebuild-object/forge/stage3_build/visual_hull.py +357 -0
  82. package/assets/rebuild-object/forge/stage4_review/_fit_divine_eye.py +64 -0
  83. package/assets/rebuild-object/forge/stage4_review/append_review.py +453 -0
  84. package/assets/rebuild-object/forge/stage4_review/attachment_anchor.py +349 -0
  85. package/assets/rebuild-object/forge/stage4_review/calibrate_eye.py +131 -0
  86. package/assets/rebuild-object/forge/stage4_review/check_part_coverage.py +298 -0
  87. package/assets/rebuild-object/forge/stage4_review/compare_region_passes.py +169 -0
  88. package/assets/rebuild-object/forge/stage4_review/correction_loop.py +258 -0
  89. package/assets/rebuild-object/forge/stage4_review/cs2_review.py +224 -0
  90. package/assets/rebuild-object/forge/stage4_review/diagnose_render.py +356 -0
  91. package/assets/rebuild-object/forge/stage4_review/diagnose_render_multi_angle.py +143 -0
  92. package/assets/rebuild-object/forge/stage4_review/divine_eye.py +461 -0
  93. package/assets/rebuild-object/forge/stage4_review/fit_params.py +381 -0
  94. package/assets/rebuild-object/forge/stage4_review/geometry_integrity.py +294 -0
  95. package/assets/rebuild-object/forge/stage4_review/hair_gate.py +216 -0
  96. package/assets/rebuild-object/forge/stage4_review/interior_difference.py +188 -0
  97. package/assets/rebuild-object/forge/stage4_review/joint_loops.py +209 -0
  98. package/assets/rebuild-object/forge/stage4_review/make_comparison_sheet.py +292 -0
  99. package/assets/rebuild-object/forge/stage4_review/material_comparator.py +181 -0
  100. package/assets/rebuild-object/forge/stage4_review/material_feedback.py +143 -0
  101. package/assets/rebuild-object/forge/stage4_review/material_gate.py +126 -0
  102. package/assets/rebuild-object/forge/stage4_review/material_views.py +184 -0
  103. package/assets/rebuild-object/forge/stage4_review/mesh_reference_compare.py +362 -0
  104. package/assets/rebuild-object/forge/stage4_review/multi_pass.py +102 -0
  105. package/assets/rebuild-object/forge/stage4_review/objectness.py +143 -0
  106. package/assets/rebuild-object/forge/stage4_review/pairwise_penetration.py +376 -0
  107. package/assets/rebuild-object/forge/stage4_review/per_feature.py +215 -0
  108. package/assets/rebuild-object/forge/stage4_review/render_bridge.py +556 -0
  109. package/assets/rebuild-object/forge/stage4_review/scalp_exposure.py +257 -0
  110. package/assets/rebuild-object/forge/stage4_review/self_intersection.py +592 -0
  111. package/assets/rebuild-object/forge/stage4_review/swept_arc_gate.py +336 -0
  112. package/assets/rebuild-object/forge/stage4_review/turntable_gate.py +415 -0
  113. package/assets/rebuild-object/forge/stage4_review/validate_render_profile.py +182 -0
  114. package/assets/rebuild-object/forge/stage4_review/vertex_region_gate.py +456 -0
  115. package/assets/rebuild-object/forge/stage4_review/vlm_gate.py +196 -0
  116. package/assets/rebuild-object/forge/stage5_rig/NOTES.md +149 -0
  117. package/assets/rebuild-object/forge/stage5_rig/__init__.py +6 -0
  118. package/assets/rebuild-object/forge/stage5_rig/emit_rig.py +420 -0
  119. package/assets/rebuild-object/forge/stage5_rig/geodesic_skinning.py +508 -0
  120. package/assets/rebuild-object/forge/stage5_rig/rig_spec.py +174 -0
  121. package/assets/rebuild-object/forge/stage5_rig/validate_rig_payload.py +195 -0
  122. package/assets/rebuild-object/forge/state.py +98 -0
  123. package/assets/rebuild-object/steps.json +381 -0
  124. package/dist/{chunk-FXXVXDTW.js → chunk-24TITAFS.js} +1 -1
  125. package/dist/{chunk-OGX4DKIS.js → chunk-2C5PG2QO.js} +1 -1
  126. package/dist/{chunk-HYOXGNWS.js → chunk-2DEVOKI7.js} +1 -1
  127. package/dist/{chunk-RRI23NK2.js → chunk-2GHPYT2P.js} +1 -1
  128. package/dist/{chunk-S7HYWITX.js → chunk-2HXGMXGC.js} +1 -1
  129. package/dist/{chunk-N2UHAQXC.js → chunk-36FORP7T.js} +0 -1
  130. package/dist/{chunk-VB4WLJR2.js → chunk-3IXRQTRF.js} +1 -1
  131. package/dist/{chunk-2KVQJKIZ.js → chunk-4ENHS32B.js} +23 -36
  132. package/dist/{chunk-SXYQL4GK.js → chunk-4YHA32OE.js} +1 -1
  133. package/dist/{chunk-4FJXCS3K.js → chunk-4ZGQKPK5.js} +1 -1
  134. package/dist/{chunk-SBXCK2I2.js → chunk-6CLUPFQA.js} +2 -2
  135. package/dist/{chunk-TXOE5UY5.js → chunk-7WTF2BA4.js} +1 -1
  136. package/dist/{chunk-R2WVORGD.js → chunk-AAXZNK4Z.js} +1 -1
  137. package/dist/{chunk-DOOQUFPG.js → chunk-ALLBT4FB.js} +1 -1
  138. package/dist/{chunk-HRKVAXNN.js → chunk-BAZDPPIG.js} +5 -5
  139. package/dist/{chunk-RPJR3S5S.js → chunk-CYDENLZ4.js} +5 -8
  140. package/dist/{chunk-I5LELJSK.js → chunk-DKSUD44G.js} +1 -1
  141. package/dist/{chunk-43P4U7CB.js → chunk-DWWSJKTE.js} +1 -1
  142. package/dist/{chunk-SUSX3QIA.js → chunk-E72TFJZP.js} +1 -1
  143. package/dist/{chunk-E3FJUPLT.js → chunk-EUAAQMUA.js} +2 -0
  144. package/dist/{chunk-U6DTE5IX.js → chunk-F7LYJSZE.js} +1 -1
  145. package/dist/{chunk-MEAO33XW.js → chunk-FMON3C74.js} +8 -8
  146. package/dist/{chunk-GLEW7VJQ.js → chunk-FPILHRLZ.js} +1 -1
  147. package/dist/{chunk-OPUCUUID.js → chunk-G63MXDX2.js} +4 -0
  148. package/dist/{chunk-4UU622RK.js → chunk-GGO6ZYYI.js} +1 -3
  149. package/dist/{chunk-2ZKS7V72.js → chunk-GZCRYYS6.js} +5 -5
  150. package/dist/{chunk-E7NDOZ27.js → chunk-LE4GVTYI.js} +8 -8
  151. package/dist/{chunk-RKS7SI5L.js → chunk-NO6KPV64.js} +1 -1
  152. package/dist/{chunk-KJK5CB6E.js → chunk-NXW3Z4Y4.js} +1 -1
  153. package/dist/{chunk-7RPLQWR2.js → chunk-OHOAZGO4.js} +1 -1
  154. package/dist/chunk-PYJNI5WD.js +83 -0
  155. package/dist/{chunk-NCX6LYNJ.js → chunk-Q4XAGTFX.js} +1 -1
  156. package/dist/{chunk-3UGGMFJJ.js → chunk-QMZBSVKF.js} +1 -1
  157. package/dist/{chunk-ABTUEIRC.js → chunk-QO66UBOS.js} +2 -2
  158. package/dist/{chunk-LONQWRTR.js → chunk-S4KVGQQO.js} +8 -8
  159. package/dist/{chunk-HX5Q63UA.js → chunk-T777EXAO.js} +1 -1
  160. package/dist/{chunk-UQ7VO6B3.js → chunk-TZZNRA3S.js} +1 -1
  161. package/dist/{chunk-CTY2WZQK.js → chunk-UC3QLWMQ.js} +1 -1
  162. package/dist/{chunk-MR5KIFI7.js → chunk-UDJH2RED.js} +3 -3
  163. package/dist/{chunk-ZHLPE6LI.js → chunk-UIKYK7KI.js} +1 -1
  164. package/dist/{chunk-KAGVI3CE.js → chunk-UJRSQO2B.js} +1 -1
  165. package/dist/{chunk-Q2QC6KAZ.js → chunk-V7LEYVXB.js} +29 -25
  166. package/dist/{chunk-DB7WVFS7.js → chunk-WRMQEXUC.js} +1 -1
  167. package/dist/{chunk-HSMG6U7J.js → chunk-WXSBNC67.js} +3 -9
  168. package/dist/{chunk-QLCVLCPM.js → chunk-X4QIOXNQ.js} +1 -1
  169. package/dist/{chunk-5YPLKGY3.js → chunk-Y6WHUK2O.js} +1 -1
  170. package/dist/{chunk-VZEJ2ZHE.js → chunk-Z3E7ORGQ.js} +5 -5
  171. package/dist/index.js +20 -20
  172. package/package.json +32 -22
  173. package/dist/{chunk-Q3XQPNF6.js → chunk-BN7TR6OR.js} +3 -3
  174. package/dist/{chunk-LORGE2NB.js → chunk-U2NCN5RO.js} +3 -3
  175. package/dist/{chunk-UPHB5HWO.js → chunk-VQTTSPA3.js} +3 -3
@@ -0,0 +1,1792 @@
1
+ """Profile, record, tokenizer, and source-ingestion boundary. # noqa: SIZE_OK"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import hashlib
7
+ import math
8
+ import os
9
+ import re
10
+ import stat
11
+ import tempfile
12
+ import unicodedata
13
+ from collections import Counter
14
+ from collections.abc import Mapping, Sequence
15
+ from dataclasses import dataclass
16
+ from pathlib import Path
17
+ from typing import Final, Literal, NoReturn, TypeAlias, TypedDict
18
+
19
+ JsonScalar: TypeAlias = str | int | float | bool | None
20
+ JsonValue: TypeAlias = JsonScalar | list["JsonValue"] | dict[str, "JsonValue"]
21
+ SourceKind: TypeAlias = Literal["markdown", "json", "jsonl"]
22
+ CacheStatus: TypeAlias = Literal["hit", "rebuilt"]
23
+ CacheReason: TypeAlias = Literal["current", "missing", "stale", "corrupt", "forced"]
24
+ UnicodeNormalization: TypeAlias = Literal["NFC", "NFD", "NFKC", "NFKD"]
25
+ AccentFold: TypeAlias = Literal["none", "vi"]
26
+ _SOURCE_KINDS: Final[dict[str, SourceKind]] = {
27
+ ".md": "markdown",
28
+ ".json": "json",
29
+ ".jsonl": "jsonl",
30
+ }
31
+
32
+
33
+ class TokenizerSettings(TypedDict):
34
+ version: str
35
+ unicode_normalization: UnicodeNormalization
36
+ casefold: bool
37
+ accent_fold: AccentFold
38
+ preserve_identifiers: bool
39
+ preserve_numbers: bool
40
+
41
+
42
+ class AliasSettings(TypedDict):
43
+ enabled: bool
44
+ max_expansions: int
45
+
46
+
47
+ class Bm25Settings(TypedDict):
48
+ k1: float
49
+ b: float
50
+
51
+
52
+ class CollectionProfile(TypedDict):
53
+ source_roots: list[str]
54
+ optional_source_roots: list[str]
55
+ distilled_records: list[str]
56
+ cache: str
57
+ documentation: str
58
+ encoding: str
59
+ languages: list[str]
60
+ source_extensions: list[str]
61
+ tokenizer: TokenizerSettings
62
+ aliases: AliasSettings
63
+ bm25: Bm25Settings
64
+ term_aliases: dict[str, list[str]]
65
+
66
+
67
+ class MeasurementRequired(TypedDict):
68
+ name: str
69
+ value: str
70
+
71
+
72
+ class Measurement(MeasurementRequired, total=False):
73
+ unit: str
74
+ context: str
75
+
76
+
77
+ class SourceRefRequired(TypedDict):
78
+ path: str
79
+
80
+
81
+ class SourceRef(SourceRefRequired, total=False):
82
+ heading: str
83
+ key_path: str
84
+
85
+
86
+ class EvidenceRefRequired(TypedDict):
87
+ kind: str
88
+ ref: str
89
+
90
+
91
+ class EvidenceRef(EvidenceRefRequired, total=False):
92
+ note: str
93
+
94
+
95
+ class SpecRecord(TypedDict):
96
+ record_id: str
97
+ collection: str
98
+ domain: str
99
+ kind: str
100
+ entity: str
101
+ title: str
102
+ aliases: list[str]
103
+ content: str
104
+ constraints: list[str]
105
+ measurements: list[Measurement]
106
+ source_refs: list[SourceRef]
107
+ evidence_refs: list[EvidenceRef]
108
+ observation_status: str
109
+ confidence: float
110
+ assumptions: list[str]
111
+
112
+
113
+ class CachedSourceReference(TypedDict):
114
+ path: str
115
+ heading: str | None
116
+ key_path: str | None
117
+
118
+
119
+ class CachedEvidenceReferenceRequired(TypedDict):
120
+ kind: str
121
+ ref: str
122
+
123
+
124
+ class CachedEvidenceReference(CachedEvidenceReferenceRequired, total=False):
125
+ note: str
126
+
127
+
128
+ class CachedRecord(TypedDict):
129
+ record_id: str
130
+ collection: str
131
+ title: str
132
+ content: str
133
+ file_path: str
134
+ heading: str | None
135
+ key_path: str | None
136
+ aliases: list[str]
137
+ source_refs: list[CachedSourceReference]
138
+ evidence_refs: list[CachedEvidenceReference]
139
+
140
+
141
+ class CachedPosting(TypedDict):
142
+ record_id: str
143
+ term_frequency: int
144
+
145
+
146
+ class CachePayload(TypedDict):
147
+ schema_version: int
148
+ schema_fingerprint: str
149
+ tokenizer_fingerprint: str
150
+ config_fingerprint: str
151
+ source_fingerprint: str
152
+ fingerprint: str
153
+ collection: str
154
+ k1: float
155
+ b: float
156
+ tokenizer: TokenizerSettings
157
+ document_lengths: dict[str, int]
158
+ avgdl: float
159
+ document_frequencies: dict[str, int]
160
+ postings: dict[str, list[CachedPosting]]
161
+ records: dict[str, CachedRecord]
162
+ term_aliases: dict[str, list[str]]
163
+
164
+
165
+ @dataclass(frozen=True, slots=True)
166
+ class SourceReference:
167
+ path: str
168
+ heading: str | None = None
169
+ key_path: str | None = None
170
+
171
+
172
+ @dataclass(frozen=True, slots=True)
173
+ class EvidenceReference:
174
+ kind: str
175
+ ref: str
176
+ note: str | None = None
177
+
178
+
179
+ @dataclass(frozen=True, slots=True)
180
+ class SourceDocument:
181
+ record_id: str
182
+ collection: str
183
+ title: str
184
+ content: str
185
+ file_path: str
186
+ heading: str | None = None
187
+ key_path: str | None = None
188
+ aliases: tuple[str, ...] = ()
189
+ source_refs: tuple[SourceReference, ...] = ()
190
+ evidence_refs: tuple[EvidenceReference, ...] = ()
191
+
192
+
193
+ @dataclass(frozen=True, slots=True)
194
+ class TokenizerConfig:
195
+ version: str = "1"
196
+ unicode_normalization: UnicodeNormalization = "NFKC"
197
+ casefold: bool = True
198
+ accent_fold: AccentFold = "vi"
199
+ preserve_identifiers: bool = True
200
+ preserve_numbers: bool = True
201
+
202
+
203
+ @dataclass(frozen=True, slots=True)
204
+ class Bm25Config:
205
+ collection: str
206
+ k1: float = 1.5
207
+ b: float = 0.75
208
+ tokenizer: TokenizerConfig = TokenizerConfig()
209
+ term_aliases: tuple[tuple[str, tuple[str, ...]], ...] = ()
210
+
211
+
212
+ @dataclass(frozen=True, slots=True)
213
+ class IndexFingerprints:
214
+ schema: str = ""
215
+ tokenizer: str = ""
216
+ config: str = ""
217
+ source: str = ""
218
+
219
+ @property
220
+ def combined(self) -> str:
221
+ return _fingerprint(
222
+ {
223
+ "schema": self.schema,
224
+ "tokenizer": self.tokenizer,
225
+ "config": self.config,
226
+ "source": self.source,
227
+ }
228
+ )
229
+
230
+
231
+ @dataclass(frozen=True, slots=True)
232
+ class Posting:
233
+ record_id: str
234
+ term_frequency: int
235
+
236
+
237
+ @dataclass(frozen=True, slots=True)
238
+ class Bm25Index:
239
+ collection: str
240
+ k1: float
241
+ b: float
242
+ tokenizer: TokenizerConfig
243
+ fingerprints: IndexFingerprints
244
+ document_lengths: Mapping[str, int]
245
+ avgdl: float
246
+ document_frequencies: Mapping[str, int]
247
+ postings: Mapping[str, tuple[Posting, ...]]
248
+ records: Mapping[str, SourceDocument]
249
+ term_aliases: Mapping[str, tuple[str, ...]]
250
+
251
+ @property
252
+ def fingerprint(self) -> str:
253
+ return self.fingerprints.combined
254
+
255
+
256
+ @dataclass(frozen=True, slots=True)
257
+ class SearchMatch:
258
+ record: SourceDocument
259
+ score: float
260
+
261
+
262
+ class SerializedSearchMatch(TypedDict):
263
+ record_id: str
264
+ file_path: str
265
+ heading: str | None
266
+ key_path: str | None
267
+ score: float
268
+ snippets: list[str]
269
+ source_refs: list[CachedSourceReference]
270
+ evidence_refs: list[CachedEvidenceReference]
271
+
272
+
273
+ @dataclass(frozen=True, slots=True)
274
+ class SearchOutputRequest:
275
+ query: str
276
+ limit: int
277
+ snippet_chars: int
278
+
279
+
280
+ @dataclass(frozen=True, slots=True)
281
+ class IndexRequest:
282
+ project_root: Path
283
+ collection: str
284
+ profile: CollectionProfile
285
+ force_reindex: bool = False
286
+
287
+
288
+ @dataclass(frozen=True, slots=True)
289
+ class IndexLoadResult:
290
+ index: Bm25Index
291
+ status: CacheStatus
292
+ reason: CacheReason
293
+ cache_path: Path
294
+
295
+ @property
296
+ def fingerprint(self) -> str:
297
+ return self.index.fingerprint
298
+
299
+
300
+ @dataclass(frozen=True, slots=True)
301
+ class ConfiguredSource:
302
+ path: Path
303
+ source_path: str
304
+ kind: SourceKind
305
+
306
+
307
+ @dataclass(frozen=True, slots=True)
308
+ class ProfileValidationError(ValueError):
309
+ path: Path
310
+ reason: str
311
+
312
+ def __str__(self) -> str:
313
+ return f"{self.path}: {self.reason}"
314
+
315
+
316
+ @dataclass(frozen=True, slots=True)
317
+ class ProfileCachePathError(ValueError):
318
+ reason: str
319
+
320
+ def __str__(self) -> str:
321
+ return self.reason
322
+
323
+
324
+ @dataclass(frozen=True, slots=True)
325
+ class UnknownCollectionError(KeyError):
326
+ collection: str
327
+
328
+ def __str__(self) -> str:
329
+ return f"unknown spec-search collection: {self.collection}"
330
+
331
+
332
+ @dataclass(frozen=True, slots=True)
333
+ class SourceIngestionError(Exception):
334
+ path: Path
335
+ reason: str
336
+
337
+ def __str__(self) -> str:
338
+ return f"{self.path}: {self.reason}"
339
+
340
+
341
+ @dataclass(frozen=True, slots=True)
342
+ class SpecRecordValidationError(ValueError):
343
+ path: Path
344
+ line_number: int
345
+ reason: str
346
+
347
+ def __str__(self) -> str:
348
+ return f"{self.path}:{self.line_number}: {self.reason}"
349
+
350
+
351
+ @dataclass(frozen=True, slots=True)
352
+ class IndexBuildError(ValueError):
353
+ reason: str
354
+
355
+ def __str__(self) -> str:
356
+ return self.reason
357
+
358
+
359
+ @dataclass(frozen=True, slots=True)
360
+ class CacheValidationError(ValueError):
361
+ path: Path
362
+ reason: str
363
+
364
+ def __str__(self) -> str:
365
+ return f"{self.path}: {self.reason}"
366
+
367
+
368
+ @dataclass(frozen=True, slots=True)
369
+ class CacheReadError(Exception):
370
+ path: Path
371
+ reason: str
372
+
373
+ def __str__(self) -> str:
374
+ return f"{self.path}: {self.reason}"
375
+
376
+
377
+ @dataclass(frozen=True, slots=True)
378
+ class CacheWriteError(Exception):
379
+ path: Path
380
+ reason: str
381
+
382
+ def __str__(self) -> str:
383
+ return f"{self.path}: {self.reason}"
384
+
385
+
386
+ _DEFAULT_PROFILES_PATH: Final = Path(__file__).with_name("spec_search_profiles.json")
387
+ _CACHE_SCHEMA_VERSION: Final = 2
388
+ _TOKENIZER_SCHEMA_VERSION: Final = "2"
389
+ _DEFAULT_TOKENIZER_CONFIG: Final = TokenizerConfig()
390
+ _NORMALIZATION_BY_NAME: Final[dict[str, UnicodeNormalization]] = {
391
+ "NFC": "NFC",
392
+ "NFD": "NFD",
393
+ "NFKC": "NFKC",
394
+ "NFKD": "NFKD",
395
+ }
396
+ _ACCENT_FOLD_BY_NAME: Final[dict[str, AccentFold]] = {
397
+ "none": "none",
398
+ "vi": "vi",
399
+ }
400
+ _IDENTIFIER_TOKEN_PATTERN: Final = re.compile(
401
+ r"[^\W_]+(?:[_.\-\u2010-\u2015][^\W_]+)*",
402
+ re.UNICODE,
403
+ )
404
+ _WORD_TOKEN_PATTERN: Final = re.compile(r"[^\W_]+", re.UNICODE)
405
+ _DASH_TRANSLATION: Final = str.maketrans({character: "-" for character in "‐‑‒–—―"})
406
+ _VIETNAMESE_MARKED: Final = frozenset(
407
+ "àáảãạăằắẳẵặâầấẩẫậèéẻẽẹêềếểễệìíỉĩịòóỏõọôồốổỗộơờớởỡợ"
408
+ "ùúủũụưừứửữựỳýỷỹỵđ"
409
+ )
410
+
411
+
412
+ def _profile_error(path: Path, reason: str) -> ProfileValidationError:
413
+ return ProfileValidationError(path=path, reason=reason)
414
+
415
+
416
+ def _mapping(value: JsonValue, path: Path, label: str) -> dict[str, JsonValue]:
417
+ if type(value) is not dict:
418
+ raise _profile_error(path, f"{label} must be an object")
419
+ return value
420
+
421
+
422
+ def _profile_string(mapping: dict[str, JsonValue], field: str, path: Path) -> str:
423
+ value = mapping.get(field)
424
+ if type(value) is not str or not value:
425
+ raise _profile_error(path, f"{field} must be a non-empty string")
426
+ return value
427
+
428
+
429
+ def _profile_string_list(mapping: dict[str, JsonValue], field: str, path: Path) -> list[str]:
430
+ value = mapping.get(field)
431
+ if type(value) is not list:
432
+ raise _profile_error(path, f"{field} must be an array of non-empty strings")
433
+ parsed: list[str] = []
434
+ for item in value:
435
+ if type(item) is not str or not item:
436
+ raise _profile_error(path, f"{field} must be an array of non-empty strings")
437
+ parsed.append(item)
438
+ return parsed
439
+
440
+
441
+ def _profile_bool(mapping: dict[str, JsonValue], field: str, path: Path) -> bool:
442
+ value = mapping.get(field)
443
+ if type(value) is not bool:
444
+ raise _profile_error(path, f"{field} must be a boolean")
445
+ return value
446
+
447
+
448
+ def _profile_number(mapping: dict[str, JsonValue], field: str, path: Path) -> float:
449
+ value = mapping.get(field)
450
+ if type(value) is bool or not isinstance(value, (int, float)):
451
+ raise _profile_error(path, f"{field} must be a number")
452
+ return float(value)
453
+
454
+
455
+ def _profile_normalization(
456
+ mapping: dict[str, JsonValue],
457
+ field: str,
458
+ path: Path,
459
+ ) -> UnicodeNormalization:
460
+ value = _profile_string(mapping, field, path)
461
+ normalization = _NORMALIZATION_BY_NAME.get(value)
462
+ if normalization is None:
463
+ raise _profile_error(path, f"{field} must be NFC, NFD, NFKC, or NFKD")
464
+ return normalization
465
+
466
+
467
+ def _profile_accent_fold(
468
+ mapping: dict[str, JsonValue],
469
+ field: str,
470
+ path: Path,
471
+ ) -> AccentFold:
472
+ value = _profile_string(mapping, field, path)
473
+ accent_fold = _ACCENT_FOLD_BY_NAME.get(value)
474
+ if accent_fold is None:
475
+ raise _profile_error(path, f"{field} must be none or vi")
476
+ return accent_fold
477
+
478
+
479
+ def _profile_cache_path(mapping: dict[str, JsonValue], path: Path) -> str:
480
+ configured = _profile_string(mapping, "cache", path)
481
+ cache_path = Path(configured)
482
+ if cache_path.is_absolute() or ".." in cache_path.parts:
483
+ raise ProfileCachePathError(
484
+ "cache path must be relative and stay within project_root"
485
+ )
486
+ return configured
487
+
488
+
489
+ def load_profiles(path: Path | None = None) -> dict[str, CollectionProfile]:
490
+ profile_path = _DEFAULT_PROFILES_PATH if path is None else path
491
+ try:
492
+ raw: JsonValue = json.loads(profile_path.read_text(encoding="utf-8"))
493
+ except json.JSONDecodeError as error:
494
+ raise _profile_error(profile_path, "invalid JSON profile") from error
495
+ except (OSError, UnicodeError) as error:
496
+ raise _profile_error(profile_path, "unable to read UTF-8 profile") from error
497
+ root = _mapping(raw, profile_path, "profile")
498
+ version = root.get("profile_schema_version")
499
+ if type(version) is not int or version < 1:
500
+ raise _profile_error(profile_path, "profile_schema_version must be a positive integer")
501
+ defaults = _mapping(root.get("defaults"), profile_path, "defaults")
502
+ tokenizer_raw = _mapping(defaults.get("tokenizer"), profile_path, "defaults.tokenizer")
503
+ alias_raw = _mapping(defaults.get("aliases"), profile_path, "defaults.aliases")
504
+ bm25_raw = _mapping(defaults.get("bm25"), profile_path, "defaults.bm25")
505
+ max_expansions = alias_raw.get("max_expansions")
506
+ if type(max_expansions) is not int or max_expansions < 0:
507
+ raise _profile_error(profile_path, "defaults.aliases.max_expansions must be a non-negative integer")
508
+ tokenizer: TokenizerSettings = {
509
+ "version": _profile_string(tokenizer_raw, "version", profile_path),
510
+ "unicode_normalization": _profile_normalization(
511
+ tokenizer_raw,
512
+ "unicode_normalization",
513
+ profile_path,
514
+ ),
515
+ "casefold": _profile_bool(tokenizer_raw, "casefold", profile_path),
516
+ "accent_fold": _profile_accent_fold(tokenizer_raw, "accent_fold", profile_path),
517
+ "preserve_identifiers": _profile_bool(tokenizer_raw, "preserve_identifiers", profile_path),
518
+ "preserve_numbers": _profile_bool(tokenizer_raw, "preserve_numbers", profile_path),
519
+ }
520
+ alias_settings: AliasSettings = {
521
+ "enabled": _profile_bool(alias_raw, "enabled", profile_path),
522
+ "max_expansions": max_expansions,
523
+ }
524
+ bm25: Bm25Settings = {
525
+ "k1": _profile_number(bm25_raw, "k1", profile_path),
526
+ "b": _profile_number(bm25_raw, "b", profile_path),
527
+ }
528
+ collections = _mapping(root.get("collections"), profile_path, "collections")
529
+ parsed: dict[str, CollectionProfile] = {}
530
+ for name in sorted(collections):
531
+ collection = _mapping(collections[name], profile_path, f"collections.{name}")
532
+ term_aliases_raw = collection.get("term_aliases", {})
533
+ term_aliases_mapping = _mapping(term_aliases_raw, profile_path, f"collections.{name}.term_aliases")
534
+ term_aliases = {
535
+ term: _profile_string_list(term_aliases_mapping, term, profile_path)
536
+ for term in sorted(term_aliases_mapping)
537
+ }
538
+ parsed[name] = {
539
+ "source_roots": _profile_string_list(collection, "source_roots", profile_path),
540
+ "optional_source_roots": _profile_string_list(
541
+ collection,
542
+ "optional_source_roots",
543
+ profile_path,
544
+ ),
545
+ "distilled_records": _profile_string_list(collection, "distilled_records", profile_path),
546
+ "documentation": _profile_string(collection, "documentation", profile_path),
547
+ "cache": _profile_cache_path(collection, profile_path),
548
+ "encoding": _profile_string(defaults, "encoding", profile_path),
549
+ "languages": _profile_string_list(defaults, "languages", profile_path),
550
+ "source_extensions": _profile_string_list(defaults, "source_extensions", profile_path),
551
+ "tokenizer": tokenizer,
552
+ "aliases": alias_settings,
553
+ "bm25": bm25,
554
+ "term_aliases": term_aliases,
555
+ }
556
+ return parsed
557
+
558
+
559
+ def load_profile(collection: str, path: Path | None = None) -> CollectionProfile:
560
+ profiles = load_profiles(path)
561
+ if collection not in profiles:
562
+ raise UnknownCollectionError(collection=collection)
563
+ return profiles[collection]
564
+
565
+
566
+ def _record_error(path: Path, line_number: int, reason: str) -> SpecRecordValidationError:
567
+ return SpecRecordValidationError(path=path, line_number=line_number, reason=reason)
568
+
569
+
570
+ def _record_mapping(value: JsonValue, path: Path, line_number: int) -> dict[str, JsonValue]:
571
+ if type(value) is not dict:
572
+ raise _record_error(path, line_number, "record must be a JSON object")
573
+ return value
574
+
575
+
576
+ def _record_string(
577
+ record: dict[str, JsonValue],
578
+ field: str,
579
+ location: tuple[Path, int],
580
+ *,
581
+ allow_empty: bool = False,
582
+ ) -> str:
583
+ value = record.get(field)
584
+ if type(value) is not str or (not allow_empty and not value):
585
+ qualifier = "a string" if allow_empty else "a non-empty string"
586
+ raise _record_error(location[0], location[1], f"{field} must be {qualifier}")
587
+ return value
588
+
589
+
590
+ def _record_string_list(
591
+ record: dict[str, JsonValue],
592
+ field: str,
593
+ location: tuple[Path, int],
594
+ ) -> list[str]:
595
+ value = record.get(field)
596
+ if type(value) is not list:
597
+ raise _record_error(location[0], location[1], f"{field} must be an array of strings")
598
+ parsed: list[str] = []
599
+ for item in value:
600
+ if type(item) is not str:
601
+ raise _record_error(location[0], location[1], f"{field} must be an array of strings")
602
+ parsed.append(item)
603
+ return parsed
604
+
605
+
606
+ def _measurements(record: dict[str, JsonValue], location: tuple[Path, int]) -> list[Measurement]:
607
+ raw = record.get("measurements")
608
+ if type(raw) is not list:
609
+ raise _record_error(location[0], location[1], "measurements must be an array")
610
+ parsed: list[Measurement] = []
611
+ for value in raw:
612
+ item = _record_mapping(value, *location)
613
+ measurement: Measurement = {
614
+ "name": _record_string(item, "name", location),
615
+ "value": _record_string(item, "value", location),
616
+ }
617
+ for field in ("unit", "context"):
618
+ if field in item:
619
+ measurement[field] = _record_string(item, field, location, allow_empty=True)
620
+ parsed.append(measurement)
621
+ return parsed
622
+
623
+
624
+ def _source_refs(record: dict[str, JsonValue], location: tuple[Path, int]) -> list[SourceRef]:
625
+ raw = record.get("source_refs")
626
+ if type(raw) is not list or not raw:
627
+ raise _record_error(location[0], location[1], "source_refs must be a non-empty array")
628
+ parsed: list[SourceRef] = []
629
+ for value in raw:
630
+ item = _record_mapping(value, *location)
631
+ source_ref: SourceRef = {"path": _record_string(item, "path", location)}
632
+ for field in ("heading", "key_path"):
633
+ if field in item:
634
+ source_ref[field] = _record_string(item, field, location)
635
+ parsed.append(source_ref)
636
+ return parsed
637
+
638
+
639
+ def _evidence_refs(record: dict[str, JsonValue], location: tuple[Path, int]) -> list[EvidenceRef]:
640
+ raw = record.get("evidence_refs")
641
+ if type(raw) is not list:
642
+ raise _record_error(location[0], location[1], "evidence_refs must be an array")
643
+ parsed: list[EvidenceRef] = []
644
+ for value in raw:
645
+ item = _record_mapping(value, *location)
646
+ evidence_ref: EvidenceRef = {
647
+ "kind": _record_string(item, "kind", location),
648
+ "ref": _record_string(item, "ref", location),
649
+ }
650
+ if "note" in item:
651
+ evidence_ref["note"] = _record_string(item, "note", location, allow_empty=True)
652
+ parsed.append(evidence_ref)
653
+ return parsed
654
+
655
+
656
+ def _parse_record(value: JsonValue, path: Path, line_number: int) -> SpecRecord:
657
+ raw = _record_mapping(value, path, line_number)
658
+ location = (path, line_number)
659
+ status = _record_string(raw, "observation_status", location)
660
+ if status not in {"observed", "inferred", "unverified"}:
661
+ raise _record_error(path, line_number, "observation_status is invalid")
662
+ confidence = raw.get("confidence")
663
+ if type(confidence) is bool or not isinstance(confidence, (int, float)) or not 0 <= confidence <= 1:
664
+ raise _record_error(path, line_number, "confidence must be a number from 0 through 1")
665
+ return {
666
+ "record_id": _record_string(raw, "record_id", location),
667
+ "collection": _record_string(raw, "collection", location),
668
+ "domain": _record_string(raw, "domain", location),
669
+ "kind": _record_string(raw, "kind", location),
670
+ "entity": _record_string(raw, "entity", location),
671
+ "title": _record_string(raw, "title", location),
672
+ "aliases": _record_string_list(raw, "aliases", location),
673
+ "content": _record_string(raw, "content", location, allow_empty=True),
674
+ "constraints": _record_string_list(raw, "constraints", location),
675
+ "measurements": _measurements(raw, location),
676
+ "source_refs": _source_refs(raw, location),
677
+ "evidence_refs": _evidence_refs(raw, location),
678
+ "observation_status": status,
679
+ "confidence": float(confidence),
680
+ "assumptions": _record_string_list(raw, "assumptions", location),
681
+ }
682
+
683
+
684
+ def load_jsonl_records(path: Path) -> list[SpecRecord]:
685
+ try:
686
+ lines = path.read_text(encoding="utf-8").splitlines()
687
+ except (OSError, UnicodeError) as error:
688
+ raise _record_error(path, 0, "unable to read UTF-8 JSONL") from error
689
+ records: list[SpecRecord] = []
690
+ for line_number, line in enumerate(lines, start=1):
691
+ if not line.strip():
692
+ continue
693
+ try:
694
+ value: JsonValue = json.loads(line)
695
+ except json.JSONDecodeError as error:
696
+ raise _record_error(path, line_number, "invalid JSON object") from error
697
+ records.append(_parse_record(value, path, line_number))
698
+ return records
699
+
700
+
701
+ def _primary_tokens(text: str, tokenizer: TokenizerConfig) -> list[str]:
702
+ normalized = unicodedata.normalize(tokenizer.unicode_normalization, text)
703
+ if tokenizer.casefold:
704
+ normalized = normalized.casefold()
705
+ pattern = _IDENTIFIER_TOKEN_PATTERN if tokenizer.preserve_identifiers else _WORD_TOKEN_PATTERN
706
+ tokens = [
707
+ match.group(0).translate(_DASH_TRANSLATION)
708
+ for match in pattern.finditer(normalized)
709
+ ]
710
+ if tokenizer.preserve_numbers:
711
+ return tokens
712
+ return [token for token in tokens if any(character.isalpha() for character in token)]
713
+
714
+
715
+ def _accent_companion(token: str) -> str | None:
716
+ if not any(character.casefold() in _VIETNAMESE_MARKED for character in token):
717
+ return None
718
+ decomposed = unicodedata.normalize("NFD", token)
719
+ folded = "".join(character for character in decomposed if unicodedata.category(character) != "Mn")
720
+ folded = folded.replace("đ", "d").replace("Đ", "D")
721
+ return folded if folded != token else None
722
+
723
+
724
+ def _with_accent_companions(
725
+ tokens: Sequence[str],
726
+ accent_fold: AccentFold,
727
+ ) -> list[str]:
728
+ if accent_fold == "none":
729
+ return list(tokens)
730
+ expanded: list[str] = []
731
+ for token in tokens:
732
+ expanded.append(token)
733
+ companion = _accent_companion(token)
734
+ if companion is not None:
735
+ expanded.append(companion)
736
+ return expanded
737
+
738
+
739
+ def tokenize(
740
+ text: str,
741
+ aliases: Mapping[str, Sequence[str]] | None = None,
742
+ tokenizer: TokenizerConfig = _DEFAULT_TOKENIZER_CONFIG,
743
+ ) -> list[str]:
744
+ primary = _primary_tokens(text, tokenizer)
745
+ tokens = _with_accent_companions(primary, tokenizer.accent_fold)
746
+ if aliases is None:
747
+ return tokens
748
+ normalized_aliases = sorted(
749
+ (
750
+ (_primary_tokens(term, tokenizer), tuple(values))
751
+ for term, values in aliases.items()
752
+ ),
753
+ key=lambda item: item[0],
754
+ )
755
+ for alias_tokens, expansions in normalized_aliases:
756
+ width = len(alias_tokens)
757
+ if width == 0 or not any(primary[index : index + width] == alias_tokens for index in range(len(primary) - width + 1)):
758
+ continue
759
+ for expansion in sorted(
760
+ expansions,
761
+ key=lambda value: unicodedata.normalize(
762
+ tokenizer.unicode_normalization,
763
+ value,
764
+ ).casefold(),
765
+ ):
766
+ tokens.extend(
767
+ _with_accent_companions(
768
+ _primary_tokens(expansion, tokenizer),
769
+ tokenizer.accent_fold,
770
+ )
771
+ )
772
+ return tokens
773
+
774
+
775
+ def _read_source(path: Path) -> str:
776
+ try:
777
+ return path.read_text(encoding="utf-8")
778
+ except (OSError, UnicodeError) as error:
779
+ raise SourceIngestionError(path=path, reason="unable to read UTF-8 source") from error
780
+
781
+
782
+ def _source_reference(file_path: str, heading: str | None, key_path: str | None) -> tuple[SourceReference, ...]:
783
+ return (SourceReference(path=file_path, heading=heading, key_path=key_path),)
784
+
785
+
786
+ def ingest_markdown(path: Path, source_path: str, collection: str) -> list[SourceDocument]:
787
+ documents: list[SourceDocument] = []
788
+ heading: str | None = None
789
+ body: list[str] = []
790
+ section_number = 0
791
+
792
+ def append_section() -> None:
793
+ nonlocal section_number
794
+ content = "\n".join(body).strip()
795
+ if heading is None and not content:
796
+ return
797
+ section_number += 1
798
+ title = heading if heading is not None else path.stem
799
+ documents.append(
800
+ SourceDocument(
801
+ record_id=f"{collection}.markdown.{source_path}#{section_number}",
802
+ collection=collection,
803
+ title=title,
804
+ content=content,
805
+ file_path=source_path,
806
+ heading=heading,
807
+ source_refs=_source_reference(source_path, heading, None),
808
+ )
809
+ )
810
+
811
+ for line in _read_source(path).splitlines():
812
+ match = re.match(r"^#{1,6}\s+(.+?)\s*#*\s*$", line)
813
+ if match is None:
814
+ body.append(line)
815
+ continue
816
+ append_section()
817
+ heading = match.group(1)
818
+ body = []
819
+ append_section()
820
+ return documents
821
+
822
+
823
+ def _json_content(value: JsonScalar) -> str:
824
+ return value if isinstance(value, str) else json.dumps(value, ensure_ascii=False)
825
+
826
+
827
+ def assert_never(value: NoReturn) -> NoReturn:
828
+ raise AssertionError(f"unhandled JSON value: {value!r}")
829
+
830
+
831
+ def ingest_json(path: Path, source_path: str, collection: str) -> list[SourceDocument]:
832
+ try:
833
+ root: JsonValue = json.loads(_read_source(path))
834
+ except json.JSONDecodeError as error:
835
+ raise SourceIngestionError(path=path, reason="invalid JSON source") from error
836
+ documents: list[SourceDocument] = []
837
+
838
+ def visit(value: JsonValue, key_path: str) -> None:
839
+ match value:
840
+ case dict() as mapping:
841
+ for key in sorted(mapping):
842
+ child_path = key if not key_path else f"{key_path}.{key}"
843
+ visit(mapping[key], child_path)
844
+ case list() as values:
845
+ for index, item in enumerate(values):
846
+ visit(item, f"{key_path}[{index}]" if key_path else f"[{index}]")
847
+ case str() | int() | float() | bool() | None as scalar:
848
+ location = key_path or "$"
849
+ documents.append(
850
+ SourceDocument(
851
+ record_id=f"{collection}.json.{source_path}#{location}",
852
+ collection=collection,
853
+ title=location.rsplit(".", maxsplit=1)[-1],
854
+ content=_json_content(scalar),
855
+ file_path=source_path,
856
+ key_path=location,
857
+ source_refs=_source_reference(source_path, None, location),
858
+ )
859
+ )
860
+ case unreachable:
861
+ assert_never(unreachable)
862
+
863
+ visit(root, "")
864
+ return documents
865
+
866
+
867
+ def _ingest_jsonl(path: Path, source_path: str) -> list[SourceDocument]:
868
+ documents: list[SourceDocument] = []
869
+ for record in load_jsonl_records(path):
870
+ references = tuple(
871
+ SourceReference(
872
+ path=source_ref["path"],
873
+ heading=source_ref.get("heading"),
874
+ key_path=source_ref.get("key_path"),
875
+ )
876
+ for source_ref in record["source_refs"]
877
+ )
878
+ evidence_references = tuple(
879
+ EvidenceReference(
880
+ kind=evidence_ref["kind"],
881
+ ref=evidence_ref["ref"],
882
+ note=evidence_ref.get("note"),
883
+ )
884
+ for evidence_ref in record["evidence_refs"]
885
+ )
886
+ documents.append(
887
+ SourceDocument(
888
+ record_id=record["record_id"],
889
+ collection=record["collection"],
890
+ title=record["title"],
891
+ content=record["content"],
892
+ file_path=source_path,
893
+ aliases=tuple(record["aliases"]),
894
+ source_refs=references,
895
+ evidence_refs=evidence_references,
896
+ )
897
+ )
898
+ return documents
899
+
900
+
901
+ def _source_kind(path: Path) -> SourceKind:
902
+ kind = _SOURCE_KINDS.get(path.suffix.casefold())
903
+ if kind is None:
904
+ raise SourceIngestionError(path=path, reason="unsupported configured source extension")
905
+ return kind
906
+
907
+
908
+ def _source_tree_files(root: Path, *, optional: bool) -> list[Path]:
909
+ try:
910
+ root_mode = root.lstat().st_mode
911
+ except FileNotFoundError as error:
912
+ if optional:
913
+ return []
914
+ raise SourceIngestionError(
915
+ path=root,
916
+ reason="configured source root is not a directory",
917
+ ) from error
918
+ except OSError as error:
919
+ raise SourceIngestionError(
920
+ path=root,
921
+ reason="unable to read configured source root",
922
+ ) from error
923
+ if stat.S_ISLNK(root_mode):
924
+ raise SourceIngestionError(path=root, reason="symbolic links are not allowed")
925
+ if not stat.S_ISDIR(root_mode):
926
+ raise SourceIngestionError(
927
+ path=root,
928
+ reason="configured source root is not a directory",
929
+ )
930
+
931
+ files: list[Path] = []
932
+
933
+ def visit(directory: Path) -> None:
934
+ try:
935
+ children = sorted(
936
+ directory.iterdir(),
937
+ key=lambda candidate: candidate.name,
938
+ )
939
+ except OSError as error:
940
+ raise SourceIngestionError(
941
+ path=directory,
942
+ reason="unable to read configured source root",
943
+ ) from error
944
+ for child in children:
945
+ try:
946
+ child_mode = child.lstat().st_mode
947
+ except OSError as error:
948
+ raise SourceIngestionError(
949
+ path=child,
950
+ reason="unable to inspect configured source",
951
+ ) from error
952
+ if stat.S_ISLNK(child_mode):
953
+ raise SourceIngestionError(
954
+ path=child,
955
+ reason="symbolic links are not allowed",
956
+ )
957
+ relative = child.relative_to(root)
958
+ if _hidden_source(relative):
959
+ continue
960
+ if stat.S_ISDIR(child_mode):
961
+ visit(child)
962
+ elif stat.S_ISREG(child_mode):
963
+ files.append(child)
964
+
965
+ visit(root)
966
+ return files
967
+
968
+
969
+ def ingest_source_tree(
970
+ root: Path,
971
+ collection: str,
972
+ extensions: Sequence[str],
973
+ ) -> list[SourceDocument]:
974
+ allowed = frozenset(extension.casefold() for extension in extensions)
975
+ documents: list[SourceDocument] = []
976
+ for path in _source_tree_files(root, optional=False):
977
+ relative = path.relative_to(root)
978
+ if path.suffix.casefold() not in allowed:
979
+ continue
980
+ source_path = relative.as_posix()
981
+ match _source_kind(path):
982
+ case "markdown":
983
+ documents.extend(ingest_markdown(path, source_path, collection))
984
+ case "json":
985
+ documents.extend(ingest_json(path, source_path, collection))
986
+ case "jsonl":
987
+ documents.extend(_ingest_jsonl(path, source_path))
988
+ case unreachable:
989
+ assert_never(unreachable)
990
+ return documents
991
+
992
+
993
+ def _fingerprint(value: JsonValue | CollectionProfile) -> str:
994
+ canonical = json.dumps(value, ensure_ascii=False, separators=(",", ":"), sort_keys=True)
995
+ return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
996
+
997
+
998
+ def _alias_mapping(config: Bm25Config) -> dict[str, tuple[str, ...]]:
999
+ return {term: expansions for term, expansions in config.term_aliases}
1000
+
1001
+
1002
+ def _searchable_text(document: SourceDocument) -> str:
1003
+ parts = [document.title]
1004
+ if document.heading is not None and document.heading != document.title:
1005
+ parts.append(document.heading)
1006
+ parts.extend(document.aliases)
1007
+ parts.append(document.content)
1008
+ return "\n".join(parts)
1009
+
1010
+
1011
+ def build_index(
1012
+ documents: Sequence[SourceDocument],
1013
+ config: Bm25Config,
1014
+ fingerprints: IndexFingerprints = IndexFingerprints(),
1015
+ ) -> Bm25Index:
1016
+ if config.k1 <= 0:
1017
+ raise IndexBuildError(reason="BM25 k1 must be greater than zero")
1018
+ if not 0 <= config.b <= 1:
1019
+ raise IndexBuildError(reason="BM25 b must be from zero through one")
1020
+
1021
+ aliases = _alias_mapping(config)
1022
+ records: dict[str, SourceDocument] = {}
1023
+ document_lengths: dict[str, int] = {}
1024
+ posting_lists: dict[str, list[Posting]] = {}
1025
+ for document in sorted(documents, key=lambda item: item.record_id):
1026
+ if document.record_id in records:
1027
+ raise IndexBuildError(reason=f"duplicate record_id: {document.record_id}")
1028
+ records[document.record_id] = document
1029
+ term_frequencies = Counter(
1030
+ tokenize(_searchable_text(document), aliases, config.tokenizer)
1031
+ )
1032
+ document_lengths[document.record_id] = sum(term_frequencies.values())
1033
+ for term in sorted(term_frequencies):
1034
+ posting_lists.setdefault(term, []).append(
1035
+ Posting(record_id=document.record_id, term_frequency=term_frequencies[term])
1036
+ )
1037
+
1038
+ document_count = len(records)
1039
+ avgdl = sum(document_lengths.values()) / document_count if document_count else 0.0
1040
+ postings = {term: tuple(values) for term, values in sorted(posting_lists.items())}
1041
+ document_frequencies = {term: len(values) for term, values in postings.items()}
1042
+ return Bm25Index(
1043
+ collection=config.collection,
1044
+ k1=config.k1,
1045
+ b=config.b,
1046
+ tokenizer=config.tokenizer,
1047
+ fingerprints=fingerprints,
1048
+ document_lengths=document_lengths,
1049
+ avgdl=avgdl,
1050
+ document_frequencies=document_frequencies,
1051
+ postings=postings,
1052
+ records=records,
1053
+ term_aliases=aliases,
1054
+ )
1055
+
1056
+
1057
+ def search_index(index: Bm25Index, query: str) -> list[SearchMatch]:
1058
+ if not index.records or index.avgdl == 0:
1059
+ return []
1060
+ query_terms = sorted(set(tokenize(query, index.term_aliases, index.tokenizer)))
1061
+ scores: dict[str, float] = {}
1062
+ document_count = len(index.records)
1063
+ for term in query_terms:
1064
+ term_postings = index.postings.get(term, ())
1065
+ if not term_postings:
1066
+ continue
1067
+ document_frequency = index.document_frequencies[term]
1068
+ inverse_document_frequency = math.log(
1069
+ 1 + (document_count - document_frequency + 0.5) / (document_frequency + 0.5)
1070
+ )
1071
+ for posting in term_postings:
1072
+ document_length = index.document_lengths[posting.record_id]
1073
+ length_normalization = 1 - index.b + index.b * document_length / index.avgdl
1074
+ numerator = posting.term_frequency * (index.k1 + 1)
1075
+ denominator = posting.term_frequency + index.k1 * length_normalization
1076
+ scores[posting.record_id] = scores.get(posting.record_id, 0.0) + (
1077
+ inverse_document_frequency * numerator / denominator
1078
+ )
1079
+ matches = [
1080
+ SearchMatch(record=index.records[record_id], score=score)
1081
+ for record_id, score in scores.items()
1082
+ if score > 0
1083
+ ]
1084
+ return sorted(matches, key=lambda match: (-match.score, match.record.record_id))
1085
+
1086
+
1087
+ def _earliest_token_offset(text: str, query: str) -> int:
1088
+ query_tokens = frozenset(tokenize(query))
1089
+ for token_match in _IDENTIFIER_TOKEN_PATTERN.finditer(text):
1090
+ if query_tokens.intersection(tokenize(token_match.group(0))):
1091
+ return token_match.start()
1092
+ return 0
1093
+
1094
+
1095
+ def _trim_word_boundaries(text: str, start: int, end: int) -> tuple[int, int]:
1096
+ if start > 0:
1097
+ next_space = text.find(" ", start, end)
1098
+ if next_space >= 0:
1099
+ start = next_space + 1
1100
+ if end < len(text):
1101
+ previous_space = text.rfind(" ", start, end)
1102
+ if previous_space > start:
1103
+ end = previous_space
1104
+ return start, end
1105
+
1106
+
1107
+ def section_snippet(text: str, query: str, max_chars: int) -> str:
1108
+ normalized = " ".join(text.split())
1109
+ if len(normalized) <= max_chars:
1110
+ return normalized
1111
+ if max_chars <= 3:
1112
+ return "." * max_chars
1113
+ suffix_capacity = max_chars - 4
1114
+ target = _earliest_token_offset(normalized, query)
1115
+ if target <= suffix_capacity // 2:
1116
+ raw_start, raw_end = 0, suffix_capacity
1117
+ else:
1118
+ body_capacity = max(1, max_chars - 8)
1119
+ raw_start = max(0, target - body_capacity // 2)
1120
+ raw_end = min(len(normalized), raw_start + body_capacity)
1121
+ if raw_end == len(normalized):
1122
+ raw_start = max(0, len(normalized) - suffix_capacity)
1123
+ start, end = _trim_word_boundaries(normalized, raw_start, raw_end)
1124
+ prefix = "... " if start > 0 else ""
1125
+ suffix = " ..." if end < len(normalized) else ""
1126
+ return f"{prefix}{normalized[start:end].strip()}{suffix}"[:max_chars]
1127
+
1128
+
1129
+ def _document_key(document: SourceDocument) -> tuple[str, str | None, str | None]:
1130
+ return document.file_path, document.heading, document.key_path
1131
+
1132
+
1133
+ def _reference_key(reference: SourceReference) -> tuple[str, str | None, str | None]:
1134
+ return reference.path, reference.heading, reference.key_path
1135
+
1136
+
1137
+ def _resolve_source_section(
1138
+ match: SearchMatch,
1139
+ sections: Mapping[tuple[str, str | None, str | None], SourceDocument],
1140
+ ) -> tuple[tuple[str, str | None, str | None], str]:
1141
+ own_key = _document_key(match.record)
1142
+ if match.record.heading is not None or match.record.key_path is not None:
1143
+ return own_key, match.record.content
1144
+ for reference in match.record.source_refs:
1145
+ key = _reference_key(reference)
1146
+ source_document = sections.get(key)
1147
+ if source_document is not None:
1148
+ return key, source_document.content
1149
+ if match.record.source_refs:
1150
+ return _reference_key(match.record.source_refs[0]), match.record.content
1151
+ return own_key, match.record.content
1152
+
1153
+
1154
+ def serialize_search_results(
1155
+ index: Bm25Index,
1156
+ request: SearchOutputRequest,
1157
+ ) -> list[SerializedSearchMatch]:
1158
+ sections = {
1159
+ _document_key(document): document
1160
+ for document in sorted(index.records.values(), key=lambda item: item.record_id)
1161
+ }
1162
+ results: list[SerializedSearchMatch] = []
1163
+ seen: set[tuple[str, str | None, str | None]] = set()
1164
+ for match in search_index(index, request.query):
1165
+ section_key, source_text = _resolve_source_section(match, sections)
1166
+ if section_key in seen:
1167
+ continue
1168
+ seen.add(section_key)
1169
+ file_path, heading, key_path = section_key
1170
+ results.append(
1171
+ {
1172
+ "record_id": match.record.record_id,
1173
+ "file_path": file_path,
1174
+ "heading": heading,
1175
+ "key_path": key_path,
1176
+ "score": round(match.score, 12),
1177
+ "snippets": [section_snippet(source_text, request.query, request.snippet_chars)],
1178
+ "source_refs": [
1179
+ {
1180
+ "path": reference.path,
1181
+ "heading": reference.heading,
1182
+ "key_path": reference.key_path,
1183
+ }
1184
+ for reference in match.record.source_refs
1185
+ ],
1186
+ "evidence_refs": [
1187
+ _cached_evidence_reference(reference)
1188
+ for reference in match.record.evidence_refs
1189
+ ],
1190
+ }
1191
+ )
1192
+ if len(results) == request.limit:
1193
+ break
1194
+ return results
1195
+
1196
+
1197
+ def _hidden_source(relative: Path) -> bool:
1198
+ return any(part.startswith(".") or part == "__pycache__" for part in relative.parts)
1199
+
1200
+
1201
+ def _configured_project_path(
1202
+ request: IndexRequest,
1203
+ configured: str,
1204
+ ) -> Path:
1205
+ relative = Path(configured)
1206
+ if relative.is_absolute() or ".." in relative.parts:
1207
+ raise SourceIngestionError(
1208
+ path=relative,
1209
+ reason="configured source path must be relative and stay within project_root",
1210
+ )
1211
+ candidate = request.project_root / relative
1212
+ current = request.project_root
1213
+ for part in relative.parts:
1214
+ current /= part
1215
+ try:
1216
+ current_mode = current.lstat().st_mode
1217
+ except FileNotFoundError:
1218
+ break
1219
+ except OSError as error:
1220
+ raise SourceIngestionError(
1221
+ path=current,
1222
+ reason="unable to inspect configured source path",
1223
+ ) from error
1224
+ if stat.S_ISLNK(current_mode):
1225
+ raise SourceIngestionError(
1226
+ path=current,
1227
+ reason="symbolic links are not allowed",
1228
+ )
1229
+ return candidate
1230
+
1231
+
1232
+ def _configured_sources(request: IndexRequest) -> list[ConfiguredSource]:
1233
+ allowed = frozenset(extension.casefold() for extension in request.profile["source_extensions"])
1234
+ sources: dict[str, ConfiguredSource] = {}
1235
+ configured_roots = (
1236
+ *((configured_root, False) for configured_root in request.profile["source_roots"]),
1237
+ *(
1238
+ (configured_root, True)
1239
+ for configured_root in request.profile["optional_source_roots"]
1240
+ ),
1241
+ )
1242
+ for configured_root, optional in configured_roots:
1243
+ root = _configured_project_path(request, configured_root)
1244
+ for path in _source_tree_files(root, optional=optional):
1245
+ if path.suffix.casefold() not in allowed:
1246
+ continue
1247
+ source_path = path.relative_to(request.project_root)
1248
+ source_key = source_path.as_posix()
1249
+ sources[source_key] = ConfiguredSource(
1250
+ path=path,
1251
+ source_path=source_key,
1252
+ kind=_source_kind(path),
1253
+ )
1254
+ for configured_record in request.profile["distilled_records"]:
1255
+ path = _configured_project_path(request, configured_record)
1256
+ try:
1257
+ record_mode = path.lstat().st_mode
1258
+ except OSError as error:
1259
+ raise SourceIngestionError(
1260
+ path=path,
1261
+ reason="configured distilled record source is not a file",
1262
+ ) from error
1263
+ if stat.S_ISLNK(record_mode):
1264
+ raise SourceIngestionError(path=path, reason="symbolic links are not allowed")
1265
+ if not stat.S_ISREG(record_mode):
1266
+ raise SourceIngestionError(path=path, reason="configured distilled record source is not a file")
1267
+ source_path = path.relative_to(request.project_root)
1268
+ source_key = source_path.as_posix()
1269
+ sources[source_key] = ConfiguredSource(
1270
+ path=path,
1271
+ source_path=source_key,
1272
+ kind=_source_kind(path),
1273
+ )
1274
+ return [sources[source_key] for source_key in sorted(sources)]
1275
+
1276
+
1277
+ def _source_fingerprint(sources: Sequence[ConfiguredSource]) -> str:
1278
+ digest = hashlib.sha256()
1279
+ for source in sources:
1280
+ digest.update(source.source_path.encode("utf-8"))
1281
+ digest.update(b"\0")
1282
+ try:
1283
+ with source.path.open("rb") as source_file:
1284
+ for chunk in iter(lambda: source_file.read(1024 * 1024), b""):
1285
+ digest.update(chunk)
1286
+ except OSError as error:
1287
+ raise SourceIngestionError(
1288
+ path=source.path,
1289
+ reason="unable to read source for freshness check",
1290
+ ) from error
1291
+ digest.update(b"\0")
1292
+ return digest.hexdigest()
1293
+
1294
+
1295
+ def _index_fingerprints(request: IndexRequest, sources: Sequence[ConfiguredSource]) -> IndexFingerprints:
1296
+ schema_fingerprint = _fingerprint(
1297
+ {
1298
+ "cache_schema_version": _CACHE_SCHEMA_VERSION,
1299
+ "record_metadata_version": 1,
1300
+ }
1301
+ )
1302
+ tokenizer = request.profile["tokenizer"]
1303
+ tokenizer_value: JsonValue = {
1304
+ "implementation_version": _TOKENIZER_SCHEMA_VERSION,
1305
+ "settings": {
1306
+ "version": tokenizer["version"],
1307
+ "unicode_normalization": tokenizer["unicode_normalization"],
1308
+ "casefold": tokenizer["casefold"],
1309
+ "accent_fold": tokenizer["accent_fold"],
1310
+ "preserve_identifiers": tokenizer["preserve_identifiers"],
1311
+ "preserve_numbers": tokenizer["preserve_numbers"],
1312
+ },
1313
+ }
1314
+ tokenizer_fingerprint = _fingerprint(tokenizer_value)
1315
+ config_fingerprint = _fingerprint(request.profile)
1316
+ return IndexFingerprints(
1317
+ schema=schema_fingerprint,
1318
+ tokenizer=tokenizer_fingerprint,
1319
+ config=config_fingerprint,
1320
+ source=_source_fingerprint(sources),
1321
+ )
1322
+
1323
+
1324
+ def _ingest_configured_sources(
1325
+ request: IndexRequest,
1326
+ sources: Sequence[ConfiguredSource],
1327
+ ) -> list[SourceDocument]:
1328
+ documents: list[SourceDocument] = []
1329
+ for source in sources:
1330
+ match source.kind:
1331
+ case "markdown":
1332
+ documents.extend(ingest_markdown(source.path, source.source_path, request.collection))
1333
+ case "json":
1334
+ documents.extend(ingest_json(source.path, source.source_path, request.collection))
1335
+ case "jsonl":
1336
+ documents.extend(_ingest_jsonl(source.path, source.source_path))
1337
+ case unreachable:
1338
+ assert_never(unreachable)
1339
+ return documents
1340
+
1341
+
1342
+ def _cached_source_reference(reference: SourceReference) -> CachedSourceReference:
1343
+ return {
1344
+ "path": reference.path,
1345
+ "heading": reference.heading,
1346
+ "key_path": reference.key_path,
1347
+ }
1348
+
1349
+
1350
+ def _cached_evidence_reference(
1351
+ reference: EvidenceReference,
1352
+ ) -> CachedEvidenceReference:
1353
+ cached: CachedEvidenceReference = {
1354
+ "kind": reference.kind,
1355
+ "ref": reference.ref,
1356
+ }
1357
+ if reference.note is not None:
1358
+ cached["note"] = reference.note
1359
+ return cached
1360
+
1361
+
1362
+ def _tokenizer_config(settings: TokenizerSettings) -> TokenizerConfig:
1363
+ return TokenizerConfig(
1364
+ version=settings["version"],
1365
+ unicode_normalization=settings["unicode_normalization"],
1366
+ casefold=settings["casefold"],
1367
+ accent_fold=settings["accent_fold"],
1368
+ preserve_identifiers=settings["preserve_identifiers"],
1369
+ preserve_numbers=settings["preserve_numbers"],
1370
+ )
1371
+
1372
+
1373
+ def _tokenizer_settings(config: TokenizerConfig) -> TokenizerSettings:
1374
+ return {
1375
+ "version": config.version,
1376
+ "unicode_normalization": config.unicode_normalization,
1377
+ "casefold": config.casefold,
1378
+ "accent_fold": config.accent_fold,
1379
+ "preserve_identifiers": config.preserve_identifiers,
1380
+ "preserve_numbers": config.preserve_numbers,
1381
+ }
1382
+
1383
+
1384
+ def _cached_record(document: SourceDocument) -> CachedRecord:
1385
+ return {
1386
+ "record_id": document.record_id,
1387
+ "collection": document.collection,
1388
+ "title": document.title,
1389
+ "content": document.content,
1390
+ "file_path": document.file_path,
1391
+ "heading": document.heading,
1392
+ "key_path": document.key_path,
1393
+ "aliases": list(document.aliases),
1394
+ "source_refs": [_cached_source_reference(reference) for reference in document.source_refs],
1395
+ "evidence_refs": [
1396
+ _cached_evidence_reference(reference)
1397
+ for reference in document.evidence_refs
1398
+ ],
1399
+ }
1400
+
1401
+
1402
+ def _cache_payload(index: Bm25Index) -> CachePayload:
1403
+ return {
1404
+ "schema_version": _CACHE_SCHEMA_VERSION,
1405
+ "schema_fingerprint": index.fingerprints.schema,
1406
+ "tokenizer_fingerprint": index.fingerprints.tokenizer,
1407
+ "config_fingerprint": index.fingerprints.config,
1408
+ "source_fingerprint": index.fingerprints.source,
1409
+ "fingerprint": index.fingerprint,
1410
+ "collection": index.collection,
1411
+ "k1": index.k1,
1412
+ "b": index.b,
1413
+ "tokenizer": _tokenizer_settings(index.tokenizer),
1414
+ "document_lengths": dict(index.document_lengths),
1415
+ "avgdl": index.avgdl,
1416
+ "document_frequencies": dict(index.document_frequencies),
1417
+ "postings": {
1418
+ term: [
1419
+ {"record_id": posting.record_id, "term_frequency": posting.term_frequency}
1420
+ for posting in postings
1421
+ ]
1422
+ for term, postings in index.postings.items()
1423
+ },
1424
+ "records": {
1425
+ record_id: _cached_record(document)
1426
+ for record_id, document in index.records.items()
1427
+ },
1428
+ "term_aliases": {
1429
+ term: list(expansions)
1430
+ for term, expansions in index.term_aliases.items()
1431
+ },
1432
+ }
1433
+
1434
+
1435
+ def _cache_validation_error(path: Path, reason: str) -> CacheValidationError:
1436
+ return CacheValidationError(path=path, reason=reason)
1437
+
1438
+
1439
+ def _cache_mapping(value: JsonValue, path: Path, label: str) -> dict[str, JsonValue]:
1440
+ if type(value) is not dict:
1441
+ raise _cache_validation_error(path, f"{label} must be an object")
1442
+ return value
1443
+
1444
+
1445
+ def _cache_string(mapping: dict[str, JsonValue], field: str, path: Path) -> str:
1446
+ value = mapping.get(field)
1447
+ if type(value) is not str:
1448
+ raise _cache_validation_error(path, f"{field} must be a string")
1449
+ return value
1450
+
1451
+
1452
+ def _cache_optional_string(mapping: dict[str, JsonValue], field: str, path: Path) -> str | None:
1453
+ value = mapping.get(field)
1454
+ if value is not None and type(value) is not str:
1455
+ raise _cache_validation_error(path, f"{field} must be a string or null")
1456
+ return value
1457
+
1458
+
1459
+ def _cache_float(mapping: dict[str, JsonValue], field: str, path: Path) -> float:
1460
+ value = mapping.get(field)
1461
+ if type(value) is bool or not isinstance(value, (int, float)):
1462
+ raise _cache_validation_error(path, f"{field} must be a number")
1463
+ return float(value)
1464
+
1465
+
1466
+ def _cache_integer(mapping: dict[str, JsonValue], field: str, path: Path) -> int:
1467
+ value = mapping.get(field)
1468
+ if type(value) is not int:
1469
+ raise _cache_validation_error(path, f"{field} must be an integer")
1470
+ return value
1471
+
1472
+
1473
+ def _cache_bool(mapping: dict[str, JsonValue], field: str, path: Path) -> bool:
1474
+ value = mapping.get(field)
1475
+ if type(value) is not bool:
1476
+ raise _cache_validation_error(path, f"{field} must be a boolean")
1477
+ return value
1478
+
1479
+
1480
+ def _cache_string_list(value: JsonValue, path: Path, label: str) -> list[str]:
1481
+ if type(value) is not list or not all(type(item) is str for item in value):
1482
+ raise _cache_validation_error(path, f"{label} must be an array of strings")
1483
+ parsed: list[str] = []
1484
+ for item in value:
1485
+ if type(item) is str:
1486
+ parsed.append(item)
1487
+ return parsed
1488
+
1489
+
1490
+ def _parse_cached_reference(value: JsonValue, path: Path) -> SourceReference:
1491
+ raw = _cache_mapping(value, path, "source reference")
1492
+ return SourceReference(
1493
+ path=_cache_string(raw, "path", path),
1494
+ heading=_cache_optional_string(raw, "heading", path),
1495
+ key_path=_cache_optional_string(raw, "key_path", path),
1496
+ )
1497
+
1498
+
1499
+ def _parse_cached_evidence_reference(
1500
+ value: JsonValue,
1501
+ path: Path,
1502
+ ) -> EvidenceReference:
1503
+ raw = _cache_mapping(value, path, "evidence reference")
1504
+ return EvidenceReference(
1505
+ kind=_cache_string(raw, "kind", path),
1506
+ ref=_cache_string(raw, "ref", path),
1507
+ note=_cache_optional_string(raw, "note", path),
1508
+ )
1509
+
1510
+
1511
+ def _parse_cached_record(record_id: str, value: JsonValue, path: Path) -> SourceDocument:
1512
+ raw = _cache_mapping(value, path, f"records.{record_id}")
1513
+ cached_record_id = _cache_string(raw, "record_id", path)
1514
+ if cached_record_id != record_id:
1515
+ raise _cache_validation_error(path, f"records.{record_id}.record_id does not match its key")
1516
+ references_raw = raw.get("source_refs")
1517
+ if type(references_raw) is not list:
1518
+ raise _cache_validation_error(path, f"records.{record_id}.source_refs must be an array")
1519
+ evidence_references_raw = raw.get("evidence_refs")
1520
+ if type(evidence_references_raw) is not list:
1521
+ raise _cache_validation_error(path, f"records.{record_id}.evidence_refs must be an array")
1522
+ return SourceDocument(
1523
+ record_id=record_id,
1524
+ collection=_cache_string(raw, "collection", path),
1525
+ title=_cache_string(raw, "title", path),
1526
+ content=_cache_string(raw, "content", path),
1527
+ file_path=_cache_string(raw, "file_path", path),
1528
+ heading=_cache_optional_string(raw, "heading", path),
1529
+ key_path=_cache_optional_string(raw, "key_path", path),
1530
+ aliases=tuple(_cache_string_list(raw.get("aliases"), path, f"records.{record_id}.aliases")),
1531
+ source_refs=tuple(_parse_cached_reference(reference, path) for reference in references_raw),
1532
+ evidence_refs=tuple(
1533
+ _parse_cached_evidence_reference(reference, path)
1534
+ for reference in evidence_references_raw
1535
+ ),
1536
+ )
1537
+
1538
+
1539
+ def _parse_integer_mapping(value: JsonValue, path: Path, label: str) -> dict[str, int]:
1540
+ raw = _cache_mapping(value, path, label)
1541
+ parsed: dict[str, int] = {}
1542
+ for key, item in raw.items():
1543
+ if type(item) is not int or item < 0:
1544
+ raise _cache_validation_error(path, f"{label}.{key} must be a non-negative integer")
1545
+ parsed[key] = item
1546
+ return parsed
1547
+
1548
+
1549
+ def _parse_postings(
1550
+ value: JsonValue,
1551
+ path: Path,
1552
+ records: Mapping[str, SourceDocument],
1553
+ ) -> dict[str, tuple[Posting, ...]]:
1554
+ raw = _cache_mapping(value, path, "postings")
1555
+ parsed: dict[str, tuple[Posting, ...]] = {}
1556
+ for term, values in raw.items():
1557
+ if type(values) is not list:
1558
+ raise _cache_validation_error(path, f"postings.{term} must be an array")
1559
+ postings: list[Posting] = []
1560
+ previous_record_id: str | None = None
1561
+ for value_item in values:
1562
+ item = _cache_mapping(value_item, path, f"postings.{term} entry")
1563
+ record_id = _cache_string(item, "record_id", path)
1564
+ term_frequency = _cache_integer(item, "term_frequency", path)
1565
+ if record_id not in records or term_frequency <= 0:
1566
+ raise _cache_validation_error(path, f"postings.{term} contains an invalid entry")
1567
+ if previous_record_id is not None and record_id <= previous_record_id:
1568
+ raise _cache_validation_error(path, f"postings.{term} is not record_id sorted")
1569
+ previous_record_id = record_id
1570
+ postings.append(Posting(record_id=record_id, term_frequency=term_frequency))
1571
+ parsed[term] = tuple(postings)
1572
+ return parsed
1573
+
1574
+
1575
+ def _parse_term_aliases(value: JsonValue, path: Path) -> dict[str, tuple[str, ...]]:
1576
+ raw = _cache_mapping(value, path, "term_aliases")
1577
+ return {
1578
+ term: tuple(_cache_string_list(expansions, path, f"term_aliases.{term}"))
1579
+ for term, expansions in raw.items()
1580
+ }
1581
+
1582
+
1583
+ def _parse_cached_tokenizer(value: JsonValue, path: Path) -> TokenizerConfig:
1584
+ raw = _cache_mapping(value, path, "tokenizer")
1585
+ normalization = _NORMALIZATION_BY_NAME.get(
1586
+ _cache_string(raw, "unicode_normalization", path)
1587
+ )
1588
+ if normalization is None:
1589
+ raise _cache_validation_error(
1590
+ path,
1591
+ "tokenizer.unicode_normalization is invalid",
1592
+ )
1593
+ accent_fold = _ACCENT_FOLD_BY_NAME.get(
1594
+ _cache_string(raw, "accent_fold", path)
1595
+ )
1596
+ if accent_fold is None:
1597
+ raise _cache_validation_error(path, "tokenizer.accent_fold is invalid")
1598
+ return TokenizerConfig(
1599
+ version=_cache_string(raw, "version", path),
1600
+ unicode_normalization=normalization,
1601
+ casefold=_cache_bool(raw, "casefold", path),
1602
+ accent_fold=accent_fold,
1603
+ preserve_identifiers=_cache_bool(raw, "preserve_identifiers", path),
1604
+ preserve_numbers=_cache_bool(raw, "preserve_numbers", path),
1605
+ )
1606
+
1607
+
1608
+ def _parse_cache(value: JsonValue, path: Path) -> Bm25Index:
1609
+ raw = _cache_mapping(value, path, "cache")
1610
+ records_raw = _cache_mapping(raw.get("records"), path, "records")
1611
+ records = {
1612
+ record_id: _parse_cached_record(record_id, record, path)
1613
+ for record_id, record in sorted(records_raw.items())
1614
+ }
1615
+ document_lengths = _parse_integer_mapping(raw.get("document_lengths"), path, "document_lengths")
1616
+ document_frequencies = _parse_integer_mapping(
1617
+ raw.get("document_frequencies"),
1618
+ path,
1619
+ "document_frequencies",
1620
+ )
1621
+ postings = _parse_postings(raw.get("postings"), path, records)
1622
+ if set(document_lengths) != set(records):
1623
+ raise _cache_validation_error(path, "document_lengths keys must match records")
1624
+ if {
1625
+ term: len(term_postings)
1626
+ for term, term_postings in postings.items()
1627
+ } != document_frequencies:
1628
+ raise _cache_validation_error(path, "document_frequencies must match postings")
1629
+ avgdl = _cache_float(raw, "avgdl", path)
1630
+ expected_avgdl = sum(document_lengths.values()) / len(records) if records else 0.0
1631
+ if not math.isclose(avgdl, expected_avgdl, rel_tol=0.0, abs_tol=1e-12):
1632
+ raise _cache_validation_error(path, "avgdl must match document_lengths")
1633
+ schema_version = _cache_integer(raw, "schema_version", path)
1634
+ if schema_version < 1:
1635
+ raise _cache_validation_error(path, "schema_version must be positive")
1636
+ fingerprints = IndexFingerprints(
1637
+ schema=_cache_string(raw, "schema_fingerprint", path),
1638
+ tokenizer=_cache_string(raw, "tokenizer_fingerprint", path),
1639
+ config=_cache_string(raw, "config_fingerprint", path),
1640
+ source=_cache_string(raw, "source_fingerprint", path),
1641
+ )
1642
+ if _cache_string(raw, "fingerprint", path) != fingerprints.combined:
1643
+ raise _cache_validation_error(path, "fingerprint does not match component fingerprints")
1644
+ return Bm25Index(
1645
+ collection=_cache_string(raw, "collection", path),
1646
+ k1=_cache_float(raw, "k1", path),
1647
+ b=_cache_float(raw, "b", path),
1648
+ tokenizer=_parse_cached_tokenizer(raw.get("tokenizer"), path),
1649
+ fingerprints=fingerprints,
1650
+ document_lengths=document_lengths,
1651
+ avgdl=avgdl,
1652
+ document_frequencies=document_frequencies,
1653
+ postings=postings,
1654
+ records=records,
1655
+ term_aliases=_parse_term_aliases(raw.get("term_aliases"), path),
1656
+ )
1657
+
1658
+
1659
+ def _read_cache(path: Path) -> Bm25Index:
1660
+ try:
1661
+ value: JsonValue = json.loads(path.read_text(encoding="utf-8"))
1662
+ except json.JSONDecodeError as error:
1663
+ raise _cache_validation_error(path, "invalid JSON cache") from error
1664
+ except UnicodeError as error:
1665
+ raise _cache_validation_error(path, "cache is not valid UTF-8") from error
1666
+ except OSError as error:
1667
+ raise CacheReadError(path=path, reason="unable to read cache") from error
1668
+ return _parse_cache(value, path)
1669
+
1670
+
1671
+ def _write_cache(path: Path, index: Bm25Index) -> None:
1672
+ try:
1673
+ path.parent.mkdir(parents=True, exist_ok=True)
1674
+ except OSError as error:
1675
+ raise CacheWriteError(path=path, reason="unable to create cache directory") from error
1676
+ temporary_path: Path | None = None
1677
+ try:
1678
+ with tempfile.NamedTemporaryFile(
1679
+ mode="w",
1680
+ encoding="utf-8",
1681
+ dir=path.parent,
1682
+ prefix=f".{path.name}.",
1683
+ suffix=".tmp",
1684
+ delete=False,
1685
+ ) as temporary_file:
1686
+ temporary_path = Path(temporary_file.name)
1687
+ json.dump(
1688
+ _cache_payload(index),
1689
+ temporary_file,
1690
+ ensure_ascii=False,
1691
+ separators=(",", ":"),
1692
+ sort_keys=True,
1693
+ )
1694
+ temporary_file.write("\n")
1695
+ temporary_file.flush()
1696
+ os.fsync(temporary_file.fileno())
1697
+ os.replace(temporary_path, path)
1698
+ temporary_path = None
1699
+ except OSError as error:
1700
+ if temporary_path is not None:
1701
+ try:
1702
+ temporary_path.unlink(missing_ok=True)
1703
+ except OSError as cleanup_error:
1704
+ raise CacheWriteError(
1705
+ path=path,
1706
+ reason=f"atomic cache replacement failed; temporary cleanup failed: {cleanup_error}",
1707
+ ) from error
1708
+ raise CacheWriteError(path=path, reason="atomic cache replacement failed") from error
1709
+
1710
+
1711
+ def _index_config(request: IndexRequest) -> Bm25Config:
1712
+ alias_settings = request.profile["aliases"]
1713
+ max_expansions = alias_settings["max_expansions"]
1714
+ term_aliases = request.profile["term_aliases"] if alias_settings["enabled"] else {}
1715
+ return Bm25Config(
1716
+ collection=request.collection,
1717
+ k1=request.profile["bm25"]["k1"],
1718
+ b=request.profile["bm25"]["b"],
1719
+ tokenizer=_tokenizer_config(request.profile["tokenizer"]),
1720
+ term_aliases=tuple(
1721
+ (term, tuple(expansions[:max_expansions]))
1722
+ for term, expansions in sorted(term_aliases.items())
1723
+ if max_expansions > 0
1724
+ ),
1725
+ )
1726
+
1727
+
1728
+ def _cache_path(request: IndexRequest) -> Path:
1729
+ configured = Path(request.profile["cache"])
1730
+ if configured.is_absolute() or ".." in configured.parts:
1731
+ raise _cache_validation_error(
1732
+ configured,
1733
+ "cache path must be relative and stay within project_root",
1734
+ )
1735
+ try:
1736
+ project_root = request.project_root.resolve()
1737
+ cache_path = (request.project_root / configured).resolve()
1738
+ cache_path.relative_to(project_root)
1739
+ except (OSError, RuntimeError, ValueError) as error:
1740
+ raise _cache_validation_error(
1741
+ configured,
1742
+ "cache path must be relative and stay within project_root",
1743
+ ) from error
1744
+ if cache_path == project_root:
1745
+ raise _cache_validation_error(
1746
+ configured,
1747
+ "cache path must be relative and stay within project_root",
1748
+ )
1749
+ return cache_path
1750
+
1751
+
1752
+ def load_or_build_index(request: IndexRequest) -> IndexLoadResult:
1753
+ cache_path = _cache_path(request)
1754
+ sources = _configured_sources(request)
1755
+ fingerprints = _index_fingerprints(request, sources)
1756
+ config = _index_config(request)
1757
+ reason: CacheReason
1758
+ if request.force_reindex:
1759
+ reason = "forced"
1760
+ elif not cache_path.is_file():
1761
+ reason = "missing"
1762
+ else:
1763
+ try:
1764
+ cached = _read_cache(cache_path)
1765
+ except CacheValidationError:
1766
+ reason = "corrupt"
1767
+ else:
1768
+ if (
1769
+ cached.collection == request.collection
1770
+ and cached.fingerprints == fingerprints
1771
+ and cached.k1 == config.k1
1772
+ and cached.b == config.b
1773
+ and cached.tokenizer == config.tokenizer
1774
+ and cached.term_aliases == _alias_mapping(config)
1775
+ ):
1776
+ return IndexLoadResult(
1777
+ index=cached,
1778
+ status="hit",
1779
+ reason="current",
1780
+ cache_path=cache_path,
1781
+ )
1782
+ reason = "stale"
1783
+
1784
+ documents = _ingest_configured_sources(request, sources)
1785
+ index = build_index(documents, config, fingerprints)
1786
+ _write_cache(cache_path, index)
1787
+ return IndexLoadResult(
1788
+ index=index,
1789
+ status="rebuilt",
1790
+ reason=reason,
1791
+ cache_path=cache_path,
1792
+ )