scientific-computing-system 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (430) hide show
  1. package/.binder/postBuild +9 -0
  2. package/.binder/requirements.txt +10 -0
  3. package/.gitattributes +35 -0
  4. package/.github/CODEOWNERS +4 -0
  5. package/.github/FUNDING.yml +3 -0
  6. package/.github/ISSUE_TEMPLATE/bug_report.md +50 -0
  7. package/.github/ISSUE_TEMPLATE/config.yml +8 -0
  8. package/.github/ISSUE_TEMPLATE/feature_request.md +28 -0
  9. package/.github/PULL_REQUEST_TEMPLATE.md +29 -0
  10. package/.github/dependabot.yml +32 -0
  11. package/.github/labeler.yml +50 -0
  12. package/.github/workflows/benchmarks.yml +97 -0
  13. package/.github/workflows/bot-reviewer.yml +58 -0
  14. package/.github/workflows/changelog.yml +130 -0
  15. package/.github/workflows/cli-package-smoke.yml +45 -0
  16. package/.github/workflows/codeql.yml +55 -0
  17. package/.github/workflows/npm-publish.yml +33 -0
  18. package/.github/workflows/p08-cancel-noncanonical-runs.yml +41 -0
  19. package/.github/workflows/pr-automation.yml +78 -0
  20. package/.github/workflows/public-external-validation-p08-v2-glm.yml +161 -0
  21. package/.github/workflows/public-external-validation-p08-v2-recovery-merge-gate.yml +72 -0
  22. package/.github/workflows/public-external-validation-p08-v2-recovery-merge.yml +113 -0
  23. package/.github/workflows/public-external-validation-p08-v2-run-recovery-anatomy-gate.yml +57 -0
  24. package/.github/workflows/public-external-validation-p08-v2-run-recovery-merge-gate.yml +63 -0
  25. package/.github/workflows/public-external-validation-p08-v2-run-recovery-merge.yml +89 -0
  26. package/.github/workflows/public-external-validation-p08-v2-run-recovery.yml +182 -0
  27. package/.github/workflows/public-external-validation-p08-v3-glm-gate.yml +67 -0
  28. package/.github/workflows/public-external-validation-p08-v4-recovery-glm-gate.yml +78 -0
  29. package/.github/workflows/public-external-validation-p08-v4-recovery-glm.yml +248 -0
  30. package/.github/workflows/public-external-validation-p08-v5-run-recovery-glm-gate.yml +66 -0
  31. package/.github/workflows/public-external-validation-p08-v5-run-recovery-glm.yml +218 -0
  32. package/.github/workflows/pypi-registry-smoke.yml +116 -0
  33. package/.github/workflows/release.yml +359 -0
  34. package/.github/workflows/tests.yml +250 -0
  35. package/.github/workflows/tmp-compassion-raw-acquire.yml +63 -0
  36. package/.github/workflows/wsl-science-runner-smoke.yml +45 -0
  37. package/.pre-commit-config.yaml +48 -0
  38. package/CHANGELOG.md +1139 -0
  39. package/CITATION.cff +29 -0
  40. package/CODE_OF_CONDUCT.md +25 -0
  41. package/CONTRIBUTING.md +275 -0
  42. package/LICENSE +21 -0
  43. package/README.md +281 -0
  44. package/ROADMAP.md +155 -0
  45. package/SECURITY.md +82 -0
  46. package/assets/logo.svg +38 -0
  47. package/assets/social_preview.png +0 -0
  48. package/benchmarks/results.json +43 -0
  49. package/benchmarks/robust_runner.py +118 -0
  50. package/benchmarks/run_benchmarks.py +394 -0
  51. package/bin/scs.js +2 -0
  52. package/cliff.toml +100 -0
  53. package/dashboard/app.py +224 -0
  54. package/docs/ARCHITECTURE.md +252 -0
  55. package/docs/CASE_STUDY_HUBBLE.md +78 -0
  56. package/docs/CASE_STUDY_QUANTUM_ML.md +79 -0
  57. package/docs/api.md +133 -0
  58. package/docs/assets/icon.svg +17 -0
  59. package/docs/assets/logo.svg +38 -0
  60. package/docs/benchmarks.md +62 -0
  61. package/docs/cookbook.md +930 -0
  62. package/docs/getting-started.md +185 -0
  63. package/docs/index.md +111 -0
  64. package/docs/maintenance.md +61 -0
  65. package/docs/ml_reference.md +92 -0
  66. package/docs/research-workflows.md +82 -0
  67. package/docs/stylesheets/extra.css +122 -0
  68. package/docs/tour_of_numerical_methods.md +330 -0
  69. package/docs/tutorials/core_demo.md +35 -0
  70. package/docs/tutorials/data_analysis_demo.md +43 -0
  71. package/docs/tutorials/diffeq_demo.md +48 -0
  72. package/docs/tutorials/fft2_demo.md +67 -0
  73. package/docs/tutorials/graph_demo.md +45 -0
  74. package/docs/tutorials/hypothesis_demo.md +44 -0
  75. package/docs/tutorials/hypothesis_tests_demo.md +170 -0
  76. package/docs/tutorials/hypothesis_with_stats_demo.md +80 -0
  77. package/docs/tutorials/knowledge_demo.md +114 -0
  78. package/docs/tutorials/linalg_demo.md +103 -0
  79. package/docs/tutorials/math_utils_demo.md +46 -0
  80. package/docs/tutorials/ml_advanced_demo.md +96 -0
  81. package/docs/tutorials/ml_and_viz_demo.md +93 -0
  82. package/docs/tutorials/ml_demo.md +70 -0
  83. package/docs/tutorials/modeling_demo.md +82 -0
  84. package/docs/tutorials/montecarlo_demo.md +42 -0
  85. package/docs/tutorials/nlp_attention_demo.md +107 -0
  86. package/docs/tutorials/nlp_bpe_demo.md +103 -0
  87. package/docs/tutorials/nlp_mini_gpt_demo.md +110 -0
  88. package/docs/tutorials/nlp_viz.md +76 -0
  89. package/docs/tutorials/numerical_integration_demo.md +65 -0
  90. package/docs/tutorials/optimization_demo.md +106 -0
  91. package/docs/tutorials/pandas_io_demo.md +160 -0
  92. package/docs/tutorials/pca_demo.md +87 -0
  93. package/docs/tutorials/probability_demo.md +48 -0
  94. package/docs/tutorials/quantum_demo.md +31 -0
  95. package/docs/tutorials/quick_start.md +44 -0
  96. package/docs/tutorials/scientific_demo.md +46 -0
  97. package/docs/tutorials/signals_demo.md +167 -0
  98. package/docs/tutorials/stats_demo.md +94 -0
  99. package/docs/tutorials/stiff_ode_demo.md +84 -0
  100. package/docs/tutorials/time_series_demo.md +145 -0
  101. package/examples/core_demo.py +40 -0
  102. package/examples/data_analysis_demo.py +60 -0
  103. package/examples/diffeq_demo.py +34 -0
  104. package/examples/discovery_pipeline_demo.py +57 -0
  105. package/examples/ensemble_showcase.py +81 -0
  106. package/examples/fft2_demo.py +32 -0
  107. package/examples/graph_demo.py +49 -0
  108. package/examples/hypothesis_custom_generator.py +121 -0
  109. package/examples/hypothesis_demo.py +48 -0
  110. package/examples/hypothesis_tests_demo.py +52 -0
  111. package/examples/hypothesis_with_stats_demo.py +43 -0
  112. package/examples/interpolate_demo.py +57 -0
  113. package/examples/knowledge_demo.py +100 -0
  114. package/examples/linalg_demo.py +61 -0
  115. package/examples/math_utils_demo.py +53 -0
  116. package/examples/ml_and_viz_demo.py +47 -0
  117. package/examples/modeling_demo.py +110 -0
  118. package/examples/montecarlo_demo.py +41 -0
  119. package/examples/nlp_attention_demo.py +168 -0
  120. package/examples/nlp_bpe_demo.py +79 -0
  121. package/examples/nlp_mini_gpt_demo.py +76 -0
  122. package/examples/nlp_viz_demo.py +98 -0
  123. package/examples/numerical_integration_demo.py +60 -0
  124. package/examples/optimization_demo.py +34 -0
  125. package/examples/pca_demo.py +124 -0
  126. package/examples/pde_demo.py +65 -0
  127. package/examples/plot_demo.py +84 -0
  128. package/examples/plotting_notebook.ipynb +87 -0
  129. package/examples/probability_demo.py +39 -0
  130. package/examples/quantum_demo.py +42 -0
  131. package/examples/scientific_demo.py +49 -0
  132. package/examples/signals_demo.py +86 -0
  133. package/examples/stats_demo.py +40 -0
  134. package/examples/tour_of_numerical_methods.ipynb +497 -0
  135. package/index.js +1 -0
  136. package/mkdocs.yml +159 -0
  137. package/package.json +1 -0
  138. package/pyproject.toml +288 -0
  139. package/requirements-dev.lock +427 -0
  140. package/requirements-dev.txt +39 -0
  141. package/requirements.lock +6 -0
  142. package/requirements.txt +13 -0
  143. package/scripts/build_gif.py +111 -0
  144. package/scripts/build_video.py +214 -0
  145. package/scripts/cleanup_deployments.py +173 -0
  146. package/scripts/crop_readme_png.py +40 -0
  147. package/scripts/make_pi_dashboard.py +316 -0
  148. package/scripts/make_pi_gif.py +138 -0
  149. package/scripts/publish.py +203 -0
  150. package/scripts/render_promo.mjs +93 -0
  151. package/scripts/render_readme.py +211 -0
  152. package/scripts/render_readme_sections.py +168 -0
  153. package/scripts/verify_cli_install.py +99 -0
  154. package/scripts/verify_cookbook.py +601 -0
  155. package/scripts/verify_d1_numerics.py +504 -0
  156. package/scripts/verify_d2_edge_cases.py +442 -0
  157. package/scripts/verify_d4_hypothesis.py +337 -0
  158. package/scripts/verify_ml_reference.py +160 -0
  159. package/scripts/verify_pypi_release.py +97 -0
  160. package/scripts/verify_release_integrity.py +194 -0
  161. package/src/cds/__init__.py +132 -0
  162. package/src/cds/__main__.py +8 -0
  163. package/src/cds/_version.py +11 -0
  164. package/src/cds/bayes/__init__.py +25 -0
  165. package/src/cds/bayes/conjugate.py +560 -0
  166. package/src/cds/cli/__init__.py +104 -0
  167. package/src/cds/cli/__main__.py +8 -0
  168. package/src/cds/cli/_handlers.py +323 -0
  169. package/src/cds/cli/_parser.py +155 -0
  170. package/src/cds/cli/_style.py +208 -0
  171. package/src/cds/cli/_system_info.py +71 -0
  172. package/src/cds/core/__init__.py +5 -0
  173. package/src/cds/core/_numeric.py +92 -0
  174. package/src/cds/core/models.py +166 -0
  175. package/src/cds/data_analysis/__init__.py +30 -0
  176. package/src/cds/data_analysis/dataset.py +122 -0
  177. package/src/cds/data_analysis/loader.py +75 -0
  178. package/src/cds/data_analysis/pandas_io.py +108 -0
  179. package/src/cds/data_analysis/transform.py +36 -0
  180. package/src/cds/data_analysis/viz.py +88 -0
  181. package/src/cds/data_io/__init__.py +27 -0
  182. package/src/cds/data_io/streaming.py +314 -0
  183. package/src/cds/diffeq/__init__.py +37 -0
  184. package/src/cds/diffeq/_implicit.py +349 -0
  185. package/src/cds/diffeq/solvers.py +312 -0
  186. package/src/cds/diffeq/symplectic.py +225 -0
  187. package/src/cds/fractals/__init__.py +34 -0
  188. package/src/cds/fractals/sets.py +356 -0
  189. package/src/cds/genetics/__init__.py +22 -0
  190. package/src/cds/genetics/sequence.py +199 -0
  191. package/src/cds/graph/__init__.py +31 -0
  192. package/src/cds/graph/algorithms.py +399 -0
  193. package/src/cds/hypothesis/__init__.py +51 -0
  194. package/src/cds/hypothesis/evaluator.py +311 -0
  195. package/src/cds/hypothesis/generator.py +275 -0
  196. package/src/cds/hypothesis/mining.py +314 -0
  197. package/src/cds/infotheory/__init__.py +25 -0
  198. package/src/cds/infotheory/measures.py +276 -0
  199. package/src/cds/interpolate/__init__.py +156 -0
  200. package/src/cds/knowledge/__init__.py +45 -0
  201. package/src/cds/knowledge/graph.py +489 -0
  202. package/src/cds/knowledge/notes.py +231 -0
  203. package/src/cds/knowledge/retrieval.py +339 -0
  204. package/src/cds/math_utils/__init__.py +46 -0
  205. package/src/cds/math_utils/calculus.py +40 -0
  206. package/src/cds/math_utils/linalg.py +496 -0
  207. package/src/cds/math_utils/special.py +167 -0
  208. package/src/cds/math_utils/svd.py +261 -0
  209. package/src/cds/ml/__init__.py +60 -0
  210. package/src/cds/ml/boosting.py +304 -0
  211. package/src/cds/ml/clustering.py +190 -0
  212. package/src/cds/ml/decomposition.py +172 -0
  213. package/src/cds/ml/ensemble.py +152 -0
  214. package/src/cds/ml/linear_models.py +225 -0
  215. package/src/cds/ml/metrics.py +227 -0
  216. package/src/cds/ml/model_selection.py +150 -0
  217. package/src/cds/ml/naive_bayes.py +179 -0
  218. package/src/cds/ml/neighbors.py +162 -0
  219. package/src/cds/ml/neural.py +204 -0
  220. package/src/cds/ml/preprocessing.py +131 -0
  221. package/src/cds/ml/tree.py +228 -0
  222. package/src/cds/ml/voting.py +175 -0
  223. package/src/cds/modeling/__init__.py +44 -0
  224. package/src/cds/modeling/_base.py +210 -0
  225. package/src/cds/modeling/_nodes.py +526 -0
  226. package/src/cds/modeling/expression.py +81 -0
  227. package/src/cds/modeling/fitting.py +477 -0
  228. package/src/cds/modeling/model.py +134 -0
  229. package/src/cds/modeling/solver.py +187 -0
  230. package/src/cds/montecarlo/__init__.py +24 -0
  231. package/src/cds/montecarlo/markov.py +112 -0
  232. package/src/cds/montecarlo/methods.py +294 -0
  233. package/src/cds/nlp/__init__.py +170 -0
  234. package/src/cds/nlp/attention.py +285 -0
  235. package/src/cds/nlp/autograd/__init__.py +70 -0
  236. package/src/cds/nlp/autograd/_grad.py +120 -0
  237. package/src/cds/nlp/autograd/ops.py +133 -0
  238. package/src/cds/nlp/autograd/tensor.py +298 -0
  239. package/src/cds/nlp/bpe.py +449 -0
  240. package/src/cds/nlp/data.py +70 -0
  241. package/src/cds/nlp/embed.py +190 -0
  242. package/src/cds/nlp/layers.py +259 -0
  243. package/src/cds/nlp/model.py +456 -0
  244. package/src/cds/nlp/optim.py +163 -0
  245. package/src/cds/nlp/training.py +167 -0
  246. package/src/cds/nlp/viz.py +254 -0
  247. package/src/cds/numerical_integration/__init__.py +31 -0
  248. package/src/cds/numerical_integration/quadrature.py +480 -0
  249. package/src/cds/optimization/__init__.py +26 -0
  250. package/src/cds/optimization/_metaheuristics.py +287 -0
  251. package/src/cds/optimization/constrained.py +212 -0
  252. package/src/cds/optimization/minimize.py +425 -0
  253. package/src/cds/pde/__init__.py +266 -0
  254. package/src/cds/plot/__init__.py +49 -0
  255. package/src/cds/plot/_backend.py +32 -0
  256. package/src/cds/plot/charts.py +462 -0
  257. package/src/cds/probability/__init__.py +65 -0
  258. package/src/cds/probability/_advanced.py +283 -0
  259. package/src/cds/probability/distributions.py +236 -0
  260. package/src/cds/probability/extra_distributions.py +199 -0
  261. package/src/cds/provenance/__init__.py +25 -0
  262. package/src/cds/provenance/manifest.py +355 -0
  263. package/src/cds/py.typed +0 -0
  264. package/src/cds/quantum/__init__.py +51 -0
  265. package/src/cds/quantum/circuit.py +122 -0
  266. package/src/cds/quantum/multi_qubit.py +310 -0
  267. package/src/cds/quantum/simulator.py +53 -0
  268. package/src/cds/scientific/__init__.py +34 -0
  269. package/src/cds/scientific/constants.py +35 -0
  270. package/src/cds/scientific/formulas.py +116 -0
  271. package/src/cds/sensitivity.py +204 -0
  272. package/src/cds/signals/__init__.py +59 -0
  273. package/src/cds/signals/filters.py +449 -0
  274. package/src/cds/signals/processing.py +224 -0
  275. package/src/cds/signals/stft.py +177 -0
  276. package/src/cds/signals/wavelet.py +146 -0
  277. package/src/cds/stats/__init__.py +99 -0
  278. package/src/cds/stats/_distributions.py +102 -0
  279. package/src/cds/stats/bootstrap.py +188 -0
  280. package/src/cds/stats/descriptive.py +172 -0
  281. package/src/cds/stats/hypothesis_tests.py +294 -0
  282. package/src/cds/stats/nonparametric.py +141 -0
  283. package/src/cds/stats/power.py +290 -0
  284. package/src/cds/stats/regression.py +51 -0
  285. package/src/cds/stats/time_series.py +420 -0
  286. package/src/cds/tools/__init__.py +29 -0
  287. package/src/cds/tools/adapters.py +218 -0
  288. package/src/cds/tools/registry.py +181 -0
  289. package/src/cds/uncertainty/__init__.py +17 -0
  290. package/src/cds/uncertainty/propagation.py +233 -0
  291. package/src/cds/units/__init__.py +45 -0
  292. package/src/cds/units/core.py +199 -0
  293. package/src/cds/validation/__init__.py +41 -0
  294. package/src/cds/validation/adequacy.py +157 -0
  295. package/src/cds/validation/checks.py +485 -0
  296. package/src/cds/validation/report.py +50 -0
  297. package/src/cds/wavelets/__init__.py +5 -0
  298. package/src/cds/wavelets/haar.py +219 -0
  299. package/src/cds/workflow/__init__.py +77 -0
  300. package/src/cds/workflow/engine.py +116 -0
  301. package/src/cds/workflow/gates.py +120 -0
  302. package/src/cds/workflow/orchestrator.py +431 -0
  303. package/src/cds/workflow/selection.py +454 -0
  304. package/src/cds/workflow/tooling.py +155 -0
  305. package/src/cds/workflow/types.py +107 -0
  306. package/tests/__init__.py +0 -0
  307. package/tests/conftest.py +109 -0
  308. package/tests/test_advanced_fitting.py +247 -0
  309. package/tests/test_audit_completion_coverage.py +183 -0
  310. package/tests/test_audit_guard_coverage.py +115 -0
  311. package/tests/test_audit_hardening.py +138 -0
  312. package/tests/test_audit_hardening_coverage.py +111 -0
  313. package/tests/test_bayes_v2.py +208 -0
  314. package/tests/test_benchmarks.py +111 -0
  315. package/tests/test_bootstrap.py +135 -0
  316. package/tests/test_cli.py +51 -0
  317. package/tests/test_cli_color.py +114 -0
  318. package/tests/test_cli_extended.py +239 -0
  319. package/tests/test_cli_system_info.py +36 -0
  320. package/tests/test_constrained_opt.py +174 -0
  321. package/tests/test_core.py +273 -0
  322. package/tests/test_data_analysis.py +146 -0
  323. package/tests/test_data_analysis_lazy_bridge.py +68 -0
  324. package/tests/test_data_analysis_pandas_io.py +119 -0
  325. package/tests/test_data_io.py +149 -0
  326. package/tests/test_dataset.py +91 -0
  327. package/tests/test_diffeq.py +186 -0
  328. package/tests/test_diffeq_implicit.py +173 -0
  329. package/tests/test_domain_validation.py +66 -0
  330. package/tests/test_edge_misc_numerical.py +666 -0
  331. package/tests/test_edge_ml_quantum_linalg.py +191 -0
  332. package/tests/test_edge_nlp.py +229 -0
  333. package/tests/test_edge_quantum_evaluator_cli.py +601 -0
  334. package/tests/test_edge_stats_optimization_signals.py +406 -0
  335. package/tests/test_extra_distributions.py +206 -0
  336. package/tests/test_fft2.py +67 -0
  337. package/tests/test_fitting_bootstrap.py +202 -0
  338. package/tests/test_fractals.py +387 -0
  339. package/tests/test_genetics.py +159 -0
  340. package/tests/test_graph.py +380 -0
  341. package/tests/test_hardening_privacy_provenance.py +306 -0
  342. package/tests/test_hypothesis.py +216 -0
  343. package/tests/test_hypothesis_engine.py +59 -0
  344. package/tests/test_hypothesis_mining.py +247 -0
  345. package/tests/test_hypothesis_tests.py +277 -0
  346. package/tests/test_infotheory.py +302 -0
  347. package/tests/test_interpolate.py +189 -0
  348. package/tests/test_knowledge.py +1149 -0
  349. package/tests/test_layering.py +112 -0
  350. package/tests/test_linalg_extended.py +179 -0
  351. package/tests/test_linalg_qr_cholesky.py +68 -0
  352. package/tests/test_markov.py +155 -0
  353. package/tests/test_math_utils.py +157 -0
  354. package/tests/test_ml_boosting.py +148 -0
  355. package/tests/test_ml_clustering.py +92 -0
  356. package/tests/test_ml_ensemble.py +103 -0
  357. package/tests/test_ml_knn.py +95 -0
  358. package/tests/test_ml_linreg.py +70 -0
  359. package/tests/test_ml_logreg.py +84 -0
  360. package/tests/test_ml_metrics.py +125 -0
  361. package/tests/test_ml_model_selection.py +108 -0
  362. package/tests/test_ml_naive_bayes.py +183 -0
  363. package/tests/test_ml_pca.py +98 -0
  364. package/tests/test_ml_preprocessing.py +104 -0
  365. package/tests/test_ml_tree.py +89 -0
  366. package/tests/test_ml_viz.py +58 -0
  367. package/tests/test_ml_voting.py +219 -0
  368. package/tests/test_modeling.py +726 -0
  369. package/tests/test_modeling_fit_validation.py +46 -0
  370. package/tests/test_montecarlo.py +245 -0
  371. package/tests/test_multi_qubit.py +466 -0
  372. package/tests/test_nlp_attention.py +335 -0
  373. package/tests/test_nlp_autograd.py +435 -0
  374. package/tests/test_nlp_bpe.py +463 -0
  375. package/tests/test_nlp_embed.py +240 -0
  376. package/tests/test_nlp_layers.py +276 -0
  377. package/tests/test_nlp_model.py +172 -0
  378. package/tests/test_nlp_training.py +262 -0
  379. package/tests/test_nlp_viz.py +188 -0
  380. package/tests/test_numerical_integration.py +374 -0
  381. package/tests/test_numerical_invariants.py +768 -0
  382. package/tests/test_numerical_oracles.py +241 -0
  383. package/tests/test_optimization.py +139 -0
  384. package/tests/test_optimization_metaheuristics.py +221 -0
  385. package/tests/test_pde.py +294 -0
  386. package/tests/test_plot_charts.py +247 -0
  387. package/tests/test_plot_lazy.py +48 -0
  388. package/tests/test_power.py +226 -0
  389. package/tests/test_probability.py +274 -0
  390. package/tests/test_probability_advanced.py +226 -0
  391. package/tests/test_property_invariants.py +277 -0
  392. package/tests/test_provenance.py +215 -0
  393. package/tests/test_provenance_audit_hardening.py +45 -0
  394. package/tests/test_public_api.py +75 -0
  395. package/tests/test_quantum.py +195 -0
  396. package/tests/test_release_contract.py +105 -0
  397. package/tests/test_retrieval.py +255 -0
  398. package/tests/test_scientific.py +185 -0
  399. package/tests/test_selection_audit_hardening.py +55 -0
  400. package/tests/test_sensitivity.py +59 -0
  401. package/tests/test_sensitivity_global.py +73 -0
  402. package/tests/test_signals.py +146 -0
  403. package/tests/test_signals_filters.py +460 -0
  404. package/tests/test_special_invariants.py +222 -0
  405. package/tests/test_special_numerics.py +44 -0
  406. package/tests/test_statistical_audit.py +75 -0
  407. package/tests/test_stats.py +206 -0
  408. package/tests/test_stats_audit_coverage.py +17 -0
  409. package/tests/test_stats_nonparametric.py +87 -0
  410. package/tests/test_stats_time_series.py +352 -0
  411. package/tests/test_stft.py +208 -0
  412. package/tests/test_streaming_analytics.py +128 -0
  413. package/tests/test_svd.py +170 -0
  414. package/tests/test_symplectic.py +200 -0
  415. package/tests/test_tool_adapters.py +197 -0
  416. package/tests/test_tools_registry.py +132 -0
  417. package/tests/test_uncertainty.py +171 -0
  418. package/tests/test_units.py +139 -0
  419. package/tests/test_validation.py +100 -0
  420. package/tests/test_validation_adequacy.py +129 -0
  421. package/tests/test_validation_advanced.py +110 -0
  422. package/tests/test_wavelet.py +170 -0
  423. package/tests/test_wavelets_v2.py +119 -0
  424. package/tests/test_workflow.py +173 -0
  425. package/tests/test_workflow_gates.py +144 -0
  426. package/tests/test_workflow_orchestrator.py +516 -0
  427. package/tests/test_workflow_orchestrator_blocked_review.py +95 -0
  428. package/tests/test_workflow_selection.py +312 -0
  429. package/tests/test_workflow_selection_coverage.py +114 -0
  430. package/tests/test_workflow_tooling.py +190 -0
@@ -0,0 +1,1149 @@
1
+ """Tests for cds.knowledge — concept graphs, notes, and structured retrieval."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from pathlib import Path
7
+ from typing import cast
8
+
9
+ import pytest
10
+
11
+ from cds.knowledge import (
12
+ Concept,
13
+ KnowledgeGraph,
14
+ Note,
15
+ Notebook,
16
+ Relation,
17
+ SearchResult,
18
+ search,
19
+ search_concepts,
20
+ search_notes,
21
+ )
22
+ from cds.knowledge.retrieval import NAME_TAG_SCORE, SUBSTRING_SCORE
23
+
24
+ # ---------------------------------------------------------------------- #
25
+ # Concept
26
+ # ---------------------------------------------------------------------- #
27
+
28
+
29
+ class TestConcept:
30
+ def test_defaults_are_empty_not_none(self) -> None:
31
+ c = Concept("x")
32
+ assert c.name == "x"
33
+ assert c.description is None
34
+ assert c.tags == []
35
+ assert c.metadata == {}
36
+
37
+ def test_stores_fields(self) -> None:
38
+ c = Concept("x", description="d", tags=["a", "b"], metadata={"k": "v"})
39
+ assert c.description == "d"
40
+ assert c.tags == ["a", "b"]
41
+ assert c.metadata == {"k": "v"}
42
+
43
+ def test_equality_by_name(self) -> None:
44
+ assert Concept("x") == Concept("x", description="different")
45
+ assert Concept("x") != Concept("y")
46
+
47
+ def test_equality_with_non_concept(self) -> None:
48
+ assert Concept("x") != "x"
49
+ assert Concept("x") != 42
50
+ assert Concept("x") != None # noqa: E711
51
+
52
+ def test_hash_is_stable_and_name_based(self) -> None:
53
+ c1 = Concept("x", description="one")
54
+ c2 = Concept("x", description="two")
55
+ assert hash(c1) == hash(c2)
56
+ # Usable as a set member / dict key.
57
+ assert {c1, c2, Concept("y")} == {c1, Concept("y")}
58
+
59
+ def test_to_dict_roundtrips_fields(self) -> None:
60
+ c = Concept("x", description="d", tags=["a"], metadata={"k": "v"})
61
+ d = c.to_dict()
62
+ assert d == {"name": "x", "description": "d", "tags": ["a"], "metadata": {"k": "v"}}
63
+
64
+ def test_to_dict_copies_mutable_fields(self) -> None:
65
+ c = Concept("x", tags=["a"], metadata={"k": "v"})
66
+ d = c.to_dict()
67
+ cast(list[str], d["tags"]).append("b")
68
+ cast(dict[str, str], d["metadata"])["z"] = "1"
69
+ assert c.tags == ["a"]
70
+ assert c.metadata == {"k": "v"}
71
+
72
+ def test_from_dict_valid(self) -> None:
73
+ c = Concept.from_dict(
74
+ {"name": "x", "description": "d", "tags": ["a"], "metadata": {"k": "v"}}
75
+ )
76
+ assert c == Concept("x", description="d", tags=["a"], metadata={"k": "v"})
77
+
78
+ def test_from_dict_null_description(self) -> None:
79
+ c = Concept.from_dict({"name": "x", "description": None, "tags": [], "metadata": {}})
80
+ assert c.description is None
81
+
82
+ def test_from_dict_roundtrip(self) -> None:
83
+ original = Concept("x", description="d", tags=["a"], metadata={"k": "v"})
84
+ assert Concept.from_dict(original.to_dict()) == original
85
+
86
+ def test_from_dict_invalid_name_type(self) -> None:
87
+ with pytest.raises(ValueError, match="Invalid concept name"):
88
+ Concept.from_dict({"name": 123, "description": None, "tags": [], "metadata": {}})
89
+
90
+ def test_from_dict_invalid_description_type(self) -> None:
91
+ with pytest.raises(ValueError, match="Invalid concept description"):
92
+ Concept.from_dict({"name": "x", "description": 5, "tags": [], "metadata": {}})
93
+
94
+ def test_from_dict_invalid_tags_not_list(self) -> None:
95
+ with pytest.raises(ValueError, match="Invalid concept tags"):
96
+ Concept.from_dict({"name": "x", "description": None, "tags": "a", "metadata": {}})
97
+
98
+ def test_from_dict_invalid_tags_element(self) -> None:
99
+ with pytest.raises(ValueError, match="Invalid concept tags"):
100
+ Concept.from_dict({"name": "x", "description": None, "tags": [1], "metadata": {}})
101
+
102
+ def test_from_dict_invalid_metadata_not_dict(self) -> None:
103
+ with pytest.raises(ValueError, match="Invalid concept metadata"):
104
+ Concept.from_dict({"name": "x", "description": None, "tags": [], "metadata": []})
105
+
106
+ def test_from_dict_invalid_metadata_value_type(self) -> None:
107
+ with pytest.raises(ValueError, match="Invalid concept metadata"):
108
+ Concept.from_dict({"name": "x", "description": None, "tags": [], "metadata": {"k": 1}})
109
+
110
+ def test_from_dict_missing_key_raises(self) -> None:
111
+ with pytest.raises(KeyError):
112
+ Concept.from_dict({"description": None, "tags": [], "metadata": {}})
113
+
114
+
115
+ # ---------------------------------------------------------------------- #
116
+ # Relation
117
+ # ---------------------------------------------------------------------- #
118
+
119
+
120
+ class TestRelation:
121
+ def test_defaults_weight_to_one(self) -> None:
122
+ r = Relation("a", "b", "is-a")
123
+ assert r.weight == 1.0
124
+
125
+ def test_stores_fields(self) -> None:
126
+ r = Relation("a", "b", "is-a", weight=2.5)
127
+ assert r.source == "a"
128
+ assert r.target == "b"
129
+ assert r.kind == "is-a"
130
+ assert r.weight == 2.5
131
+
132
+ def test_to_dict(self) -> None:
133
+ r = Relation("a", "b", "is-a", weight=0.5)
134
+ assert r.to_dict() == {"source": "a", "target": "b", "kind": "is-a", "weight": 0.5}
135
+
136
+ def test_from_dict_valid(self) -> None:
137
+ r = Relation.from_dict({"source": "a", "target": "b", "kind": "is-a", "weight": 1.0})
138
+ assert r == Relation("a", "b", "is-a", weight=1.0)
139
+
140
+ def test_from_dict_coerces_int_weight_to_float(self) -> None:
141
+ r = Relation.from_dict({"source": "a", "target": "b", "kind": "is-a", "weight": 3})
142
+ assert r.weight == 3.0
143
+ assert isinstance(r.weight, float)
144
+
145
+ def test_from_dict_roundtrip(self) -> None:
146
+ original = Relation("a", "b", "is-a", weight=0.5)
147
+ assert Relation.from_dict(original.to_dict()) == original
148
+
149
+ def test_from_dict_invalid_source(self) -> None:
150
+ with pytest.raises(ValueError, match="Invalid relation source"):
151
+ Relation.from_dict({"source": 1, "target": "b", "kind": "is-a", "weight": 1.0})
152
+
153
+ def test_from_dict_invalid_target(self) -> None:
154
+ with pytest.raises(ValueError, match="Invalid relation target"):
155
+ Relation.from_dict({"source": "a", "target": 1, "kind": "is-a", "weight": 1.0})
156
+
157
+ def test_from_dict_invalid_kind(self) -> None:
158
+ with pytest.raises(ValueError, match="Invalid relation kind"):
159
+ Relation.from_dict({"source": "a", "target": "b", "kind": 1, "weight": 1.0})
160
+
161
+ def test_from_dict_invalid_weight_type(self) -> None:
162
+ with pytest.raises(ValueError, match="Invalid relation weight"):
163
+ Relation.from_dict({"source": "a", "target": "b", "kind": "is-a", "weight": "x"})
164
+
165
+ def test_from_dict_rejects_bool_weight(self) -> None:
166
+ with pytest.raises(ValueError, match="Invalid relation weight"):
167
+ Relation.from_dict({"source": "a", "target": "b", "kind": "is-a", "weight": True})
168
+
169
+ def test_from_dict_missing_key_raises(self) -> None:
170
+ with pytest.raises(KeyError):
171
+ Relation.from_dict({"source": "a", "target": "b", "kind": "is-a"})
172
+
173
+
174
+ # ---------------------------------------------------------------------- #
175
+ # KnowledgeGraph — construction
176
+ # ---------------------------------------------------------------------- #
177
+
178
+
179
+ class TestGraphConstruction:
180
+ def test_empty_graph(self) -> None:
181
+ kg = KnowledgeGraph(name="empty")
182
+ assert kg.concepts == {}
183
+ assert kg.relations == []
184
+
185
+ def test_add_concept_returns_stored_node(self) -> None:
186
+ kg = KnowledgeGraph(name="g")
187
+ c = kg.add_concept("x", description="d", tags=["t"], metadata={"k": "v"})
188
+ assert c is kg.concepts["x"]
189
+ assert c.name == "x"
190
+ assert c.description == "d"
191
+
192
+ def test_add_concept_is_idempotent(self) -> None:
193
+ kg = KnowledgeGraph(name="g")
194
+ first = kg.add_concept("x", description="first")
195
+ second = kg.add_concept("x", description="second")
196
+ assert first is second
197
+ assert second.description == "first" # not overwritten
198
+
199
+ def test_add_concept_tags_default_empty_list(self) -> None:
200
+ kg = KnowledgeGraph(name="g")
201
+ c = kg.add_concept("x")
202
+ assert c.tags == []
203
+ assert c.metadata == {}
204
+
205
+ def test_add_concept_copies_input_collections(self) -> None:
206
+ kg = KnowledgeGraph(name="g")
207
+ tags = ["a"]
208
+ meta = {"k": "v"}
209
+ c = kg.add_concept("x", tags=tags, metadata=meta)
210
+ tags.append("b")
211
+ meta["z"] = "1"
212
+ assert c.tags == ["a"]
213
+ assert c.metadata == {"k": "v"}
214
+
215
+ def test_add_relation_requires_known_endpoints(self) -> None:
216
+ kg = KnowledgeGraph(name="g")
217
+ kg.add_concept("a")
218
+ kg.add_concept("b")
219
+ r = kg.add_relation("a", "b", "is-a", weight=2.0)
220
+ assert r in kg.relations
221
+ assert r.weight == 2.0
222
+
223
+ def test_add_relation_unknown_source_raises(self) -> None:
224
+ kg = KnowledgeGraph(name="g")
225
+ kg.add_concept("b")
226
+ with pytest.raises(KeyError, match="unknown source concept"):
227
+ kg.add_relation("missing", "b", "is-a")
228
+
229
+ def test_add_relation_unknown_target_raises(self) -> None:
230
+ kg = KnowledgeGraph(name="g")
231
+ kg.add_concept("a")
232
+ with pytest.raises(KeyError, match="unknown target concept"):
233
+ kg.add_relation("a", "missing", "is-a")
234
+
235
+ def test_link_concepts_creates_missing(self) -> None:
236
+ kg = KnowledgeGraph(name="g")
237
+ kg.link_concepts("a", "b", "is-a")
238
+ assert "a" in kg.concepts
239
+ assert "b" in kg.concepts
240
+ assert len(kg.relations) == 1
241
+
242
+ def test_link_concepts_reuses_existing(self) -> None:
243
+ kg = KnowledgeGraph(name="g")
244
+ kg.add_concept("a", description="keep")
245
+ kg.link_concepts("a", "b", "is-a")
246
+ # Existing concept is preserved (idempotent add).
247
+ assert kg.concepts["a"].description == "keep"
248
+
249
+
250
+ # ---------------------------------------------------------------------- #
251
+ # KnowledgeGraph — neighbor queries
252
+ # ---------------------------------------------------------------------- #
253
+
254
+
255
+ class TestGraphNeighbors:
256
+ def _graph(self) -> KnowledgeGraph:
257
+ # a --is-a--> b --is-a--> c
258
+ # a --related-to--> c
259
+ kg = KnowledgeGraph(name="g")
260
+ kg.add_concept("a")
261
+ kg.add_concept("b")
262
+ kg.add_concept("c")
263
+ kg.add_relation("a", "b", "is-a")
264
+ kg.add_relation("b", "c", "is-a")
265
+ kg.add_relation("a", "c", "related-to")
266
+ return kg
267
+
268
+ def test_neighbors_undirected_both_directions(self) -> None:
269
+ kg = self._graph()
270
+ assert set(kg.neighbors("a")) == {"b", "c"}
271
+ assert set(kg.neighbors("b")) == {"a", "c"}
272
+ assert set(kg.neighbors("c")) == {"a", "b"}
273
+
274
+ def test_neighbors_filtered_by_kind(self) -> None:
275
+ kg = self._graph()
276
+ assert set(kg.neighbors("a", kind="is-a")) == {"b"}
277
+ assert set(kg.neighbors("a", kind="related-to")) == {"c"}
278
+ assert kg.neighbors("a", kind="nonexistent") == []
279
+
280
+ def test_neighbors_dedupes(self) -> None:
281
+ kg = KnowledgeGraph(name="g")
282
+ kg.add_concept("a")
283
+ kg.add_concept("b")
284
+ # Two relations between the same pair: b should appear once.
285
+ kg.add_relation("a", "b", "is-a")
286
+ kg.add_relation("b", "a", "related-to")
287
+ assert kg.neighbors("a") == ["b"]
288
+
289
+ def test_neighbors_unknown_concept_raises(self) -> None:
290
+ kg = self._graph()
291
+ with pytest.raises(KeyError, match="unknown concept"):
292
+ kg.neighbors("missing")
293
+
294
+ def test_neighbors_out_only_outgoing(self) -> None:
295
+ kg = self._graph()
296
+ assert set(kg.neighbors_out("a")) == {"b", "c"}
297
+ assert kg.neighbors_out("b") == ["c"]
298
+ assert kg.neighbors_out("c") == []
299
+
300
+ def test_neighbors_out_filtered_by_kind(self) -> None:
301
+ kg = self._graph()
302
+ assert kg.neighbors_out("a", kind="is-a") == ["b"]
303
+ assert kg.neighbors_out("a", kind="related-to") == ["c"]
304
+
305
+ def test_neighbors_out_unknown_raises(self) -> None:
306
+ kg = self._graph()
307
+ with pytest.raises(KeyError, match="unknown concept"):
308
+ kg.neighbors_out("missing")
309
+
310
+ def test_neighbors_in_only_incoming(self) -> None:
311
+ kg = self._graph()
312
+ assert kg.neighbors_in("a") == []
313
+ assert set(kg.neighbors_in("b")) == {"a"}
314
+ assert set(kg.neighbors_in("c")) == {"a", "b"}
315
+
316
+ def test_neighbors_in_filtered_by_kind(self) -> None:
317
+ kg = self._graph()
318
+ assert kg.neighbors_in("c", kind="is-a") == ["b"]
319
+ assert kg.neighbors_in("c", kind="related-to") == ["a"]
320
+
321
+ def test_neighbors_in_unknown_raises(self) -> None:
322
+ kg = self._graph()
323
+ with pytest.raises(KeyError, match="unknown concept"):
324
+ kg.neighbors_in("missing")
325
+
326
+
327
+ # ---------------------------------------------------------------------- #
328
+ # KnowledgeGraph — traversal (path, reachability, cycles)
329
+ # ---------------------------------------------------------------------- #
330
+
331
+
332
+ class TestGraphTraversal:
333
+ def test_find_path_source_equals_target(self) -> None:
334
+ kg = KnowledgeGraph(name="g")
335
+ kg.add_concept("a")
336
+ assert kg.find_path("a", "a") == ["a"]
337
+
338
+ def test_find_path_direct_neighbor(self) -> None:
339
+ kg = KnowledgeGraph(name="g")
340
+ kg.link_concepts("a", "b", "is-a")
341
+ assert kg.find_path("a", "b") == ["a", "b"]
342
+
343
+ def test_find_path_multi_hop(self) -> None:
344
+ kg = KnowledgeGraph(name="g")
345
+ for pair in [("a", "b"), ("b", "c"), ("c", "d")]:
346
+ kg.link_concepts(*pair, kind="is-a")
347
+ assert kg.find_path("a", "d") == ["a", "b", "c", "d"]
348
+
349
+ def test_find_path_traverses_against_direction(self) -> None:
350
+ # Only edge is b -> a; path from a to b must go "backwards".
351
+ kg = KnowledgeGraph(name="g")
352
+ kg.add_concept("a")
353
+ kg.add_concept("b")
354
+ kg.add_relation("b", "a", "is-a")
355
+ assert kg.find_path("a", "b") == ["a", "b"]
356
+
357
+ def test_find_path_no_connection_returns_none(self) -> None:
358
+ kg = KnowledgeGraph(name="g")
359
+ kg.add_concept("a")
360
+ kg.add_concept("b")
361
+ assert kg.find_path("a", "b") is None
362
+
363
+ def test_find_path_unknown_source_returns_none(self) -> None:
364
+ kg = KnowledgeGraph(name="g")
365
+ kg.add_concept("a")
366
+ assert kg.find_path("missing", "a") is None
367
+
368
+ def test_find_path_unknown_target_returns_none(self) -> None:
369
+ kg = KnowledgeGraph(name="g")
370
+ kg.add_concept("a")
371
+ assert kg.find_path("a", "missing") is None
372
+
373
+ def test_find_path_returns_shortest(self) -> None:
374
+ # Triangle: a-b-c plus a direct shortcut a-c.
375
+ kg = KnowledgeGraph(name="g")
376
+ kg.link_concepts("a", "b", "is-a")
377
+ kg.link_concepts("b", "c", "is-a")
378
+ kg.link_concepts("a", "c", "is-a")
379
+ # BFS finds the 2-hop [a, c] via the shortcut, not [a,b,c].
380
+ assert len(kg.find_path("a", "c") or []) == 2 # noqa: PLR2004
381
+
382
+ def test_reachable_includes_self(self) -> None:
383
+ kg = KnowledgeGraph(name="g")
384
+ kg.add_concept("a")
385
+ assert kg.reachable("a") == {"a"}
386
+
387
+ def test_reachable_traverses_graph(self) -> None:
388
+ kg = KnowledgeGraph(name="g")
389
+ kg.link_concepts("a", "b", "is-a")
390
+ kg.link_concepts("b", "c", "is-a")
391
+ assert kg.reachable("a") == {"a", "b", "c"}
392
+
393
+ def test_reachable_unknown_concept_returns_empty(self) -> None:
394
+ kg = KnowledgeGraph(name="g")
395
+ assert kg.reachable("missing") == set()
396
+
397
+ def test_find_cycles_empty(self) -> None:
398
+ kg = KnowledgeGraph(name="g")
399
+ kg.link_concepts("a", "b", "is-a")
400
+ assert kg.find_cycles() == []
401
+
402
+ def test_find_cycles_simple_triangle(self) -> None:
403
+ kg = KnowledgeGraph(name="g")
404
+ kg.link_concepts("a", "b", "is-a")
405
+ kg.link_concepts("b", "c", "is-a")
406
+ kg.link_concepts("c", "a", "is-a")
407
+ cycles = kg.find_cycles()
408
+ assert cycles == [["a", "b", "c"]]
409
+
410
+ def test_find_cycles_normalized_to_smallest_member(self) -> None:
411
+ # Same cycle entered from different nodes collapses to one entry.
412
+ kg = KnowledgeGraph(name="g")
413
+ kg.link_concepts("c", "a", "is-a") # entered via c first
414
+ kg.link_concepts("a", "b", "is-a")
415
+ kg.link_concepts("b", "c", "is-a")
416
+ cycles = kg.find_cycles()
417
+ assert cycles == [["a", "b", "c"]]
418
+
419
+ def test_find_cycles_self_loop(self) -> None:
420
+ kg = KnowledgeGraph(name="g")
421
+ kg.add_concept("a")
422
+ kg.add_relation("a", "a", "is-a")
423
+ assert kg.find_cycles() == [["a"]]
424
+
425
+ def test_find_cycles_multiple_distinct(self) -> None:
426
+ kg = KnowledgeGraph(name="g")
427
+ for n in ["a", "b", "c", "d", "e", "f"]:
428
+ kg.add_concept(n)
429
+ # Cycle 1: a -> b -> c -> a
430
+ kg.add_relation("a", "b", "is-a")
431
+ kg.add_relation("b", "c", "is-a")
432
+ kg.add_relation("c", "a", "is-a")
433
+ # Cycle 2: d -> e -> f -> d
434
+ kg.add_relation("d", "e", "is-a")
435
+ kg.add_relation("e", "f", "is-a")
436
+ kg.add_relation("f", "d", "is-a")
437
+ cycles = kg.find_cycles()
438
+ assert cycles == [["a", "b", "c"], ["d", "e", "f"]]
439
+
440
+ def test_find_cycles_does_not_hit_recursion_limit(self) -> None:
441
+ # A long chain with a closing edge back to the start.
442
+ n = 5000
443
+ kg = KnowledgeGraph(name="deep")
444
+ for i in range(n):
445
+ kg.add_concept(f"c{i}")
446
+ for i in range(n - 1):
447
+ kg.add_relation(f"c{i}", f"c{i + 1}", "is-a")
448
+ kg.add_relation(f"c{n - 1}", "c0", "is-a") # close the loop
449
+ cycles = kg.find_cycles()
450
+ assert len(cycles) == 1
451
+ assert len(cycles[0]) == n
452
+ assert cycles[0][0] == "c0"
453
+
454
+
455
+ # ---------------------------------------------------------------------- #
456
+ # KnowledgeGraph — rendering & serialization
457
+ # ---------------------------------------------------------------------- #
458
+
459
+
460
+ class TestGraphRendering:
461
+ def test_to_markdown_full(self) -> None:
462
+ kg = KnowledgeGraph(name="My Graph")
463
+ kg.link_concepts("a", "b", "is-a")
464
+ md = kg.to_markdown()
465
+ assert "# Knowledge Graph: My Graph" in md
466
+ assert "## Concepts" in md
467
+ assert "## Relations" in md
468
+ assert "**a**" in md
469
+ assert "`a` --is-a--> `b`" in md
470
+
471
+ def test_to_markdown_no_concepts(self) -> None:
472
+ kg = KnowledgeGraph(name="empty")
473
+ md = kg.to_markdown()
474
+ assert "_No concepts._" in md
475
+ assert "_No relations._" in md
476
+
477
+ def test_to_markdown_concepts_sorted(self) -> None:
478
+ kg = KnowledgeGraph(name="g")
479
+ kg.add_concept("zeta")
480
+ kg.add_concept("alpha")
481
+ md = kg.to_markdown()
482
+ assert md.index("**alpha**") < md.index("**zeta**")
483
+
484
+ def test_to_dict_structure(self) -> None:
485
+ kg = KnowledgeGraph(name="g")
486
+ kg.link_concepts("a", "b", "is-a")
487
+ d = kg.to_dict()
488
+ assert d["name"] == "g"
489
+ concepts = cast(list[dict[str, object]], d["concepts"])
490
+ assert [c["name"] for c in concepts] == ["a", "b"]
491
+ relations = cast(list[dict[str, object]], d["relations"])
492
+ assert relations[0]["kind"] == "is-a"
493
+
494
+ def test_from_dict_roundtrip(self) -> None:
495
+ kg = KnowledgeGraph(name="g")
496
+ kg.add_concept("a", description="d", tags=["t"])
497
+ kg.link_concepts("a", "b", "is-a", weight=2.0)
498
+ rebuilt = KnowledgeGraph.from_dict(kg.to_dict())
499
+ assert rebuilt.name == "g"
500
+ assert set(rebuilt.concepts) == {"a", "b"}
501
+ assert rebuilt.concepts["a"].description == "d"
502
+ assert len(rebuilt.relations) == 1
503
+ assert rebuilt.relations[0].weight == 2.0
504
+
505
+ def test_from_dict_preserves_concept_order(self) -> None:
506
+ kg = KnowledgeGraph(name="g")
507
+ kg.add_concept("z")
508
+ kg.add_concept("a")
509
+ rebuilt = KnowledgeGraph.from_dict(kg.to_dict())
510
+ # concepts dict preserves insertion order from the serialized list.
511
+ assert list(rebuilt.concepts.keys()) == ["z", "a"]
512
+
513
+ def test_from_dict_invalid_name(self) -> None:
514
+ with pytest.raises(ValueError, match="Invalid graph name"):
515
+ KnowledgeGraph.from_dict({"name": 1, "concepts": [], "relations": []})
516
+
517
+ def test_from_dict_invalid_concepts_list(self) -> None:
518
+ with pytest.raises(ValueError, match="Invalid concepts list"):
519
+ KnowledgeGraph.from_dict({"name": "g", "concepts": "x", "relations": []})
520
+
521
+ def test_from_dict_invalid_relations_list(self) -> None:
522
+ with pytest.raises(ValueError, match="Invalid relations list"):
523
+ KnowledgeGraph.from_dict({"name": "g", "concepts": [], "relations": "x"})
524
+
525
+ def test_from_dict_invalid_concept_entry(self) -> None:
526
+ with pytest.raises(ValueError, match="Invalid concept entry"):
527
+ KnowledgeGraph.from_dict({"name": "g", "concepts": ["not-a-dict"], "relations": []})
528
+
529
+ def test_from_dict_invalid_relation_entry(self) -> None:
530
+ with pytest.raises(ValueError, match="Invalid relation entry"):
531
+ KnowledgeGraph.from_dict({"name": "g", "concepts": [], "relations": ["x"]})
532
+
533
+ def test_save_load_roundtrip(self, tmp_path: Path) -> None:
534
+ kg = KnowledgeGraph(name="g")
535
+ kg.link_concepts("a", "b", "is-a")
536
+ path = tmp_path / "kg.json"
537
+ kg.save(path)
538
+ loaded = KnowledgeGraph.load(path)
539
+ assert set(loaded.concepts) == {"a", "b"}
540
+ assert len(loaded.relations) == 1
541
+
542
+ def test_save_writes_indented_utf8_json(self, tmp_path) -> None: # type: ignore[no-untyped-def]
543
+ kg = KnowledgeGraph(name="g")
544
+ kg.add_concept("λ") # non-ASCII to verify ensure_ascii=False
545
+ path = tmp_path / "kg.json"
546
+ kg.save(path)
547
+ text = path.read_text(encoding="utf-8")
548
+ assert "λ" in text
549
+ assert "\n" in text # indented
550
+
551
+ def test_load_non_dict_raises(self, tmp_path) -> None: # type: ignore[no-untyped-def]
552
+ path = tmp_path / "bad.json"
553
+ path.write_text("[1, 2, 3]", encoding="utf-8")
554
+ with pytest.raises(ValueError, match="Invalid graph file"):
555
+ KnowledgeGraph.load(path)
556
+
557
+ def test_load_roundtrips_loaded_via_json_module(self, tmp_path) -> None: # type: ignore[no-untyped-def]
558
+ # Ensure the persisted form is plain JSON any reader can parse.
559
+ kg = KnowledgeGraph(name="g")
560
+ kg.link_concepts("a", "b", "is-a")
561
+ path = tmp_path / "kg.json"
562
+ kg.save(path)
563
+ raw = json.loads(path.read_text(encoding="utf-8"))
564
+ assert raw["name"] == "g"
565
+
566
+
567
+ # ---------------------------------------------------------------------- #
568
+ # Note
569
+ # ---------------------------------------------------------------------- #
570
+
571
+
572
+ class TestNote:
573
+ def test_defaults(self) -> None:
574
+ n = Note(id="n1", title="t", body="b")
575
+ assert n.tags == []
576
+ assert n.linked_concepts == []
577
+ assert n.created is None
578
+
579
+ def test_to_dict(self) -> None:
580
+ n = Note(id="n1", title="t", body="b", tags=["x"], linked_concepts=["c"], created="2024")
581
+ assert n.to_dict() == {
582
+ "id": "n1",
583
+ "title": "t",
584
+ "body": "b",
585
+ "tags": ["x"],
586
+ "linked_concepts": ["c"],
587
+ "created": "2024",
588
+ }
589
+
590
+ def test_to_dict_copies_mutable_fields(self) -> None:
591
+ n = Note(id="n1", title="t", body="b", tags=["x"], linked_concepts=["c"])
592
+ d = n.to_dict()
593
+ cast(list[str], d["tags"]).append("y")
594
+ cast(list[str], d["linked_concepts"]).append("z")
595
+ assert n.tags == ["x"]
596
+ assert n.linked_concepts == ["c"]
597
+
598
+ def test_from_dict_valid(self) -> None:
599
+ n = Note.from_dict(
600
+ {
601
+ "id": "n1",
602
+ "title": "t",
603
+ "body": "b",
604
+ "tags": ["x"],
605
+ "linked_concepts": ["c"],
606
+ "created": "2024",
607
+ }
608
+ )
609
+ assert n.id == "n1"
610
+ assert n.tags == ["x"]
611
+ assert n.created == "2024"
612
+
613
+ def test_from_dict_null_created(self) -> None:
614
+ n = Note.from_dict(
615
+ {
616
+ "id": "n1",
617
+ "title": "t",
618
+ "body": "b",
619
+ "tags": [],
620
+ "linked_concepts": [],
621
+ "created": None,
622
+ }
623
+ )
624
+ assert n.created is None
625
+
626
+ def test_from_dict_roundtrip(self) -> None:
627
+ original = Note(
628
+ id="n1", title="t", body="b", tags=["x"], linked_concepts=["c"], created="2024"
629
+ )
630
+ rebuilt = Note.from_dict(original.to_dict())
631
+ assert rebuilt.id == original.id
632
+ assert rebuilt.tags == original.tags
633
+
634
+ def test_from_dict_invalid_id(self) -> None:
635
+ with pytest.raises(ValueError, match="Invalid note id"):
636
+ Note.from_dict(
637
+ {
638
+ "id": 1,
639
+ "title": "t",
640
+ "body": "b",
641
+ "tags": [],
642
+ "linked_concepts": [],
643
+ "created": None,
644
+ }
645
+ )
646
+
647
+ def test_from_dict_invalid_title(self) -> None:
648
+ with pytest.raises(ValueError, match="Invalid note title"):
649
+ Note.from_dict(
650
+ {
651
+ "id": "n1",
652
+ "title": 1,
653
+ "body": "b",
654
+ "tags": [],
655
+ "linked_concepts": [],
656
+ "created": None,
657
+ }
658
+ )
659
+
660
+ def test_from_dict_invalid_body(self) -> None:
661
+ with pytest.raises(ValueError, match="Invalid note body"):
662
+ Note.from_dict(
663
+ {
664
+ "id": "n1",
665
+ "title": "t",
666
+ "body": 1,
667
+ "tags": [],
668
+ "linked_concepts": [],
669
+ "created": None,
670
+ }
671
+ )
672
+
673
+ def test_from_dict_invalid_tags(self) -> None:
674
+ with pytest.raises(ValueError, match="Invalid note tags"):
675
+ Note.from_dict(
676
+ {
677
+ "id": "n1",
678
+ "title": "t",
679
+ "body": "b",
680
+ "tags": [1],
681
+ "linked_concepts": [],
682
+ "created": None,
683
+ }
684
+ )
685
+
686
+ def test_from_dict_invalid_linked_concepts(self) -> None:
687
+ with pytest.raises(ValueError, match="Invalid note linked_concepts"):
688
+ Note.from_dict(
689
+ {
690
+ "id": "n1",
691
+ "title": "t",
692
+ "body": "b",
693
+ "tags": [],
694
+ "linked_concepts": [1],
695
+ "created": None,
696
+ }
697
+ )
698
+
699
+ def test_from_dict_invalid_created(self) -> None:
700
+ with pytest.raises(ValueError, match="Invalid note created"):
701
+ Note.from_dict(
702
+ {
703
+ "id": "n1",
704
+ "title": "t",
705
+ "body": "b",
706
+ "tags": [],
707
+ "linked_concepts": [],
708
+ "created": 2024,
709
+ }
710
+ )
711
+
712
+ def test_from_dict_missing_key_raises(self) -> None:
713
+ with pytest.raises(KeyError):
714
+ Note.from_dict(
715
+ {"title": "t", "body": "b", "tags": [], "linked_concepts": [], "created": None}
716
+ )
717
+
718
+ def test_to_markdown_with_all_fields(self) -> None:
719
+ n = Note(
720
+ id="n1",
721
+ title="t",
722
+ body="b",
723
+ tags=["x", "y"],
724
+ linked_concepts=["c1", "c2"],
725
+ created="2024",
726
+ )
727
+ md = n.to_markdown()
728
+ assert md.startswith("# t")
729
+ assert "_Created: 2024_" in md
730
+ assert "`x`" in md and "`y`" in md
731
+ assert "## Linked concepts" in md
732
+ assert "`c1`" in md
733
+ assert md.rstrip().endswith("b") is False or "b" in md # body present
734
+
735
+ def test_to_markdown_minimal(self) -> None:
736
+ n = Note(id="n1", title="t", body="b")
737
+ md = n.to_markdown()
738
+ assert "_Created:" not in md
739
+ assert "Tags:" not in md
740
+ assert "## Linked concepts" not in md
741
+
742
+
743
+ # ---------------------------------------------------------------------- #
744
+ # Notebook
745
+ # ---------------------------------------------------------------------- #
746
+
747
+
748
+ class TestNotebook:
749
+ def test_add_note_returns_stored(self) -> None:
750
+ nb = Notebook(name="nb")
751
+ n = nb.add_note("n1", "title", "body", tags=["t"], linked_concepts=["c"], created="2024")
752
+ assert n is nb.notes["n1"]
753
+ assert n.title == "title"
754
+
755
+ def test_add_note_overwrites_existing(self) -> None:
756
+ nb = Notebook(name="nb")
757
+ nb.add_note("n1", "first", "b1")
758
+ nb.add_note("n1", "second", "b2")
759
+ assert len(nb.notes) == 1
760
+ assert nb.notes["n1"].title == "second"
761
+
762
+ def test_add_note_defaults_empty_collections(self) -> None:
763
+ nb = Notebook(name="nb")
764
+ n = nb.add_note("n1", "t", "b")
765
+ assert n.tags == []
766
+ assert n.linked_concepts == []
767
+ assert n.created is None
768
+
769
+ def test_add_note_copies_input_collections(self) -> None:
770
+ nb = Notebook(name="nb")
771
+ tags = ["a"]
772
+ linked = ["c"]
773
+ n = nb.add_note("n1", "t", "b", tags=tags, linked_concepts=linked)
774
+ tags.append("b")
775
+ linked.append("d")
776
+ assert n.tags == ["a"]
777
+ assert n.linked_concepts == ["c"]
778
+
779
+ def test_get_note_found(self) -> None:
780
+ nb = Notebook(name="nb")
781
+ nb.add_note("n1", "t", "b")
782
+ assert nb.get_note("n1").title == "t"
783
+
784
+ def test_get_note_unknown_raises(self) -> None:
785
+ nb = Notebook(name="nb")
786
+ with pytest.raises(KeyError, match="unknown note"):
787
+ nb.get_note("missing")
788
+
789
+ def test_notes_for_concept(self) -> None:
790
+ nb = Notebook(name="nb")
791
+ nb.add_note("n1", "t1", "b", linked_concepts=["c1", "c2"])
792
+ nb.add_note("n2", "t2", "b", linked_concepts=["c2"])
793
+ nb.add_note("n3", "t3", "b", linked_concepts=[])
794
+ assert [n.id for n in nb.notes_for_concept("c2")] == ["n1", "n2"]
795
+ assert nb.notes_for_concept("c1") == [nb.notes["n1"]]
796
+ assert nb.notes_for_concept("absent") == []
797
+
798
+ def test_notes_by_tag(self) -> None:
799
+ nb = Notebook(name="nb")
800
+ nb.add_note("n1", "t1", "b", tags=["exp", "fail"])
801
+ nb.add_note("n2", "t2", "b", tags=["exp"])
802
+ assert [n.id for n in nb.notes_by_tag("exp")] == ["n1", "n2"]
803
+ assert nb.notes_by_tag("fail") == [nb.notes["n1"]]
804
+ assert nb.notes_by_tag("absent") == []
805
+
806
+ def test_to_markdown_empty(self) -> None:
807
+ nb = Notebook(name="empty")
808
+ md = nb.to_markdown()
809
+ assert "# Notebook: empty" in md
810
+ assert "_No notes._" in md
811
+
812
+ def test_to_markdown_with_notes_sorted_by_id(self) -> None:
813
+ nb = Notebook(name="nb")
814
+ nb.add_note("n2", "second", "b", tags=["t"])
815
+ nb.add_note("n1", "first", "b")
816
+ md = nb.to_markdown()
817
+ assert md.index("**n1**") < md.index("**n2**")
818
+ assert "(t)" in md # tags rendered for n2
819
+
820
+ def test_to_dict_structure(self) -> None:
821
+ nb = Notebook(name="nb")
822
+ nb.add_note("n1", "t", "b")
823
+ d = nb.to_dict()
824
+ assert d["name"] == "nb"
825
+ assert cast(list[dict[str, object]], d["notes"])[0]["id"] == "n1"
826
+
827
+ def test_from_dict_roundtrip(self) -> None:
828
+ nb = Notebook(name="nb")
829
+ nb.add_note("n1", "t", "b", tags=["x"], linked_concepts=["c"], created="2024")
830
+ rebuilt = Notebook.from_dict(nb.to_dict())
831
+ assert rebuilt.name == "nb"
832
+ assert rebuilt.get_note("n1").title == "t"
833
+ assert rebuilt.get_note("n1").tags == ["x"]
834
+
835
+ def test_from_dict_invalid_name(self) -> None:
836
+ with pytest.raises(ValueError, match="Invalid notebook name"):
837
+ Notebook.from_dict({"name": 1, "notes": []})
838
+
839
+ def test_from_dict_invalid_notes_list(self) -> None:
840
+ with pytest.raises(ValueError, match="Invalid notes list"):
841
+ Notebook.from_dict({"name": "nb", "notes": "x"})
842
+
843
+ def test_from_dict_invalid_note_entry(self) -> None:
844
+ with pytest.raises(ValueError, match="Invalid note entry"):
845
+ Notebook.from_dict({"name": "nb", "notes": ["not-a-dict"]})
846
+
847
+ def test_save_load_roundtrip(self, tmp_path: Path) -> None:
848
+ nb = Notebook(name="nb")
849
+ nb.add_note("n1", "t", "b")
850
+ path = tmp_path / "nb.json"
851
+ nb.save(path)
852
+ loaded = Notebook.load(path)
853
+ assert loaded.get_note("n1").title == "t"
854
+
855
+ def test_load_non_dict_raises(self, tmp_path) -> None: # type: ignore[no-untyped-def]
856
+ path = tmp_path / "bad.json"
857
+ path.write_text("[]", encoding="utf-8")
858
+ with pytest.raises(ValueError, match="Invalid notebook file"):
859
+ Notebook.load(path)
860
+
861
+ def test_save_writes_utf8(self, tmp_path) -> None: # type: ignore[no-untyped-def]
862
+ nb = Notebook(name="café")
863
+ nb.add_note("n1", "tître", "b")
864
+ path = tmp_path / "nb.json"
865
+ nb.save(path)
866
+ text = path.read_text(encoding="utf-8")
867
+ assert "café" in text
868
+ assert "tître" in text
869
+
870
+
871
+ # ---------------------------------------------------------------------- #
872
+ # Retrieval — search_concepts
873
+ # ---------------------------------------------------------------------- #
874
+
875
+
876
+ class TestSearchConcepts:
877
+ def _graph(self) -> KnowledgeGraph:
878
+ kg = KnowledgeGraph(name="g")
879
+ kg.add_concept("Gravity", description="attractive force between masses", tags=["physics"])
880
+ kg.add_concept("Graviton", description="hypothetical quantum of gravity", tags=["physics"])
881
+ kg.add_concept("Energy", description="capacity to do work", tags=["physics", "abstract"])
882
+ kg.add_concept("Mass", tags=["physics"])
883
+ return kg
884
+
885
+ def test_exact_name_match_scores_highest(self) -> None:
886
+ kg = self._graph()
887
+ results = search_concepts(kg, "gravity")
888
+ assert results[0].concept_name == "Gravity"
889
+ assert results[0].score == NAME_TAG_SCORE
890
+ assert results[0].matched_on == "name"
891
+
892
+ def test_substring_name_match(self) -> None:
893
+ kg = self._graph()
894
+ results = search_concepts(kg, "grav")
895
+ names = [r.concept_name for r in results]
896
+ assert "Gravity" in names
897
+ assert "Graviton" in names
898
+ assert all(r.score == SUBSTRING_SCORE for r in results)
899
+
900
+ def test_description_substring_match(self) -> None:
901
+ kg = self._graph()
902
+ results = search_concepts(kg, "masses")
903
+ assert any(r.concept_name == "Gravity" and r.matched_on == "description" for r in results)
904
+
905
+ def test_case_insensitive(self) -> None:
906
+ kg = self._graph()
907
+ assert search_concepts(kg, "GRAVITY")[0].concept_name == "Gravity"
908
+ assert search_concepts(kg, "gravity")[0].concept_name == "Gravity"
909
+
910
+ def test_no_match_returns_empty(self) -> None:
911
+ kg = self._graph()
912
+ assert search_concepts(kg, "nonexistent") == []
913
+
914
+ def test_tag_filter_excludes_non_matching(self) -> None:
915
+ kg = self._graph()
916
+ results = search_concepts(kg, "energy", tag="abstract")
917
+ assert [r.concept_name for r in results] == ["Energy"]
918
+ # Without the abstract tag, Energy would still match.
919
+ results2 = search_concepts(kg, "energy", tag="physics")
920
+ assert "Energy" in [r.concept_name for r in results2]
921
+
922
+ def test_tag_filter_no_matches_returns_empty(self) -> None:
923
+ kg = self._graph()
924
+ assert search_concepts(kg, "gravity", tag="absenttag") == []
925
+
926
+ def test_ties_break_alphabetically(self) -> None:
927
+ kg = self._graph()
928
+ results = search_concepts(kg, "grav")
929
+ # Gravity & Graviton both substring (0.5); ties break alphabetically:
930
+ # "Graviton" < "Gravity" because 'i' < 'y'.
931
+ assert [r.concept_name for r in results] == ["Graviton", "Gravity"]
932
+
933
+ def test_results_sorted_by_score_then_name(self) -> None:
934
+ kg = KnowledgeGraph(name="g")
935
+ kg.add_concept("Zeta", description="contains needle")
936
+ kg.add_concept("needle") # exact match -> 1.0
937
+ kg.add_concept("Alpha", description="contains needle")
938
+ results = search_concepts(kg, "needle")
939
+ # Exact (needle) first, then Alpha & Zeta alphabetical.
940
+ assert [r.concept_name for r in results] == ["needle", "Alpha", "Zeta"]
941
+
942
+ def test_description_none_does_not_match_substring(self) -> None:
943
+ # 'Mass' has description=None; a query present only in it must not match.
944
+ kg = self._graph()
945
+ results = search_concepts(kg, "physics-label")
946
+ assert not any(r.concept_name == "Mass" for r in results)
947
+
948
+
949
+ # ---------------------------------------------------------------------- #
950
+ # Retrieval — search_notes
951
+ # ---------------------------------------------------------------------- #
952
+
953
+
954
+ class TestSearchNotes:
955
+ def _notebook(self) -> Notebook:
956
+ nb = Notebook(name="nb")
957
+ nb.add_note("n1", "Gravity", "discusses masses", tags=["physics"])
958
+ nb.add_note("n2", "Misc", "gravity is mentioned in body", tags=["physics"])
959
+ nb.add_note("n3", "Unrelated", "nothing here")
960
+ return nb
961
+
962
+ def test_exact_title_match_scores_highest(self) -> None:
963
+ nb = self._notebook()
964
+ results = search_notes(nb, "gravity")
965
+ assert results[0].note_id == "n1"
966
+ assert results[0].score == NAME_TAG_SCORE
967
+ assert results[0].matched_on == "title"
968
+
969
+ def test_substring_title_match(self) -> None:
970
+ nb = Notebook(name="nb")
971
+ nb.add_note("n1", "Gravitational waves", "b")
972
+ results = search_notes(nb, "grav")
973
+ assert results[0].note_id == "n1"
974
+ assert results[0].matched_on == "title"
975
+ assert results[0].score == SUBSTRING_SCORE
976
+
977
+ def test_body_substring_match(self) -> None:
978
+ nb = self._notebook()
979
+ results = search_notes(nb, "gravity")
980
+ ids = [r.note_id for r in results]
981
+ assert "n2" in ids
982
+ n2 = next(r for r in results if r.note_id == "n2")
983
+ assert n2.matched_on == "body"
984
+ assert n2.score == SUBSTRING_SCORE
985
+
986
+ def test_title_match_preferred_over_body(self) -> None:
987
+ # n1 matches title exactly (1.0), n2 matches body (0.5).
988
+ nb = self._notebook()
989
+ results = search_notes(nb, "gravity")
990
+ assert results[0].note_id == "n1"
991
+
992
+ def test_case_insensitive(self) -> None:
993
+ nb = self._notebook()
994
+ assert search_notes(nb, "GRAVITY")[0].note_id == "n1"
995
+
996
+ def test_no_match_returns_empty(self) -> None:
997
+ nb = self._notebook()
998
+ assert search_notes(nb, "nonexistent") == []
999
+
1000
+ def test_tag_filter(self) -> None:
1001
+ nb = self._notebook()
1002
+ results = search_notes(nb, "gravity", tag="physics")
1003
+ assert {r.note_id for r in results} == {"n1", "n2"}
1004
+ # n3 has no 'physics' tag and wouldn't match anyway.
1005
+
1006
+ def test_tag_filter_excludes(self) -> None:
1007
+ nb = Notebook(name="nb")
1008
+ nb.add_note("n1", "gravity", "b", tags=["a"])
1009
+ nb.add_note("n2", "gravity", "b", tags=["b"])
1010
+ results = search_notes(nb, "gravity", tag="a")
1011
+ assert [r.note_id for r in results] == ["n1"]
1012
+
1013
+ def test_results_sorted_by_score_then_id(self) -> None:
1014
+ nb = Notebook(name="nb")
1015
+ nb.add_note("zzz", "needle", "b") # exact 1.0
1016
+ nb.add_note("bbb", "x", "needle in body") # substring 0.5
1017
+ nb.add_note("aaa", "x", "needle in body") # substring 0.5
1018
+ results = search_notes(nb, "needle")
1019
+ assert [r.note_id for r in results] == ["zzz", "aaa", "bbb"]
1020
+
1021
+
1022
+ # ---------------------------------------------------------------------- #
1023
+ # Retrieval — combined search
1024
+ # ---------------------------------------------------------------------- #
1025
+
1026
+
1027
+ class TestSearchCombined:
1028
+ def test_merges_concepts_and_notes(self) -> None:
1029
+ kg = KnowledgeGraph(name="g")
1030
+ kg.add_concept("gravity")
1031
+ nb = Notebook(name="nb")
1032
+ nb.add_note("n1", "gravity note", "b")
1033
+ results = search(kg, nb, "gravity")
1034
+ assert {r.concept_name for r in results if r.concept_name} == {"gravity"}
1035
+ assert {r.note_id for r in results if r.note_id} == {"n1"}
1036
+
1037
+ def test_combined_ranking(self) -> None:
1038
+ kg = KnowledgeGraph(name="g")
1039
+ kg.add_concept("needle", description="contains needle") # exact 1.0
1040
+ nb = Notebook(name="nb")
1041
+ nb.add_note("n1", "needle", "b") # exact 1.0
1042
+ nb.add_note("n2", "x", "needle body") # substring 0.5
1043
+ results = search(kg, nb, "needle")
1044
+ # Two exact matches (1.0) first, ordered by identifier alphabetically,
1045
+ # then the 0.5 body match. Note id "n1" and concept name "needle" sort
1046
+ # before "n2"; "n1" < "needle" lexicographically.
1047
+ scores = [r.score for r in results]
1048
+ assert scores == sorted(scores, reverse=True)
1049
+ assert results[-1].note_id == "n2"
1050
+
1051
+ def test_combined_tag_filter_applied_to_both(self) -> None:
1052
+ kg = KnowledgeGraph(name="g")
1053
+ kg.add_concept("needle", tags=["keep"])
1054
+ kg.add_concept("needle2", tags=["drop"])
1055
+ nb = Notebook(name="nb")
1056
+ nb.add_note("n1", "needle", "b", tags=["keep"])
1057
+ nb.add_note("n2", "needle", "b", tags=["drop"])
1058
+ results = search(kg, nb, "needle", tag="keep")
1059
+ assert {r.concept_name for r in results if r.concept_name} == {"needle"}
1060
+ assert {r.note_id for r in results if r.note_id} == {"n1"}
1061
+
1062
+ def test_empty_stores_return_empty(self) -> None:
1063
+ kg = KnowledgeGraph(name="g")
1064
+ nb = Notebook(name="nb")
1065
+ assert search(kg, nb, "anything") == []
1066
+
1067
+
1068
+ # ---------------------------------------------------------------------- #
1069
+ # Public API surface
1070
+ # ---------------------------------------------------------------------- #
1071
+
1072
+
1073
+ class TestPublicAPI:
1074
+ def test_search_result_dataclass_fields(self) -> None:
1075
+ r = SearchResult(concept_name="x", note_id=None, score=1.0, matched_on="name")
1076
+ assert r.concept_name == "x"
1077
+ assert r.note_id is None
1078
+ assert r.score == 1.0
1079
+ assert r.matched_on == "name"
1080
+
1081
+ def test_search_result_note_variant(self) -> None:
1082
+ r = SearchResult(concept_name=None, note_id="n1", score=0.5, matched_on="body")
1083
+ assert r.concept_name is None
1084
+ assert r.note_id == "n1"
1085
+
1086
+ def test_all_documented_names_exported(self) -> None:
1087
+ # cds.knowledge is already imported at module scope (above), so read
1088
+ # it back from sys.modules instead of re-``import``-ing, which would
1089
+ # mix ``import cds.knowledge`` with the module-scope ``from`` form.
1090
+ import sys
1091
+
1092
+ mod = sys.modules["cds.knowledge"]
1093
+
1094
+ expected = {
1095
+ "Concept",
1096
+ "Relation",
1097
+ "KnowledgeGraph",
1098
+ "Note",
1099
+ "Notebook",
1100
+ "SearchResult",
1101
+ "search",
1102
+ "search_concepts",
1103
+ "search_notes",
1104
+ "RetrievalHit",
1105
+ "rank_tfidf",
1106
+ }
1107
+ assert expected.issubset(set(dir(mod)))
1108
+ assert expected == set(mod.__all__)
1109
+
1110
+
1111
+ # ---------------------------------------------------------------------- #
1112
+ # Integration: the documented end-to-end workflow
1113
+ # ---------------------------------------------------------------------- #
1114
+
1115
+
1116
+ class TestIntegration:
1117
+ def test_full_workflow_roundtrip(self, tmp_path) -> None: # type: ignore[no-untyped-def]
1118
+ kg = KnowledgeGraph(name="Cosmology")
1119
+ kg.add_concept("Dark Energy", description="drives expansion", tags=["cosmology"])
1120
+ kg.add_concept("Hubble Constant", tags=["cosmology"])
1121
+ kg.add_relation("Dark Energy", "Hubble Constant", kind="affects")
1122
+
1123
+ nb = Notebook(name="Lab")
1124
+ nb.add_note(
1125
+ "n1",
1126
+ "Hubble Tension",
1127
+ "local vs cmb measurements",
1128
+ tags=["exp"],
1129
+ linked_concepts=["Hubble Constant"],
1130
+ )
1131
+
1132
+ # Persistence round-trips for both.
1133
+ gpath = tmp_path / "g.json"
1134
+ npath = tmp_path / "n.json"
1135
+ kg.save(gpath)
1136
+ nb.save(npath)
1137
+ kg2 = KnowledgeGraph.load(gpath)
1138
+ nb2 = Notebook.load(npath)
1139
+
1140
+ # Search works on reloaded data.
1141
+ results = search(kg2, nb2, "hubble")
1142
+ assert any(r.concept_name == "Hubble Constant" for r in results)
1143
+ assert any(r.note_id == "n1" for r in results)
1144
+
1145
+ # Traversal survives the round-trip.
1146
+ assert kg2.find_path("Dark Energy", "Hubble Constant") == [
1147
+ "Dark Energy",
1148
+ "Hubble Constant",
1149
+ ]