cosmos-platform 1.6.0.dev1__py3-none-any.whl

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 (541) hide show
  1. cosmos_platform-1.6.0.dev1.dist-info/METADATA +150 -0
  2. cosmos_platform-1.6.0.dev1.dist-info/RECORD +541 -0
  3. cosmos_platform-1.6.0.dev1.dist-info/WHEEL +5 -0
  4. cosmos_platform-1.6.0.dev1.dist-info/entry_points.txt +2 -0
  5. cosmos_platform-1.6.0.dev1.dist-info/licenses/LICENSE +202 -0
  6. cosmos_platform-1.6.0.dev1.dist-info/top_level.txt +2 -0
  7. runtime/__init__.py +1 -0
  8. runtime/candidate/__init__.py +8 -0
  9. runtime/candidate/admission_gate.py +1776 -0
  10. runtime/certification/test_certify_opencode_identity.py +71 -0
  11. runtime/certification/test_certify_w304_windows_silence.py +888 -0
  12. runtime/certification/test_cosmos15_empirical.py +60 -0
  13. runtime/certification/test_cosmos_control_center.py +490 -0
  14. runtime/certification/test_cosmos_dogfood.py +143 -0
  15. runtime/certification/test_enforcement_census_lc16.py +1112 -0
  16. runtime/certification/test_eol_byte_stability_p001.py +394 -0
  17. runtime/certification/test_lc113_adapter_terminal_proofs.py +414 -0
  18. runtime/certification/test_live_certification_k3.py +622 -0
  19. runtime/certification/test_mcp_live_c4b.py +1210 -0
  20. runtime/certification/test_phase9_closeout.py +19 -0
  21. runtime/certification/test_preservation_census_lc17.py +1039 -0
  22. runtime/certification/test_self_hosting_cold_reconstruction.py +158 -0
  23. runtime/certification/test_self_hosting_conformance.py +18 -0
  24. runtime/certification/test_self_hosting_continuity.py +50 -0
  25. runtime/certification/test_self_hosting_environment.py +329 -0
  26. runtime/certification/test_self_hosting_learning.py +56 -0
  27. runtime/certification/test_self_hosting_two_generation.py +21 -0
  28. runtime/certification/test_truth_drift_lc18.py +557 -0
  29. runtime/certification/test_universal_binding_c3.py +770 -0
  30. runtime/certification/test_w101_attempt2.py +698 -0
  31. runtime/certification/test_w101_preservation.py +425 -0
  32. runtime/certification/test_w304_option_a_startup_liveness.py +1093 -0
  33. runtime/certification/test_w304_wedge_log_flood.py +468 -0
  34. runtime/certification/test_w304_wedge_recovery.py +258 -0
  35. runtime/cosmos_runtime/__init__.py +169 -0
  36. runtime/cosmos_runtime/__main__.py +3 -0
  37. runtime/cosmos_runtime/actors.py +363 -0
  38. runtime/cosmos_runtime/adaptive_reasoning.py +242 -0
  39. runtime/cosmos_runtime/authorization.py +567 -0
  40. runtime/cosmos_runtime/cli.py +61 -0
  41. runtime/cosmos_runtime/config.py +21 -0
  42. runtime/cosmos_runtime/context.py +347 -0
  43. runtime/cosmos_runtime/continuation.py +548 -0
  44. runtime/cosmos_runtime/continuity/__init__.py +16 -0
  45. runtime/cosmos_runtime/continuity/handoff.py +208 -0
  46. runtime/cosmos_runtime/controller.py +218 -0
  47. runtime/cosmos_runtime/effects.py +546 -0
  48. runtime/cosmos_runtime/execution.py +725 -0
  49. runtime/cosmos_runtime/execution_shim.py +428 -0
  50. runtime/cosmos_runtime/governance/__init__.py +60 -0
  51. runtime/cosmos_runtime/governance/completion.py +434 -0
  52. runtime/cosmos_runtime/governance/gates.py +952 -0
  53. runtime/cosmos_runtime/governance/scope_types.py +150 -0
  54. runtime/cosmos_runtime/ids.py +25 -0
  55. runtime/cosmos_runtime/intake.py +170 -0
  56. runtime/cosmos_runtime/learning.py +294 -0
  57. runtime/cosmos_runtime/model.py +240 -0
  58. runtime/cosmos_runtime/resilience.py +298 -0
  59. runtime/cosmos_runtime/security/__init__.py +72 -0
  60. runtime/cosmos_runtime/security/audit.py +139 -0
  61. runtime/cosmos_runtime/security/consent.py +153 -0
  62. runtime/cosmos_runtime/security/encryption.py +158 -0
  63. runtime/cosmos_runtime/security/enterprise_fence.py +169 -0
  64. runtime/cosmos_runtime/security/injection_detector.py +123 -0
  65. runtime/cosmos_runtime/security/microphone.py +145 -0
  66. runtime/cosmos_runtime/security/retention.py +168 -0
  67. runtime/cosmos_runtime/security/tenant.py +108 -0
  68. runtime/cosmos_runtime/services.py +187 -0
  69. runtime/cosmos_runtime/store.py +802 -0
  70. runtime/cosmos_runtime/telemetry/__init__.py +42 -0
  71. runtime/cosmos_runtime/telemetry/bus.py +198 -0
  72. runtime/cosmos_runtime/telemetry/events.py +187 -0
  73. runtime/cosmos_runtime/telemetry/scrubber.py +119 -0
  74. runtime/tests/__init__.py +11 -0
  75. runtime/tests/_pollution_guard.py +311 -0
  76. runtime/tests/_retrieval_fixtures.py +102 -0
  77. runtime/tests/_world_isolation.py +138 -0
  78. runtime/tests/conftest.py +56 -0
  79. runtime/tests/gate_local_support.py +234 -0
  80. runtime/tests/test_aaa_pollution_guard.py +218 -0
  81. runtime/tests/test_actor_routing.py +187 -0
  82. runtime/tests/test_adapter_family_agent_frameworks_activation.py +883 -0
  83. runtime/tests/test_adapter_family_cloud_coding_activation.py +1090 -0
  84. runtime/tests/test_adapter_family_core_cli_activation.py +2039 -0
  85. runtime/tests/test_adapter_family_emacs_activation.py +769 -0
  86. runtime/tests/test_adapter_family_ide_rules_activation.py +1016 -0
  87. runtime/tests/test_adapter_family_jetbrains_eclipse_activation.py +990 -0
  88. runtime/tests/test_adapter_family_neovim_activation.py +830 -0
  89. runtime/tests/test_adaptive_reasoning.py +115 -0
  90. runtime/tests/test_ar4_self_hosting_decoupling.py +49 -0
  91. runtime/tests/test_assurance_spine_c2.py +411 -0
  92. runtime/tests/test_authorization_gateway.py +203 -0
  93. runtime/tests/test_capability_reconciliation_lc14.py +257 -0
  94. runtime/tests/test_carrier_flow_k3.py +326 -0
  95. runtime/tests/test_cert_invalidation_k4.py +764 -0
  96. runtime/tests/test_certification_adversarial_v1.py +882 -0
  97. runtime/tests/test_claims_matrix_lc15.py +551 -0
  98. runtime/tests/test_completion.py +306 -0
  99. runtime/tests/test_context_binding.py +160 -0
  100. runtime/tests/test_continuation.py +269 -0
  101. runtime/tests/test_cosmos15_baseline.py +31 -0
  102. runtime/tests/test_cosmos15_claude_door.py +108 -0
  103. runtime/tests/test_cosmos15_developer_world.py +194 -0
  104. runtime/tests/test_cosmos15_observatory.py +286 -0
  105. runtime/tests/test_cosmos15_operator.py +329 -0
  106. runtime/tests/test_cosmos_admin.py +221 -0
  107. runtime/tests/test_cosmos_agent_directory_boundary.py +32 -0
  108. runtime/tests/test_cosmos_ask.py +119 -0
  109. runtime/tests/test_cosmos_blocker_gate.py +192 -0
  110. runtime/tests/test_cosmos_branch_audit.py +227 -0
  111. runtime/tests/test_cosmos_by_path.py +557 -0
  112. runtime/tests/test_cosmos_capability_health.py +651 -0
  113. runtime/tests/test_cosmos_certification.py +98 -0
  114. runtime/tests/test_cosmos_check_proposal.py +584 -0
  115. runtime/tests/test_cosmos_check_runner.py +578 -0
  116. runtime/tests/test_cosmos_check_runner_shard_s1.py +765 -0
  117. runtime/tests/test_cosmos_cloud_bundle.py +33 -0
  118. runtime/tests/test_cosmos_cold_clone_binding.py +106 -0
  119. runtime/tests/test_cosmos_context_authority.py +276 -0
  120. runtime/tests/test_cosmos_continuation.py +210 -0
  121. runtime/tests/test_cosmos_continuity.py +147 -0
  122. runtime/tests/test_cosmos_continuity_demo.py +93 -0
  123. runtime/tests/test_cosmos_continuity_hook.py +453 -0
  124. runtime/tests/test_cosmos_controller.py +125 -0
  125. runtime/tests/test_cosmos_cross_harness_handoff.py +93 -0
  126. runtime/tests/test_cosmos_current_task_derivation.py +202 -0
  127. runtime/tests/test_cosmos_decision_guard.py +179 -0
  128. runtime/tests/test_cosmos_decisions.py +161 -0
  129. runtime/tests/test_cosmos_defensibility_qualification.py +135 -0
  130. runtime/tests/test_cosmos_delta.py +512 -0
  131. runtime/tests/test_cosmos_delta_cli.py +196 -0
  132. runtime/tests/test_cosmos_dependency_graph.py +94 -0
  133. runtime/tests/test_cosmos_dependency_graph_scope.py +67 -0
  134. runtime/tests/test_cosmos_deployment_reconciler.py +213 -0
  135. runtime/tests/test_cosmos_doctor_command_shadowing.py +61 -0
  136. runtime/tests/test_cosmos_doorway_validator.py +139 -0
  137. runtime/tests/test_cosmos_enforce.py +222 -0
  138. runtime/tests/test_cosmos_events.py +77 -0
  139. runtime/tests/test_cosmos_evidence.py +122 -0
  140. runtime/tests/test_cosmos_execution_shim.py +254 -0
  141. runtime/tests/test_cosmos_feedback.py +97 -0
  142. runtime/tests/test_cosmos_gate.py +3007 -0
  143. runtime/tests/test_cosmos_gate_backlog.py +218 -0
  144. runtime/tests/test_cosmos_gate_categories.py +240 -0
  145. runtime/tests/test_cosmos_gate_f008.py +386 -0
  146. runtime/tests/test_cosmos_gate_fast.py +3527 -0
  147. runtime/tests/test_cosmos_gate_governance.py +196 -0
  148. runtime/tests/test_cosmos_gate_lessons.py +113 -0
  149. runtime/tests/test_cosmos_gate_load.py +283 -0
  150. runtime/tests/test_cosmos_gate_multi.py +357 -0
  151. runtime/tests/test_cosmos_gate_override.py +114 -0
  152. runtime/tests/test_cosmos_gate_profile.py +271 -0
  153. runtime/tests/test_cosmos_gate_recheck.py +134 -0
  154. runtime/tests/test_cosmos_gate_runtime.py +304 -0
  155. runtime/tests/test_cosmos_gate_selfcheck.py +27 -0
  156. runtime/tests/test_cosmos_gate_skip.py +95 -0
  157. runtime/tests/test_cosmos_git_hooks.py +117 -0
  158. runtime/tests/test_cosmos_guard.py +938 -0
  159. runtime/tests/test_cosmos_harness_doors.py +50 -0
  160. runtime/tests/test_cosmos_hygiene.py +76 -0
  161. runtime/tests/test_cosmos_hypothesis.py +106 -0
  162. runtime/tests/test_cosmos_index_hot_journal.py +108 -0
  163. runtime/tests/test_cosmos_landing_board.py +228 -0
  164. runtime/tests/test_cosmos_learn.py +92 -0
  165. runtime/tests/test_cosmos_levels_of_done.py +67 -0
  166. runtime/tests/test_cosmos_lineage.py +157 -0
  167. runtime/tests/test_cosmos_mcp_binding.py +182 -0
  168. runtime/tests/test_cosmos_mcp_governed_tools.py +185 -0
  169. runtime/tests/test_cosmos_mcp_registration.py +430 -0
  170. runtime/tests/test_cosmos_memory_maintenance.py +81 -0
  171. runtime/tests/test_cosmos_modality_registry.py +52 -0
  172. runtime/tests/test_cosmos_narrative.py +189 -0
  173. runtime/tests/test_cosmos_navigator_product_path.py +56 -0
  174. runtime/tests/test_cosmos_next.py +669 -0
  175. runtime/tests/test_cosmos_no_raw_process_start.py +92 -0
  176. runtime/tests/test_cosmos_objective_convergence.py +86 -0
  177. runtime/tests/test_cosmos_obligation_lc03.py +745 -0
  178. runtime/tests/test_cosmos_obligations.py +302 -0
  179. runtime/tests/test_cosmos_observe.py +100 -0
  180. runtime/tests/test_cosmos_onboarding.py +224 -0
  181. runtime/tests/test_cosmos_override_gate.py +288 -0
  182. runtime/tests/test_cosmos_packaging_billing_gate.py +396 -0
  183. runtime/tests/test_cosmos_pilot.py +165 -0
  184. runtime/tests/test_cosmos_popup_check.py +75 -0
  185. runtime/tests/test_cosmos_proc_owned_tree.py +249 -0
  186. runtime/tests/test_cosmos_project_adapters.py +158 -0
  187. runtime/tests/test_cosmos_push.py +178 -0
  188. runtime/tests/test_cosmos_qualification.py +94 -0
  189. runtime/tests/test_cosmos_remediation.py +67 -0
  190. runtime/tests/test_cosmos_report.py +99 -0
  191. runtime/tests/test_cosmos_retrieval.py +512 -0
  192. runtime/tests/test_cosmos_retrieval_cli_mcp.py +198 -0
  193. runtime/tests/test_cosmos_retrieval_model_fetch.py +40 -0
  194. runtime/tests/test_cosmos_safety.py +528 -0
  195. runtime/tests/test_cosmos_security_package.py +417 -0
  196. runtime/tests/test_cosmos_security_qualification.py +59 -0
  197. runtime/tests/test_cosmos_self_repair.py +504 -0
  198. runtime/tests/test_cosmos_serving.py +153 -0
  199. runtime/tests/test_cosmos_session_lifecycle.py +181 -0
  200. runtime/tests/test_cosmos_session_start.py +493 -0
  201. runtime/tests/test_cosmos_settings_hooks.py +36 -0
  202. runtime/tests/test_cosmos_speed_limits.py +36 -0
  203. runtime/tests/test_cosmos_staging_qualification.py +117 -0
  204. runtime/tests/test_cosmos_stop_guard.py +84 -0
  205. runtime/tests/test_cosmos_studio.py +1102 -0
  206. runtime/tests/test_cosmos_substrate_liveness.py +111 -0
  207. runtime/tests/test_cosmos_supply_chain_gate.py +238 -0
  208. runtime/tests/test_cosmos_synthetic_pilot.py +46 -0
  209. runtime/tests/test_cosmos_telemetry.py +65 -0
  210. runtime/tests/test_cosmos_telemetry_bus.py +157 -0
  211. runtime/tests/test_cosmos_telemetry_scrubber.py +124 -0
  212. runtime/tests/test_cosmos_tracker_render.py +95 -0
  213. runtime/tests/test_cosmos_trigger_records.py +198 -0
  214. runtime/tests/test_cosmos_tripartite_delta.py +154 -0
  215. runtime/tests/test_cosmos_tripartite_events.py +103 -0
  216. runtime/tests/test_cosmos_trust_readiness.py +375 -0
  217. runtime/tests/test_cosmos_vault.py +3524 -0
  218. runtime/tests/test_cosmos_vault_entry_points.py +920 -0
  219. runtime/tests/test_cosmos_vault_worker.py +1450 -0
  220. runtime/tests/test_cosmos_visibility_policy.py +187 -0
  221. runtime/tests/test_cosmos_wake.py +43 -0
  222. runtime/tests/test_cosmos_watchdog.py +1318 -0
  223. runtime/tests/test_cosmos_world_refresh_and_capture.py +711 -0
  224. runtime/tests/test_cosmos_wrong_direction.py +214 -0
  225. runtime/tests/test_cosmos_zero_step.py +245 -0
  226. runtime/tests/test_daemon_supervisor_c5b.py +845 -0
  227. runtime/tests/test_enforcement_live_c4.py +485 -0
  228. runtime/tests/test_execution_loop.py +216 -0
  229. runtime/tests/test_foundation.py +145 -0
  230. runtime/tests/test_governance_gates.py +327 -0
  231. runtime/tests/test_intake.py +107 -0
  232. runtime/tests/test_invalidationscan_k4.py +776 -0
  233. runtime/tests/test_lc112_live_attestation_commission.py +292 -0
  234. runtime/tests/test_lc133_lp2_entry_points.py +268 -0
  235. runtime/tests/test_lc1_baseline_lc19.py +702 -0
  236. runtime/tests/test_levels_of_done_k1.py +474 -0
  237. runtime/tests/test_live_attestation_k2.py +521 -0
  238. runtime/tests/test_live_attestation_k2_regressions.py +442 -0
  239. runtime/tests/test_live_certification_k3_regressions.py +623 -0
  240. runtime/tests/test_lp7_studio_trigger.py +191 -0
  241. runtime/tests/test_master_plan_revision_identity.py +123 -0
  242. runtime/tests/test_multi_harness_acceptance.py +292 -0
  243. runtime/tests/test_multi_harness_stress.py +188 -0
  244. runtime/tests/test_objective_live_c1.py +437 -0
  245. runtime/tests/test_obligation_reconciliation_lc13.py +351 -0
  246. runtime/tests/test_observation_projection.py +156 -0
  247. runtime/tests/test_observation_wiring.py +100 -0
  248. runtime/tests/test_one_active_wave_lc06.py +629 -0
  249. runtime/tests/test_operational_sandbox_harness.py +111 -0
  250. runtime/tests/test_p002_canonical_engine.py +275 -0
  251. runtime/tests/test_p003_watcher_failure_attribution.py +933 -0
  252. runtime/tests/test_phase8_closeout.py +89 -0
  253. runtime/tests/test_phase8_company_environment.py +84 -0
  254. runtime/tests/test_phase8_company_proof.py +278 -0
  255. runtime/tests/test_phase8_cross_environment_audit.py +89 -0
  256. runtime/tests/test_phase8_developer_environment.py +59 -0
  257. runtime/tests/test_phase8_developer_proof.py +204 -0
  258. runtime/tests/test_phase8_harness.py +66 -0
  259. runtime/tests/test_phase8_personal_environment.py +62 -0
  260. runtime/tests/test_phase8_personal_proof.py +105 -0
  261. runtime/tests/test_phase8_protocol.py +180 -0
  262. runtime/tests/test_plan_before_code_lc04.py +830 -0
  263. runtime/tests/test_plan_census_lc12.py +243 -0
  264. runtime/tests/test_repo_census_lc11.py +230 -0
  265. runtime/tests/test_resilience.py +182 -0
  266. runtime/tests/test_retrieval_live_c5.py +270 -0
  267. runtime/tests/test_run_monitor_s2.py +587 -0
  268. runtime/tests/test_runtime_conformance.py +389 -0
  269. runtime/tests/test_sandbox_adapters.py +238 -0
  270. runtime/tests/test_scale_acceptance.py +114 -0
  271. runtime/tests/test_scope_freeze_lc05.py +638 -0
  272. runtime/tests/test_self_hosting_first_change.py +69 -0
  273. runtime/tests/test_self_hosting_projection.py +145 -0
  274. runtime/tests/test_self_hosting_protocol.py +87 -0
  275. runtime/tests/test_siem_integration_harness.py +98 -0
  276. runtime/tests/test_sign_release_archive.py +141 -0
  277. runtime/tests/test_store_concurrency.py +118 -0
  278. runtime/tests/test_studio_broker_integration.py +147 -0
  279. runtime/tests/test_tiers_doc.py +54 -0
  280. runtime/tests/test_trigger_firing_c1.py +342 -0
  281. runtime/tests/test_verify_tripartite_observability.py +120 -0
  282. runtime/tests/test_w102_branch_audit_equivalence.py +334 -0
  283. runtime/tests/test_w102_git_timeout_hang.py +233 -0
  284. runtime/tests/test_w103_identity.py +378 -0
  285. runtime/tests/test_w103_real_harness_identity.py +159 -0
  286. runtime/tests/test_w103_review_correction.py +224 -0
  287. runtime/tests/test_w103_round2_consumption.py +304 -0
  288. runtime/tests/test_w304_silent_background.py +713 -0
  289. runtime/tests/test_wave_report_lc07.py +332 -0
  290. tools/__init__.py +5 -0
  291. tools/adapter_families/agent_frameworks.py +1418 -0
  292. tools/adapter_families/cloud_coding.py +875 -0
  293. tools/adapter_families/core_cli.py +2519 -0
  294. tools/adapter_families/emacs.py +1247 -0
  295. tools/adapter_families/ide_rules.py +1105 -0
  296. tools/adapter_families/jetbrains_eclipse.py +1381 -0
  297. tools/adapter_families/neovim.py +995 -0
  298. tools/build_cosmos15_release_archive.py +110 -0
  299. tools/catalogs/model-modalities.json +84 -0
  300. tools/catalogs/ui-ux-catalog.json +173 -0
  301. tools/control_center/app.js +78 -0
  302. tools/control_center/index.html +35 -0
  303. tools/control_center/styles.css +4 -0
  304. tools/cosmos.py +1018 -0
  305. tools/cosmos15_operator.py +980 -0
  306. tools/cosmos15_world_recovery.py +292 -0
  307. tools/cosmos_adapter_health.py +311 -0
  308. tools/cosmos_ask.py +102 -0
  309. tools/cosmos_attach.py +237 -0
  310. tools/cosmos_background.py +258 -0
  311. tools/cosmos_bind.py +764 -0
  312. tools/cosmos_binding.py +130 -0
  313. tools/cosmos_blocker_gate.py +285 -0
  314. tools/cosmos_branch_audit.py +315 -0
  315. tools/cosmos_capability_health.py +4202 -0
  316. tools/cosmos_capability_reconciliation.py +419 -0
  317. tools/cosmos_capture_hook.py +644 -0
  318. tools/cosmos_cert_invalidation.py +1673 -0
  319. tools/cosmos_certification.py +506 -0
  320. tools/cosmos_check_proposal.py +483 -0
  321. tools/cosmos_check_runner.py +2480 -0
  322. tools/cosmos_claims_matrix.py +851 -0
  323. tools/cosmos_claude_door.py +268 -0
  324. tools/cosmos_cloud_bundle.py +73 -0
  325. tools/cosmos_context_authority.py +515 -0
  326. tools/cosmos_continuation.py +315 -0
  327. tools/cosmos_continuity_demo.py +180 -0
  328. tools/cosmos_continuity_wrapper.py +194 -0
  329. tools/cosmos_control_center.py +476 -0
  330. tools/cosmos_curator.py +175 -0
  331. tools/cosmos_daemon_supervisor.py +3082 -0
  332. tools/cosmos_decision_guard.py +206 -0
  333. tools/cosmos_decision_rank.py +103 -0
  334. tools/cosmos_decisions.py +343 -0
  335. tools/cosmos_defensibility_qualification.py +322 -0
  336. tools/cosmos_delta.py +887 -0
  337. tools/cosmos_dependency_graph.py +235 -0
  338. tools/cosmos_deployment_reconciler.py +393 -0
  339. tools/cosmos_design_dna.py +377 -0
  340. tools/cosmos_developer_world.py +1233 -0
  341. tools/cosmos_doctor.py +427 -0
  342. tools/cosmos_door_common.py +16 -0
  343. tools/cosmos_door_helpers.py +54 -0
  344. tools/cosmos_doorway_validator.py +152 -0
  345. tools/cosmos_enforce.py +527 -0
  346. tools/cosmos_enforcement_census.py +2657 -0
  347. tools/cosmos_eval.py +310 -0
  348. tools/cosmos_events.py +123 -0
  349. tools/cosmos_evidence.py +135 -0
  350. tools/cosmos_feedback.py +252 -0
  351. tools/cosmos_forge_adapters.py +190 -0
  352. tools/cosmos_forge_protection.py +154 -0
  353. tools/cosmos_fs_watcher.py +1378 -0
  354. tools/cosmos_gate.py +3172 -0
  355. tools/cosmos_gate_backlog.py +294 -0
  356. tools/cosmos_gate_carry.py +122 -0
  357. tools/cosmos_gate_categories.py +159 -0
  358. tools/cosmos_gate_closure.py +56 -0
  359. tools/cosmos_gate_fast.py +2592 -0
  360. tools/cosmos_gate_governance.py +282 -0
  361. tools/cosmos_gate_holdout.py +704 -0
  362. tools/cosmos_gate_linux.py +203 -0
  363. tools/cosmos_gate_load.py +205 -0
  364. tools/cosmos_gate_override.py +82 -0
  365. tools/cosmos_gate_profile.py +169 -0
  366. tools/cosmos_gate_protect.py +79 -0
  367. tools/cosmos_gate_replacements.py +66 -0
  368. tools/cosmos_gate_runtime.py +123 -0
  369. tools/cosmos_gate_scope.py +110 -0
  370. tools/cosmos_gate_selfcheck.py +79 -0
  371. tools/cosmos_gate_service.py +591 -0
  372. tools/cosmos_gate_union.py +108 -0
  373. tools/cosmos_git_hooks.py +59 -0
  374. tools/cosmos_githooks.py +94 -0
  375. tools/cosmos_guard.py +1887 -0
  376. tools/cosmos_harness_doors.py +350 -0
  377. tools/cosmos_home_guard.py +199 -0
  378. tools/cosmos_hygiene.py +251 -0
  379. tools/cosmos_hypothesis.py +124 -0
  380. tools/cosmos_identity.py +295 -0
  381. tools/cosmos_invariants.py +212 -0
  382. tools/cosmos_landing_board.py +394 -0
  383. tools/cosmos_launch.py +432 -0
  384. tools/cosmos_launcher.py +177 -0
  385. tools/cosmos_lc1_baseline.py +776 -0
  386. tools/cosmos_learn.py +319 -0
  387. tools/cosmos_levels_of_done.py +740 -0
  388. tools/cosmos_lineage.py +201 -0
  389. tools/cosmos_live_attestation.py +1559 -0
  390. tools/cosmos_mcp_registration.py +625 -0
  391. tools/cosmos_mcp_server.py +2253 -0
  392. tools/cosmos_memory.py +273 -0
  393. tools/cosmos_memory_check.py +97 -0
  394. tools/cosmos_modality_registry.py +113 -0
  395. tools/cosmos_narrative.py +225 -0
  396. tools/cosmos_next.py +659 -0
  397. tools/cosmos_objective_convergence.py +167 -0
  398. tools/cosmos_obligations.py +2809 -0
  399. tools/cosmos_observation_projection.py +144 -0
  400. tools/cosmos_observe.py +353 -0
  401. tools/cosmos_opencode_push.js +164 -0
  402. tools/cosmos_overlay_injector.py +44 -0
  403. tools/cosmos_override_gate.py +550 -0
  404. tools/cosmos_packaging_billing_gate.py +314 -0
  405. tools/cosmos_packet.py +973 -0
  406. tools/cosmos_pilot.py +731 -0
  407. tools/cosmos_plan_census.py +634 -0
  408. tools/cosmos_popup_check.py +260 -0
  409. tools/cosmos_premise.py +327 -0
  410. tools/cosmos_preservation_census.py +2185 -0
  411. tools/cosmos_proc.py +639 -0
  412. tools/cosmos_project_adapters.py +2773 -0
  413. tools/cosmos_push.py +138 -0
  414. tools/cosmos_qualification.py +291 -0
  415. tools/cosmos_reachability.py +345 -0
  416. tools/cosmos_reconciliation.py +451 -0
  417. tools/cosmos_refresh_adapters.py +80 -0
  418. tools/cosmos_remediation.py +166 -0
  419. tools/cosmos_repo_census.py +640 -0
  420. tools/cosmos_repo_finder.py +217 -0
  421. tools/cosmos_report.py +134 -0
  422. tools/cosmos_retrieval/__init__.py +41 -0
  423. tools/cosmos_retrieval/__main__.py +4 -0
  424. tools/cosmos_retrieval/activation.py +564 -0
  425. tools/cosmos_retrieval/cli.py +274 -0
  426. tools/cosmos_retrieval/embedders.py +214 -0
  427. tools/cosmos_retrieval/index.py +884 -0
  428. tools/cosmos_retrieval/model_fetch.py +122 -0
  429. tools/cosmos_retrieval/text.py +243 -0
  430. tools/cosmos_retrieval/vectors.py +101 -0
  431. tools/cosmos_rollback.py +453 -0
  432. tools/cosmos_run_monitor.py +1198 -0
  433. tools/cosmos_safety.py +350 -0
  434. tools/cosmos_scorecard.py +466 -0
  435. tools/cosmos_security_qualification.py +202 -0
  436. tools/cosmos_self_repair.py +192 -0
  437. tools/cosmos_serving.py +339 -0
  438. tools/cosmos_session_brief.py +302 -0
  439. tools/cosmos_session_lifecycle.py +389 -0
  440. tools/cosmos_session_start.py +1894 -0
  441. tools/cosmos_setup.py +585 -0
  442. tools/cosmos_staging_qualification.py +252 -0
  443. tools/cosmos_stop_guard.py +111 -0
  444. tools/cosmos_studio_app.py +2225 -0
  445. tools/cosmos_supply_chain_gate.py +454 -0
  446. tools/cosmos_synthetic_pilot.py +215 -0
  447. tools/cosmos_telemetry.py +153 -0
  448. tools/cosmos_tracker_render.py +196 -0
  449. tools/cosmos_trust_readiness.py +607 -0
  450. tools/cosmos_truth_drift.py +1573 -0
  451. tools/cosmos_vault.py +2023 -0
  452. tools/cosmos_vault_acl.py +715 -0
  453. tools/cosmos_vault_bundle.py +438 -0
  454. tools/cosmos_vault_install.py +471 -0
  455. tools/cosmos_vault_service.py +345 -0
  456. tools/cosmos_vault_worker.py +745 -0
  457. tools/cosmos_visibility_policy.py +134 -0
  458. tools/cosmos_wake.py +262 -0
  459. tools/cosmos_watchdog.py +1775 -0
  460. tools/cosmos_watchdog_timing.py +100 -0
  461. tools/cosmos_wave_report.py +357 -0
  462. tools/cosmos_wrong_direction.py +217 -0
  463. tools/evaluate_assurance_risk.py +302 -0
  464. tools/generate_execution_stack_conformance_fixtures.py +122 -0
  465. tools/generate_execution_stack_envelope_fixtures.py +122 -0
  466. tools/generate_model_route_receipt_fixtures.py +320 -0
  467. tools/observatory/README.md +64 -0
  468. tools/observatory/app.js +486 -0
  469. tools/observatory/index.html +82 -0
  470. tools/observatory/launcher.css +249 -0
  471. tools/observatory/launcher.html +80 -0
  472. tools/observatory/launcher.js +173 -0
  473. tools/observatory/styles.css +83 -0
  474. tools/operational_sandbox_harness.py +481 -0
  475. tools/owner_requeue.py +402 -0
  476. tools/reference_authorization.py +427 -0
  477. tools/reference_cold_reconstruction.py +264 -0
  478. tools/reference_context_binder.py +570 -0
  479. tools/reference_cosmos15_empirical.py +208 -0
  480. tools/reference_dogfood_runner.py +166 -0
  481. tools/reference_environment_audit.py +332 -0
  482. tools/reference_environment_harness.py +764 -0
  483. tools/reference_environment_proof.py +206 -0
  484. tools/reference_first_self_change.py +342 -0
  485. tools/reference_generation_a_continuation.py +111 -0
  486. tools/reference_generation_b_continuation.py +102 -0
  487. tools/reference_knowledge_lifecycle.py +318 -0
  488. tools/reference_maintenance.py +399 -0
  489. tools/reference_observatory.py +848 -0
  490. tools/reference_phase8_closeout.py +249 -0
  491. tools/reference_phase9_closeout.py +138 -0
  492. tools/reference_repository_projection.py +689 -0
  493. tools/reference_self_hosting.py +245 -0
  494. tools/reference_self_hosting_conformance.py +118 -0
  495. tools/reference_self_hosting_continuity.py +227 -0
  496. tools/reference_self_hosting_environment.py +411 -0
  497. tools/reference_self_learning.py +284 -0
  498. tools/run_execution_stack_conformance.py +195 -0
  499. tools/schemas/cosmos-certification.schema.json +65 -0
  500. tools/schemas/cosmos-record.schema.json +2918 -0
  501. tools/schemas/enterprise-audit-export.schema.json +255 -0
  502. tools/schemas/enterprise-durability-recovery.schema.json +282 -0
  503. tools/schemas/enterprise-execution-sandbox.schema.json +241 -0
  504. tools/schemas/enterprise-identity-policy.schema.json +222 -0
  505. tools/schemas/enterprise-secrets.schema.json +243 -0
  506. tools/schemas/environment-pack.schema.json +184 -0
  507. tools/schemas/environment-proof-case.schema.json +131 -0
  508. tools/schemas/execution-stack-conformance.schema.json +132 -0
  509. tools/schemas/execution-stack-envelope.schema.json +161 -0
  510. tools/schemas/model-modality-profile.schema.json +66 -0
  511. tools/schemas/model-route-receipt.schema.json +71 -0
  512. tools/schemas/relation-type.schema.json +76 -0
  513. tools/schemas/release-manifest.schema.json +58 -0
  514. tools/schemas/self-hosting-contract.schema.json +143 -0
  515. tools/siem_integration_harness.py +413 -0
  516. tools/sign_release_archive.py +357 -0
  517. tools/spec/reveal-register.json +65 -0
  518. tools/spec/reveal-register.schema.json +41 -0
  519. tools/stitch_design_bridge.py +593 -0
  520. tools/studio/byom_router.js +101 -0
  521. tools/studio/ide.html +109 -0
  522. tools/studio/ide.js +62 -0
  523. tools/studio/index.html +23 -0
  524. tools/studio/modality_guard.js +101 -0
  525. tools/studio/observatory_dock.js +60 -0
  526. tools/studio/studio.css +489 -0
  527. tools/studio/studio.js +50 -0
  528. tools/studio/studio_concentric_live.png +0 -0
  529. tools/studio/studio_cosmos_canvas.png +0 -0
  530. tools/studio/studio_hero_live.png +0 -0
  531. tools/studio/studio_live.png +0 -0
  532. tools/studio/studio_preview.png +0 -0
  533. tools/studio/studio_refined_platform.png +0 -0
  534. tools/studio/subatomic_sidecar.js +57 -0
  535. tools/validate_environment_proof.py +39 -0
  536. tools/validate_execution_stack_envelopes.py +157 -0
  537. tools/validate_model_route_receipts.py +183 -0
  538. tools/validate_ontology.py +121 -0
  539. tools/verify_cosmos15_baseline.py +104 -0
  540. tools/verify_cosmos15_release_archive.py +225 -0
  541. tools/verify_tripartite_observability.py +136 -0
@@ -0,0 +1,884 @@
1
+ """Cosmos retrieval index: build, status (freshness), and search.
2
+
3
+ The index is derived, disposable state stored at
4
+ ``<project root>/.cosmos/retrieval/index.sqlite3``. It is never a source of
5
+ truth: every result carries a path and line range to verify against the
6
+ working tree, and ``status`` reports whether the index still matches HEAD.
7
+
8
+ Corpus: the files ``git ls-files`` reports for the project root (tracked
9
+ files only), minus binary, oversized, excluded-extension and
10
+ sensitive-looking paths. Content is taken from the working tree and
11
+ redacted before chunking, so secrets never become stored text or terms.
12
+
13
+ Ranking:
14
+ * always BM25 over code-aware terms (path and symbol terms boosted);
15
+ * when the index was built with a dense embedder, BM25 and cosine rankings
16
+ are fused with reciprocal rank fusion (RRF).
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import hashlib
21
+ import math
22
+ import os
23
+ import sqlite3
24
+ from tools import cosmos_proc as subprocess
25
+ import time
26
+ from collections import Counter
27
+ from datetime import datetime, timezone
28
+ from pathlib import Path
29
+ from typing import Any, Iterable
30
+
31
+ from .embedders import Embedder, LexicalEmbedder, OnnxEmbedder, RetrievalConfigError, select_embedder
32
+ from .text import chunk_lines, is_sensitive_path, path_terms, redact, tokenize
33
+ from .vectors import to_blob, try_load_sqlite_vec, vector_search
34
+
35
+ SCHEMA_VERSION = "1"
36
+ INDEX_RELATIVE_PATH = Path(".cosmos") / "retrieval" / "index.sqlite3"
37
+ DEFAULT_MAX_FILE_BYTES = 400_000
38
+ BM25_K1 = 1.2
39
+ BM25_B = 0.75
40
+ PATH_WEIGHT = 1.5
41
+ SYMBOL_WEIGHT = 2.0
42
+ RRF_K = 60
43
+ GIT_TIMEOUT_SECONDS = 60
44
+
45
+ EXCLUDED_EXTENSIONS = frozenset(
46
+ {
47
+ # binaries, archives, media, fonts
48
+ ".png", ".jpg", ".jpeg", ".gif", ".ico", ".bmp", ".webp", ".pdf", ".svgz",
49
+ ".zip", ".tar", ".gz", ".tgz", ".bz2", ".xz", ".7z", ".whl", ".bundle", ".jar",
50
+ ".exe", ".dll", ".so", ".dylib", ".bin", ".pyc", ".pyo", ".class", ".o", ".a",
51
+ ".woff", ".woff2", ".ttf", ".otf", ".eot", ".mp3", ".mp4", ".wav", ".mov",
52
+ ".db", ".sqlite", ".sqlite3", ".onnx", ".pt", ".npy",
53
+ # append-only data logs and lockfiles: large, repetitive, low retrieval value
54
+ ".jsonl", ".lock",
55
+ }
56
+ )
57
+ EXCLUDED_FILENAMES = frozenset({"package-lock.json", "pnpm-lock.yaml", "yarn.lock", "poetry.lock"})
58
+
59
+
60
+ def pipeline_fingerprint() -> str:
61
+ """Fingerprint of everything that turns file bytes into stored chunks/terms.
62
+
63
+ Incremental builds skip files whose content hash is unchanged, so a change
64
+ to redaction, tokenization, chunking, weights or exclusions must force a
65
+ full rebuild; otherwise old files would keep stale (e.g. unredacted) data.
66
+ """
67
+ from . import text as _text
68
+
69
+ digest = hashlib.sha256(Path(_text.__file__).read_bytes())
70
+ digest.update(
71
+ repr((SCHEMA_VERSION, PATH_WEIGHT, SYMBOL_WEIGHT, sorted(EXCLUDED_EXTENSIONS), sorted(EXCLUDED_FILENAMES))).encode()
72
+ )
73
+ return digest.hexdigest()[:16]
74
+
75
+
76
+ class RetrievalError(RuntimeError):
77
+ """A user-facing retrieval failure (not a git repo, index missing, ...)."""
78
+
79
+
80
+ class IndexMissingError(RetrievalError):
81
+ pass
82
+
83
+
84
+ # ---------------------------------------------------------------------------
85
+ # git
86
+ # ---------------------------------------------------------------------------
87
+
88
+ def _git(root: Path, *args: str) -> subprocess.CompletedProcess[bytes]:
89
+ return subprocess.run(
90
+ ["git", "-C", str(root), *args],
91
+ capture_output=True,
92
+ timeout=GIT_TIMEOUT_SECONDS,
93
+ check=False,
94
+ )
95
+
96
+
97
+ def resolve_root(path: str | os.PathLike[str] | None = None) -> Path:
98
+ """Resolve the git top-level directory containing ``path`` (default: cwd)."""
99
+ start = Path(path) if path is not None else Path.cwd()
100
+ if not start.exists():
101
+ raise RetrievalError(f"root does not exist: {start}")
102
+ try:
103
+ proc = _git(start, "rev-parse", "--show-toplevel")
104
+ except (OSError, subprocess.TimeoutExpired) as exc:
105
+ raise RetrievalError(f"git unavailable: {exc}") from exc
106
+ if proc.returncode != 0:
107
+ raise RetrievalError(f"not inside a git work tree: {start}")
108
+ return Path(proc.stdout.decode("utf-8").strip()).resolve()
109
+
110
+
111
+ def git_head(root: Path) -> str | None:
112
+ proc = _git(root, "rev-parse", "--verify", "--quiet", "HEAD")
113
+ if proc.returncode != 0:
114
+ return None # repository without commits
115
+ return proc.stdout.decode("utf-8").strip() or None
116
+
117
+
118
+ def list_git_files(root: Path) -> list[str]:
119
+ proc = _git(root, "ls-files", "-z", "--cached")
120
+ if proc.returncode != 0:
121
+ raise RetrievalError(f"git ls-files failed: {proc.stderr.decode('utf-8', 'replace').strip()}")
122
+ seen: dict[str, None] = {}
123
+ for raw in proc.stdout.split(b"\0"):
124
+ if raw:
125
+ seen.setdefault(raw.decode("utf-8", "surrogateescape"), None)
126
+ return list(seen)
127
+
128
+
129
+ def path_exclusion_reason(path: str) -> str | None:
130
+ """Deterministic, content-independent exclusion rules."""
131
+ lowered = path.lower()
132
+ if lowered.startswith(".cosmos/") or "/.cosmos/" in lowered:
133
+ return "cosmos_state"
134
+ name = lowered.rsplit("/", 1)[-1]
135
+ if name in EXCLUDED_FILENAMES:
136
+ return "excluded_file"
137
+ if Path(name).suffix in EXCLUDED_EXTENSIONS or name.endswith(".min.js"):
138
+ return "excluded_extension"
139
+ if is_sensitive_path(path):
140
+ return "sensitive_path"
141
+ return None
142
+
143
+
144
+ def _read_candidate(root: Path, path: str, max_file_bytes: int) -> tuple[bytes | None, os.stat_result | None, str | None]:
145
+ full = root / path
146
+ try:
147
+ st = full.stat()
148
+ except OSError:
149
+ return None, None, "missing"
150
+ if not full.is_file():
151
+ return None, st, "not_a_file"
152
+ if st.st_size > max_file_bytes:
153
+ return None, st, "too_large"
154
+ try:
155
+ data = full.read_bytes()
156
+ except OSError:
157
+ return None, st, "unreadable"
158
+ if b"\0" in data[:8192]:
159
+ return data, st, "binary"
160
+ return data, st, None
161
+
162
+
163
+ def _sha256(data: bytes) -> str:
164
+ return hashlib.sha256(data).hexdigest()
165
+
166
+
167
+ # ---------------------------------------------------------------------------
168
+ # storage
169
+ # ---------------------------------------------------------------------------
170
+
171
+ _SCHEMA = """
172
+ CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT);
173
+ CREATE TABLE IF NOT EXISTS files (
174
+ path TEXT PRIMARY KEY,
175
+ content_hash TEXT NOT NULL,
176
+ size INTEGER NOT NULL,
177
+ mtime_ns INTEGER NOT NULL,
178
+ chunk_count INTEGER NOT NULL,
179
+ skip_reason TEXT,
180
+ redactions INTEGER NOT NULL DEFAULT 0,
181
+ indexed_at TEXT NOT NULL
182
+ );
183
+ CREATE TABLE IF NOT EXISTS chunks (
184
+ id INTEGER PRIMARY KEY,
185
+ path TEXT NOT NULL,
186
+ ordinal INTEGER NOT NULL,
187
+ start_line INTEGER NOT NULL,
188
+ end_line INTEGER NOT NULL,
189
+ text TEXT NOT NULL,
190
+ length INTEGER NOT NULL,
191
+ symbols TEXT NOT NULL
192
+ );
193
+ CREATE INDEX IF NOT EXISTS chunks_path ON chunks(path);
194
+ CREATE TABLE IF NOT EXISTS postings (
195
+ term TEXT NOT NULL,
196
+ chunk_id INTEGER NOT NULL,
197
+ tf REAL NOT NULL,
198
+ PRIMARY KEY (term, chunk_id)
199
+ ) WITHOUT ROWID;
200
+ CREATE INDEX IF NOT EXISTS postings_chunk ON postings(chunk_id);
201
+ CREATE TABLE IF NOT EXISTS vectors (chunk_id INTEGER PRIMARY KEY, embedding BLOB NOT NULL);
202
+ """
203
+
204
+
205
+ def index_path_for(root: Path) -> Path:
206
+ return root / INDEX_RELATIVE_PATH
207
+
208
+
209
+ def _connect_rw(path: Path) -> sqlite3.Connection:
210
+ path.parent.mkdir(parents=True, exist_ok=True)
211
+ conn = sqlite3.connect(str(path), isolation_level=None, timeout=30)
212
+ try:
213
+ # Keep the default DELETE journal mode for hot-journal recovery (test_cosmos_index_hot_journal),
214
+ # while holding SQLite temp B-trees and page cache in memory during batch index builds.
215
+ conn.execute("PRAGMA temp_store = MEMORY")
216
+ conn.execute("PRAGMA cache_size = -16384")
217
+ conn.executescript(_SCHEMA)
218
+ except BaseException:
219
+ # Never leak an open handle on a corrupt/unreadable file: on Windows
220
+ # the leaked connection would keep the file locked for the caller.
221
+ conn.close()
222
+ raise
223
+ return conn
224
+
225
+
226
+ def _connect_ro(path: Path) -> sqlite3.Connection:
227
+ """Open the index read-only. A hot journal (a write that was killed before it committed) cannot be rolled back
228
+ through a read-only connection: the first read fails with "attempt to write a readonly database". The index is
229
+ derived state, so such a journal is recovered by SQLite's own rollback: a read-write open runs it, then the
230
+ read-only open is retried."""
231
+ if not path.is_file():
232
+ raise IndexMissingError(
233
+ f"no retrieval index at {path}; build it with `python -m tools.cosmos retrieval build --root <project>`"
234
+ )
235
+ uri = path.resolve().as_uri() + "?mode=ro"
236
+ probe = sqlite3.connect(uri, uri=True, timeout=30)
237
+ try:
238
+ probe.execute("SELECT 1 FROM sqlite_master LIMIT 1").fetchall() # the first read is where a hot journal shows
239
+ return probe
240
+ except sqlite3.DatabaseError as exc:
241
+ probe.close() # never keep a handle on a file the recovery must open (Windows locks it)
242
+ if "readonly" not in str(exc).lower():
243
+ raise
244
+ recover = sqlite3.connect(str(path), timeout=30, isolation_level=None)
245
+ try:
246
+ recover.execute("SELECT 1 FROM sqlite_master LIMIT 1").fetchall() # rolls the hot journal back
247
+ finally:
248
+ recover.close()
249
+ conn = sqlite3.connect(uri, uri=True, timeout=30)
250
+ conn.execute("SELECT 1 FROM sqlite_master LIMIT 1").fetchall()
251
+ return conn
252
+
253
+
254
+ def _meta(conn: sqlite3.Connection) -> dict[str, str]:
255
+ return {k: v for k, v in conn.execute("SELECT key, value FROM meta")}
256
+
257
+
258
+ def _set_meta(conn: sqlite3.Connection, values: dict[str, Any]) -> None:
259
+ conn.executemany(
260
+ "INSERT OR REPLACE INTO meta(key, value) VALUES (?, ?)",
261
+ [(k, "" if v is None else str(v)) for k, v in values.items()],
262
+ )
263
+
264
+
265
+ def _delete_path(conn: sqlite3.Connection, path: str) -> None:
266
+ ids = [row[0] for row in conn.execute("SELECT id FROM chunks WHERE path = ?", (path,))]
267
+ for chunk_id in ids:
268
+ conn.execute("DELETE FROM postings WHERE chunk_id = ?", (chunk_id,))
269
+ conn.execute("DELETE FROM vectors WHERE chunk_id = ?", (chunk_id,))
270
+ conn.execute("DELETE FROM chunks WHERE path = ?", (path,))
271
+ conn.execute("DELETE FROM files WHERE path = ?", (path,))
272
+
273
+
274
+ def _now() -> str:
275
+ return datetime.now(timezone.utc).isoformat(timespec="seconds")
276
+
277
+
278
+ # ---------------------------------------------------------------------------
279
+ # build
280
+ # ---------------------------------------------------------------------------
281
+
282
+ def build_index(
283
+ root: str | os.PathLike[str] | None = None,
284
+ *,
285
+ embedder: Embedder | None = None,
286
+ embedder_preference: str = "auto",
287
+ model_dir: str | os.PathLike[str] | None = None,
288
+ full: bool = False,
289
+ max_file_bytes: int = DEFAULT_MAX_FILE_BYTES,
290
+ index_path: str | os.PathLike[str] | None = None,
291
+ ) -> dict[str, Any]:
292
+ """Build or incrementally update the index for ``root``'s git repository.
293
+
294
+ ``index_path`` builds into another file (the background refresh builds a temporary copy and swaps it in)."""
295
+ started = time.perf_counter()
296
+ root_path = resolve_root(root)
297
+ if embedder is None:
298
+ if model_dir is None and embedder_preference in ("auto", "onnx"):
299
+ # LC1.22 wiring: honour the durable activation config /
300
+ # default fetch destination so a model placed by
301
+ # `cosmos retrieval fetch-model` activates dense search with
302
+ # no extra flags (lazy import: activation imports this module).
303
+ from .activation import configured_model_dir
304
+
305
+ model_dir = configured_model_dir(root_path)
306
+ embedder, selection = select_embedder(embedder_preference, model_dir)
307
+ else:
308
+ selection = {"requested": "explicit", "reason": "embedder supplied by caller"}
309
+ signature = embedder.signature()
310
+ head = git_head(root_path)
311
+ listed = list_git_files(root_path)
312
+ index_path = Path(index_path) if index_path is not None else index_path_for(root_path)
313
+
314
+ try:
315
+ conn = _connect_rw(index_path)
316
+ except sqlite3.DatabaseError as exc:
317
+ raise RetrievalError(
318
+ f"existing index at {index_path} is unreadable ({type(exc).__name__}: {exc}); "
319
+ f"delete the derived file and rebuild — it is safe to remove {index_path} "
320
+ f"(the index is derived state)"
321
+ ) from exc
322
+ counts: Counter[str] = Counter()
323
+ rebuild_reason = "requested (--full)" if full else None
324
+ fingerprint = pipeline_fingerprint()
325
+ try:
326
+ meta = _meta(conn)
327
+ if not rebuild_reason and meta:
328
+ if meta.get("schema_version") != SCHEMA_VERSION:
329
+ rebuild_reason = f"schema {meta.get('schema_version')} -> {SCHEMA_VERSION}"
330
+ elif meta.get("pipeline_fingerprint") != fingerprint:
331
+ rebuild_reason = f"text pipeline changed ({meta.get('pipeline_fingerprint')} -> {fingerprint})"
332
+ elif meta.get("embedder_signature") != signature:
333
+ rebuild_reason = f"embedder {meta.get('embedder_signature')} -> {signature}"
334
+ elif meta.get("max_file_bytes") != str(max_file_bytes):
335
+ rebuild_reason = f"max_file_bytes {meta.get('max_file_bytes')} -> {max_file_bytes}"
336
+ conn.execute("BEGIN IMMEDIATE")
337
+ if rebuild_reason:
338
+ for table in ("postings", "vectors", "chunks", "files", "meta"):
339
+ conn.execute(f"DELETE FROM {table}")
340
+
341
+ known = {
342
+ path: content_hash
343
+ for path, content_hash in conn.execute("SELECT path, content_hash FROM files")
344
+ }
345
+ wanted: set[str] = set()
346
+ pending_dense: list[tuple[int, str]] = []
347
+ posting_batch: list[tuple[str, int, float]] = []
348
+ now = _now()
349
+ for path in listed:
350
+ if path_exclusion_reason(path):
351
+ counts["excluded_by_path"] += 1
352
+ continue
353
+ data, st, reason = _read_candidate(root_path, path, max_file_bytes)
354
+ if st is None: # tracked but missing from the working tree
355
+ counts["missing"] += 1
356
+ continue
357
+ wanted.add(path)
358
+ content_hash = _sha256(data) if data is not None else f"size:{st.st_size}"
359
+ if known.get(path) == content_hash:
360
+ conn.execute(
361
+ "UPDATE files SET size = ?, mtime_ns = ? WHERE path = ?",
362
+ (st.st_size, st.st_mtime_ns, path),
363
+ )
364
+ counts["unchanged"] += 1
365
+ continue
366
+ _delete_path(conn, path)
367
+ if reason is not None:
368
+ conn.execute(
369
+ "INSERT INTO files(path, content_hash, size, mtime_ns, chunk_count, skip_reason, indexed_at)"
370
+ " VALUES (?, ?, ?, ?, 0, ?, ?)",
371
+ (path, content_hash, st.st_size, st.st_mtime_ns, reason, now),
372
+ )
373
+ counts[f"skipped_{reason}"] += 1
374
+ continue
375
+ text, redactions = redact(data.decode("utf-8", errors="replace"))
376
+ chunks = chunk_lines(text.splitlines(), Path(path).suffix.lower())
377
+ p_terms = path_terms(path)
378
+ for ordinal, chunk in enumerate(chunks):
379
+ body_terms = tokenize(chunk.text)
380
+ cur = conn.execute(
381
+ "INSERT INTO chunks(path, ordinal, start_line, end_line, text, length, symbols)"
382
+ " VALUES (?, ?, ?, ?, ?, ?, ?)",
383
+ (path, ordinal, chunk.start_line, chunk.end_line, chunk.text, len(body_terms),
384
+ "\n".join(chunk.symbols)),
385
+ )
386
+ chunk_id = int(cur.lastrowid)
387
+ tf: Counter[str] = Counter(body_terms)
388
+ for term in p_terms:
389
+ tf[term] += PATH_WEIGHT
390
+ for symbol in chunk.symbols:
391
+ for term in tokenize(symbol):
392
+ tf[term] += SYMBOL_WEIGHT
393
+ posting_batch.extend((term, chunk_id, float(value)) for term, value in tf.items())
394
+ if len(posting_batch) >= 2000:
395
+ conn.executemany(
396
+ "INSERT INTO postings(term, chunk_id, tf) VALUES (?, ?, ?)",
397
+ posting_batch,
398
+ )
399
+ posting_batch.clear()
400
+ if embedder.kind == "dense":
401
+ pending_dense.append((chunk_id, f"{path}\n{chunk.text}"))
402
+ conn.execute(
403
+ "INSERT INTO files(path, content_hash, size, mtime_ns, chunk_count, skip_reason, redactions, indexed_at)"
404
+ " VALUES (?, ?, ?, ?, ?, NULL, ?, ?)",
405
+ (path, content_hash, st.st_size, st.st_mtime_ns, len(chunks), redactions, now),
406
+ )
407
+ counts["indexed"] += 1
408
+ counts["redactions"] += redactions
409
+
410
+ if posting_batch:
411
+ conn.executemany(
412
+ "INSERT INTO postings(term, chunk_id, tf) VALUES (?, ?, ?)",
413
+ posting_batch,
414
+ )
415
+ posting_batch.clear()
416
+
417
+ for path in set(known) - wanted:
418
+ _delete_path(conn, path)
419
+ counts["removed"] += 1
420
+
421
+ if pending_dense:
422
+ batch = 64
423
+ for offset in range(0, len(pending_dense), batch):
424
+ part = pending_dense[offset : offset + batch]
425
+ vectors = embedder.embed([text for _, text in part])
426
+ conn.executemany(
427
+ "INSERT OR REPLACE INTO vectors(chunk_id, embedding) VALUES (?, ?)",
428
+ [(cid, to_blob(vec)) for (cid, _), vec in zip(part, vectors)],
429
+ )
430
+ counts["embedded_chunks"] = len(pending_dense)
431
+
432
+ dirty = _git(root_path, "status", "--porcelain", "--untracked-files=no")
433
+ _set_meta(
434
+ conn,
435
+ {
436
+ "schema_version": SCHEMA_VERSION,
437
+ "pipeline_fingerprint": fingerprint,
438
+ "embedder_name": embedder.name,
439
+ "embedder_kind": embedder.kind,
440
+ "embedder_signature": signature,
441
+ "embedder_dimensions": embedder.dimensions,
442
+ "model_dir": str(getattr(embedder, "model_dir", "") or ""),
443
+ "index_commit": head,
444
+ "built_at": _now(),
445
+ "worktree_dirty_at_build": "yes" if dirty.returncode == 0 and dirty.stdout.strip() else "no",
446
+ "max_file_bytes": max_file_bytes,
447
+ },
448
+ )
449
+ conn.execute("COMMIT")
450
+ indexed_files, chunk_total = _counts(conn)
451
+ except BaseException:
452
+ if conn.in_transaction:
453
+ conn.execute("ROLLBACK")
454
+ raise
455
+ finally:
456
+ conn.close()
457
+
458
+ return {
459
+ "schema": "cosmos.retrieval-build/1",
460
+ "root": str(root_path),
461
+ "index_path": str(index_path),
462
+ "index_commit": head,
463
+ "embedder": _embedder_block(embedder.name, embedder.kind, embedder.dimensions),
464
+ "selection": selection,
465
+ "rebuild_reason": rebuild_reason,
466
+ "tracked_files": len(listed),
467
+ "indexed_files": indexed_files,
468
+ "chunks": chunk_total,
469
+ "counts": dict(sorted(counts.items())),
470
+ "duration_seconds": round(time.perf_counter() - started, 3),
471
+ }
472
+
473
+
474
+ def _counts(conn: sqlite3.Connection) -> tuple[int, int]:
475
+ files = conn.execute("SELECT COUNT(*) FROM files WHERE skip_reason IS NULL").fetchone()[0]
476
+ chunks = conn.execute("SELECT COUNT(*) FROM chunks").fetchone()[0]
477
+ return int(files), int(chunks)
478
+
479
+
480
+ def _embedder_block(name: str, kind: str, dimensions: Any) -> dict[str, Any]:
481
+ return {
482
+ "name": name,
483
+ "kind": kind,
484
+ "semantic": kind == "dense",
485
+ "dimensions": int(dimensions or 0),
486
+ "label": "dense semantic embeddings" if kind == "dense" else "lexical BM25, not semantic",
487
+ }
488
+
489
+
490
+ # ---------------------------------------------------------------------------
491
+ # freshness / status
492
+ # ---------------------------------------------------------------------------
493
+
494
+ def compute_freshness(root: Path, conn: sqlite3.Connection, *, sample: int = 10) -> dict[str, Any]:
495
+ meta = _meta(conn)
496
+ head = git_head(root)
497
+ index_commit = meta.get("index_commit") or None
498
+ max_file_bytes = int(meta.get("max_file_bytes") or DEFAULT_MAX_FILE_BYTES)
499
+ indexed = {
500
+ path: (content_hash, size, mtime_ns)
501
+ for path, content_hash, size, mtime_ns in conn.execute(
502
+ "SELECT path, content_hash, size, mtime_ns FROM files"
503
+ )
504
+ }
505
+ listed = [p for p in list_git_files(root) if not path_exclusion_reason(p)]
506
+ added: list[str] = []
507
+ changed: list[str] = []
508
+ seen: set[str] = set()
509
+ for path in listed:
510
+ full = root / path
511
+ try:
512
+ st = full.stat()
513
+ except OSError:
514
+ continue # missing from the working tree: build skips it as well
515
+ seen.add(path)
516
+ if path not in indexed:
517
+ added.append(path)
518
+ continue
519
+ content_hash, size, mtime_ns = indexed[path]
520
+ if st.st_size == size and st.st_mtime_ns == mtime_ns:
521
+ continue
522
+ data, _st, _reason = _read_candidate(root, path, max_file_bytes)
523
+ current = _sha256(data) if data is not None else f"size:{st.st_size}"
524
+ if current != content_hash:
525
+ changed.append(path)
526
+ removed = sorted(set(indexed) - seen)
527
+ reasons: list[str] = []
528
+ if index_commit != head:
529
+ reasons.append(f"index commit {_short(index_commit)} != HEAD {_short(head)}")
530
+ if meta.get("pipeline_fingerprint") != pipeline_fingerprint():
531
+ reasons.append("index was built by a different retrieval text pipeline (rebuild required)")
532
+ if added:
533
+ reasons.append(f"{len(added)} tracked file(s) not in index")
534
+ if changed:
535
+ reasons.append(f"{len(changed)} file(s) changed since indexing")
536
+ if removed:
537
+ reasons.append(f"{len(removed)} indexed file(s) no longer tracked")
538
+ return {
539
+ "index_commit": index_commit,
540
+ "head": head,
541
+ "commit_matches_head": index_commit == head,
542
+ "stale": bool(reasons),
543
+ "stale_reasons": reasons,
544
+ "added": len(added),
545
+ "changed": len(changed),
546
+ "removed": len(removed),
547
+ "sample": sorted(added + changed)[:sample] + removed[:sample],
548
+ "built_at": meta.get("built_at") or None,
549
+ "worktree_dirty_at_build": meta.get("worktree_dirty_at_build") == "yes",
550
+ }
551
+
552
+
553
+ def _short(sha: str | None) -> str:
554
+ return sha[:12] if sha else "(none)"
555
+
556
+
557
+ def _unreadable_fields(root_path: Path, exc: BaseException) -> dict[str, Any]:
558
+ """Honest status fields for an index SQLite cannot read.
559
+
560
+ A build killed mid-transaction leaves a hot journal, and a truncated or
561
+ replaced file is simply not a database; in both cases read-only open
562
+ fails with a raw sqlite error. LC1.22 hardening: report that state
563
+ precisely instead of raising a traceback, and name the repair.
564
+ """
565
+ return {
566
+ "healthy": False,
567
+ "stale": True,
568
+ "unreadable": True,
569
+ "unreadable_reason": f"{type(exc).__name__}: {exc}",
570
+ "index_commit": None,
571
+ "head": git_head(root_path),
572
+ "indexed_files": 0,
573
+ "chunks": 0,
574
+ "stale_reasons": ["index unreadable (hot journal or corrupt file)"],
575
+ "freshness": {},
576
+ "embedder": {"name": "?", "kind": "unknown", "label": "index unreadable"},
577
+ "retrieval_backend": "none (index unreadable)",
578
+ "vector_backend": "n/a",
579
+ "hint": (
580
+ f"python -m tools.cosmos retrieval build --root {root_path} --full "
581
+ "(the index is derived state; delete .cosmos/retrieval/ if this persists)"
582
+ ),
583
+ }
584
+
585
+
586
+ def _unreadable_message(root_path: Path, exc: BaseException) -> str:
587
+ return (
588
+ f"retrieval index unreadable ({type(exc).__name__}: {exc}); rebuild with "
589
+ f"`python -m tools.cosmos retrieval build --root {root_path} --full` "
590
+ f"(the index is derived state)"
591
+ )
592
+
593
+
594
+ def _vector_backend(conn: sqlite3.Connection, kind: str) -> tuple[str, bool]:
595
+ if kind != "dense":
596
+ return "not used (lexical backend stores no vectors)", False
597
+ ok, detail = try_load_sqlite_vec(conn)
598
+ if ok:
599
+ return detail, True
600
+ return f"python-cosine (degraded: {detail})", False
601
+
602
+
603
+ def _retrieval_backend(meta: dict[str, str], dense_active: bool) -> str:
604
+ if meta.get("embedder_kind") == "dense" and dense_active:
605
+ return f"hybrid-rrf(bm25 + {meta.get('embedder_name')})"
606
+ if meta.get("embedder_kind") == "dense":
607
+ return "bm25-lexical (degraded: index has dense vectors but the embedder is unavailable)"
608
+ return "bm25-lexical"
609
+
610
+
611
+ def status(root: str | os.PathLike[str] | None = None) -> dict[str, Any]:
612
+ root_path = resolve_root(root)
613
+ index_path = index_path_for(root_path)
614
+ report: dict[str, Any] = {
615
+ "schema": "cosmos.retrieval-status/1",
616
+ "root": str(root_path),
617
+ "index_path": str(index_path),
618
+ "exists": index_path.is_file(),
619
+ }
620
+ if not report["exists"]:
621
+ report.update(
622
+ {
623
+ "healthy": False,
624
+ "stale": True,
625
+ "head": git_head(root_path),
626
+ "index_commit": None,
627
+ "indexed_files": 0,
628
+ "retrieval_backend": "none (index not built)",
629
+ "hint": "python -m tools.cosmos retrieval build --root " + str(root_path),
630
+ }
631
+ )
632
+ return report
633
+ conn = None
634
+ try:
635
+ conn = _connect_ro(index_path)
636
+ meta = _meta(conn)
637
+ files, chunks = _counts(conn)
638
+ skipped = dict(conn.execute("SELECT skip_reason, COUNT(*) FROM files WHERE skip_reason IS NOT NULL GROUP BY skip_reason"))
639
+ freshness = compute_freshness(root_path, conn)
640
+ vector_backend, _ = _vector_backend(conn, meta.get("embedder_kind", "lexical"))
641
+ dense_active = False
642
+ dense_note = None
643
+ if meta.get("embedder_kind") == "dense":
644
+ _emb, dense_note = _load_dense_embedder(meta, None)
645
+ dense_active = _emb is not None
646
+ except sqlite3.DatabaseError as exc:
647
+ report.update(_unreadable_fields(root_path, exc))
648
+ return report
649
+ finally:
650
+ if conn is not None:
651
+ conn.close()
652
+ report.update(
653
+ {
654
+ "schema_version": meta.get("schema_version"),
655
+ "indexed_files": files,
656
+ "chunks": chunks,
657
+ "skipped_files": skipped,
658
+ "index_commit": freshness["index_commit"],
659
+ "head": freshness["head"],
660
+ "stale": freshness["stale"],
661
+ "stale_reasons": freshness["stale_reasons"],
662
+ "freshness": freshness,
663
+ "embedder": _embedder_block(meta.get("embedder_name", "?"), meta.get("embedder_kind", "lexical"),
664
+ meta.get("embedder_dimensions")),
665
+ "retrieval_backend": _retrieval_backend(meta, dense_active),
666
+ "vector_backend": vector_backend,
667
+ "healthy": not freshness["stale"] and files > 0,
668
+ }
669
+ )
670
+ if dense_note:
671
+ report["dense_note"] = dense_note
672
+ return report
673
+
674
+
675
+ # ---------------------------------------------------------------------------
676
+ # search
677
+ # ---------------------------------------------------------------------------
678
+
679
+ def _load_dense_embedder(meta: dict[str, str], supplied: Embedder | None) -> tuple[Embedder | None, str | None]:
680
+ wanted = meta.get("embedder_signature")
681
+ if supplied is not None:
682
+ if supplied.kind == "dense" and supplied.signature() == wanted:
683
+ return supplied, None
684
+ return None, f"supplied embedder {supplied.signature()} does not match index {wanted}"
685
+ model_dir = meta.get("model_dir")
686
+ if not model_dir:
687
+ return None, "index built with a dense embedder that cannot be reconstructed (no model_dir recorded)"
688
+ try:
689
+ embedder = OnnxEmbedder(model_dir)
690
+ if embedder.signature() != wanted:
691
+ return None, f"model at {model_dir} ({embedder.signature()}) no longer matches index ({wanted})"
692
+ return embedder, None
693
+ except Exception as exc: # noqa: BLE001 - reported as degraded
694
+ return None, f"dense embedder unavailable: {type(exc).__name__}: {exc}"
695
+
696
+
697
+ def _normalize_query_path(query: str) -> str:
698
+ q = query.strip().strip("'\"`").replace("\\", "/")
699
+ while q.startswith("./"):
700
+ q = q[2:]
701
+ return q
702
+
703
+
704
+ def search(
705
+ root: str | os.PathLike[str] | None,
706
+ query: str,
707
+ *,
708
+ limit: int = 8,
709
+ max_per_file: int = 2,
710
+ max_chars: int | None = 1200,
711
+ embedder: Embedder | None = None,
712
+ include_freshness: bool = True,
713
+ dense: bool = True,
714
+ ) -> dict[str, Any]:
715
+ """Rank indexed chunks for ``query``. Read-only; never builds the index.
716
+
717
+ ``dense=False`` ranks with BM25 only: no dense model is loaded and the query is not embedded (a bind uses this).
718
+ """
719
+ if not isinstance(query, str) or not query.strip():
720
+ raise RetrievalError("query must be a non-empty string")
721
+ limit = max(1, min(int(limit), 100))
722
+ root_path = resolve_root(root)
723
+ try:
724
+ conn = _connect_ro(index_path_for(root_path))
725
+ except sqlite3.DatabaseError as exc:
726
+ raise RetrievalError(_unreadable_message(root_path, exc)) from exc
727
+ notes: list[str] = []
728
+ try:
729
+ try:
730
+ meta = _meta(conn)
731
+ except sqlite3.DatabaseError as exc:
732
+ raise RetrievalError(_unreadable_message(root_path, exc)) from exc
733
+ kind = meta.get("embedder_kind", "lexical")
734
+ total_chunks, avgdl = conn.execute("SELECT COUNT(*), AVG(length) FROM chunks").fetchone()
735
+ total_chunks = int(total_chunks or 0)
736
+ avgdl = float(avgdl or 1.0) or 1.0
737
+
738
+ # --- BM25 ---
739
+ bm25: dict[int, float] = {}
740
+ for term, qtf in Counter(tokenize(query)).items():
741
+ rows = conn.execute(
742
+ "SELECT p.chunk_id, p.tf, c.length FROM postings p JOIN chunks c ON c.id = p.chunk_id WHERE p.term = ?",
743
+ (term,),
744
+ ).fetchall()
745
+ if not rows:
746
+ continue
747
+ df = len(rows)
748
+ idf = math.log(1.0 + (total_chunks - df + 0.5) / (df + 0.5))
749
+ for chunk_id, tf, length in rows:
750
+ denom = tf + BM25_K1 * (1.0 - BM25_B + BM25_B * (length / avgdl))
751
+ bm25[chunk_id] = bm25.get(chunk_id, 0.0) + qtf * idf * (tf * (BM25_K1 + 1.0)) / denom
752
+
753
+ # --- exact path (ported from the snapshot's exact_path, containment enforced) ---
754
+ exact_ids: set[int] = set()
755
+ qpath = _normalize_query_path(query)
756
+ if "/" in qpath or "." in qpath:
757
+ row = conn.execute(
758
+ "SELECT id FROM chunks WHERE path = ? ORDER BY ordinal LIMIT 1", (qpath,)
759
+ ).fetchone()
760
+ if row:
761
+ exact_ids.add(int(row[0]))
762
+
763
+ # --- dense (optional) ---
764
+ cosine: dict[int, float] = {}
765
+ vector_backend, use_sqlite_vec = _vector_backend(conn, kind)
766
+ dense_active = False
767
+ if kind == "dense" and not dense:
768
+ notes.append("dense ranking skipped for this request (lexical ranking only)")
769
+ elif kind == "dense":
770
+ dense, note = _load_dense_embedder(meta, embedder)
771
+ if dense is None:
772
+ notes.append(f"dense ranking disabled: {note}")
773
+ else:
774
+ dense_active = True
775
+ qvec = dense.embed([query], is_query=True)[0]
776
+ for chunk_id, sim in vector_search(conn, qvec, max(limit * 10, 50), use_sqlite_vec=use_sqlite_vec):
777
+ cosine[chunk_id] = sim
778
+ backend = _retrieval_backend(meta, dense_active)
779
+
780
+ # --- fuse ---
781
+ def ranked(scores: dict[int, float]) -> list[int]:
782
+ return [cid for cid, _ in sorted(scores.items(), key=lambda item: (-item[1], item[0]))]
783
+
784
+ if dense_active:
785
+ fused: dict[int, float] = {}
786
+ for ranking in (ranked(bm25)[:200], ranked(cosine)):
787
+ for position, cid in enumerate(ranking, start=1):
788
+ fused[cid] = fused.get(cid, 0.0) + 1.0 / (RRF_K + position)
789
+ final, score_kind = fused, "rrf"
790
+ else:
791
+ final, score_kind = dict(bm25), "bm25"
792
+ if exact_ids:
793
+ top = max(final.values(), default=0.0)
794
+ for cid in exact_ids:
795
+ final[cid] = top + 1.0
796
+
797
+ results: list[dict[str, Any]] = []
798
+ per_file: Counter[str] = Counter()
799
+ order = sorted(final.items(), key=lambda item: -item[1])
800
+ rows_by_id: dict[int, tuple] = {}
801
+ for chunk_id, score in order:
802
+ if len(results) >= limit:
803
+ break
804
+ if chunk_id not in rows_by_id:
805
+ row = conn.execute(
806
+ "SELECT path, start_line, end_line, text, symbols FROM chunks WHERE id = ?", (chunk_id,)
807
+ ).fetchone()
808
+ if row is None:
809
+ continue
810
+ rows_by_id[chunk_id] = row
811
+ path, start_line, end_line, text, symbols = rows_by_id[chunk_id]
812
+ if max_per_file and per_file[path] >= max_per_file:
813
+ continue
814
+ per_file[path] += 1
815
+ matched = []
816
+ if chunk_id in exact_ids:
817
+ matched.append("exact_path")
818
+ if chunk_id in bm25:
819
+ matched.append("bm25")
820
+ if chunk_id in cosine:
821
+ matched.append("dense")
822
+ snippet = text if max_chars is None or len(text) <= max_chars else text[:max_chars] + " ..."
823
+ results.append(
824
+ {
825
+ "rank": len(results) + 1,
826
+ "path": path,
827
+ "start_line": start_line,
828
+ "end_line": end_line,
829
+ "score": round(score, 6),
830
+ "score_kind": score_kind,
831
+ "components": {
832
+ "bm25": round(bm25[chunk_id], 6) if chunk_id in bm25 else None,
833
+ "cosine": round(cosine[chunk_id], 6) if chunk_id in cosine else None,
834
+ },
835
+ "matched_by": matched,
836
+ "backend": backend,
837
+ "symbols": [s for s in symbols.split("\n") if s],
838
+ "snippet": snippet,
839
+ }
840
+ )
841
+ if not tokenize(query) and not dense_active and not exact_ids:
842
+ notes.append("query produced no index terms (all stopwords or punctuation)")
843
+ freshness = compute_freshness(root_path, conn) if include_freshness else None
844
+ except sqlite3.DatabaseError as exc:
845
+ raise RetrievalError(_unreadable_message(root_path, exc)) from exc
846
+ finally:
847
+ conn.close()
848
+ if freshness and freshness["stale"]:
849
+ notes.append(
850
+ "index is STALE (" + "; ".join(freshness["stale_reasons"]) + "): verify results against the working tree"
851
+ " and rebuild with `python -m tools.cosmos retrieval build`"
852
+ )
853
+ return {
854
+ "schema": "cosmos.retrieval-search/1",
855
+ "query": query,
856
+ "root": str(root_path),
857
+ "backend": {
858
+ "retrieval_backend": backend,
859
+ "embedder": _embedder_block(meta.get("embedder_name", "?"), kind, meta.get("embedder_dimensions")),
860
+ "vector_backend": vector_backend,
861
+ "score_kind": score_kind,
862
+ },
863
+ "freshness": freshness,
864
+ "result_count": len(results),
865
+ "results": results,
866
+ "notes": notes,
867
+ }
868
+
869
+
870
+ __all__: Iterable[str] = (
871
+ "DEFAULT_MAX_FILE_BYTES",
872
+ "INDEX_RELATIVE_PATH",
873
+ "IndexMissingError",
874
+ "LexicalEmbedder",
875
+ "RetrievalConfigError",
876
+ "RetrievalError",
877
+ "build_index",
878
+ "compute_freshness",
879
+ "index_path_for",
880
+ "list_git_files",
881
+ "resolve_root",
882
+ "search",
883
+ "status",
884
+ )