codmap 0.0.39__tar.gz → 0.0.41__tar.gz

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 (200) hide show
  1. {codmap-0.0.39/codmap.egg-info → codmap-0.0.41}/PKG-INFO +15 -4
  2. {codmap-0.0.39 → codmap-0.0.41}/README.md +14 -3
  3. codmap-0.0.41/codemap/advise/__init__.py +569 -0
  4. codmap-0.0.41/codemap/advise/data/feed.json +306 -0
  5. codmap-0.0.41/codemap/advise/data/matrix.toml +1697 -0
  6. codmap-0.0.41/codemap/advise/refresh.py +59 -0
  7. codmap-0.0.41/codemap/advise/render.py +152 -0
  8. {codmap-0.0.39 → codmap-0.0.41}/codemap/cli.py +64 -0
  9. {codmap-0.0.39 → codmap-0.0.41}/codemap/devkit/__init__.py +2 -2
  10. {codmap-0.0.39 → codmap-0.0.41}/codemap/devkit/install.py +12 -0
  11. {codmap-0.0.39 → codmap-0.0.41}/codemap/devkit/templates/agents_block.md +7 -0
  12. {codmap-0.0.39 → codmap-0.0.41}/codemap/model.py +4 -1
  13. {codmap-0.0.39 → codmap-0.0.41}/codemap/serve/mcp_server.py +21 -2
  14. {codmap-0.0.39 → codmap-0.0.41}/codemap/serve/session.py +14 -2
  15. {codmap-0.0.39 → codmap-0.0.41/codmap.egg-info}/PKG-INFO +15 -4
  16. {codmap-0.0.39 → codmap-0.0.41}/codmap.egg-info/SOURCES.txt +6 -0
  17. {codmap-0.0.39 → codmap-0.0.41}/pyproject.toml +2 -1
  18. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c108_devkit.py +3 -2
  19. codmap-0.0.41/tests/test_r1c110_advise.py +420 -0
  20. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c37_rule_mutation.py +1 -1
  21. {codmap-0.0.39 → codmap-0.0.41}/LICENSE +0 -0
  22. {codmap-0.0.39 → codmap-0.0.41}/codemap/__init__.py +0 -0
  23. {codmap-0.0.39 → codmap-0.0.41}/codemap/__main__.py +0 -0
  24. {codmap-0.0.39 → codmap-0.0.41}/codemap/apidiff.py +0 -0
  25. {codmap-0.0.39 → codmap-0.0.41}/codemap/arch.py +0 -0
  26. {codmap-0.0.39 → codmap-0.0.41}/codemap/devkit/artifacts.py +0 -0
  27. {codmap-0.0.39 → codmap-0.0.41}/codemap/devkit/hooks.py +0 -0
  28. {codmap-0.0.39 → codmap-0.0.41}/codemap/devkit/ratchet.py +0 -0
  29. {codmap-0.0.39 → codmap-0.0.41}/codemap/devkit/state.py +0 -0
  30. {codmap-0.0.39 → codmap-0.0.41}/codemap/devkit/templates/brief.txt +0 -0
  31. {codmap-0.0.39 → codmap-0.0.41}/codemap/devkit/templates/claude_hooks.json +0 -0
  32. {codmap-0.0.39 → codmap-0.0.41}/codemap/devkit/templates/codex_region.toml +0 -0
  33. {codmap-0.0.39 → codmap-0.0.41}/codemap/devkit/templates/contract_head.toml +0 -0
  34. {codmap-0.0.39 → codmap-0.0.41}/codemap/devkit/templates/github-workflow.yml +0 -0
  35. {codmap-0.0.39 → codmap-0.0.41}/codemap/devkit/templates/gitlab-ci.yml +0 -0
  36. {codmap-0.0.39 → codmap-0.0.41}/codemap/devkit/templates/mcp_claude.args +0 -0
  37. {codmap-0.0.39 → codmap-0.0.41}/codemap/devkit/templates/post-commit.sh +0 -0
  38. {codmap-0.0.39 → codmap-0.0.41}/codemap/devkit/templates/ratchet_region.toml +0 -0
  39. {codmap-0.0.39 → codmap-0.0.41}/codemap/devkit/usage.py +0 -0
  40. {codmap-0.0.39 → codmap-0.0.41}/codemap/diagnostics.py +0 -0
  41. {codmap-0.0.39 → codmap-0.0.41}/codemap/extract/__init__.py +0 -0
  42. {codmap-0.0.39 → codmap-0.0.41}/codemap/extract/attrflow.py +0 -0
  43. {codmap-0.0.39 → codmap-0.0.41}/codemap/extract/behavior.py +0 -0
  44. {codmap-0.0.39 → codmap-0.0.41}/codemap/extract/dataflow.py +0 -0
  45. {codmap-0.0.39 → codmap-0.0.41}/codemap/extract/dispatch.py +0 -0
  46. {codmap-0.0.39 → codmap-0.0.41}/codemap/extract/griffe_extractor.py +0 -0
  47. {codmap-0.0.39 → codmap-0.0.41}/codemap/extract/gsource.py +0 -0
  48. {codmap-0.0.39 → codmap-0.0.41}/codemap/extract/probe.py +0 -0
  49. {codmap-0.0.39 → codmap-0.0.41}/codemap/extract/roots.py +0 -0
  50. {codmap-0.0.39 → codmap-0.0.41}/codemap/extract/union.py +0 -0
  51. {codmap-0.0.39 → codmap-0.0.41}/codemap/freshness.py +0 -0
  52. {codmap-0.0.39 → codmap-0.0.41}/codemap/incremental.py +0 -0
  53. {codmap-0.0.39 → codmap-0.0.41}/codemap/integrations/__init__.py +0 -0
  54. {codmap-0.0.39 → codmap-0.0.41}/codemap/integrations/base.py +0 -0
  55. {codmap-0.0.39 → codmap-0.0.41}/codemap/integrations/cocoindex.py +0 -0
  56. {codmap-0.0.39 → codmap-0.0.41}/codemap/integrations/gate.py +0 -0
  57. {codmap-0.0.39 → codmap-0.0.41}/codemap/integrations/gitnexus.py +0 -0
  58. {codmap-0.0.39 → codmap-0.0.41}/codemap/integrations/registry.py +0 -0
  59. {codmap-0.0.39 → codmap-0.0.41}/codemap/integrations/transport.py +0 -0
  60. {codmap-0.0.39 → codmap-0.0.41}/codemap/provenance.py +0 -0
  61. {codmap-0.0.39 → codmap-0.0.41}/codemap/query.py +0 -0
  62. {codmap-0.0.39 → codmap-0.0.41}/codemap/scope.py +0 -0
  63. {codmap-0.0.39 → codmap-0.0.41}/codemap/serve/__init__.py +0 -0
  64. {codmap-0.0.39 → codmap-0.0.41}/codemap/serve/_scip_pb2.py +0 -0
  65. {codmap-0.0.39 → codmap-0.0.41}/codemap/serve/api_surface.py +0 -0
  66. {codmap-0.0.39 → codmap-0.0.41}/codemap/serve/apidiff.py +0 -0
  67. {codmap-0.0.39 → codmap-0.0.41}/codemap/serve/architecture.py +0 -0
  68. {codmap-0.0.39 → codmap-0.0.41}/codemap/serve/audit.py +0 -0
  69. {codmap-0.0.39 → codmap-0.0.41}/codemap/serve/check.py +0 -0
  70. {codmap-0.0.39 → codmap-0.0.41}/codemap/serve/ctags.py +0 -0
  71. {codmap-0.0.39 → codmap-0.0.41}/codemap/serve/currency.py +0 -0
  72. {codmap-0.0.39 → codmap-0.0.41}/codemap/serve/impact.py +0 -0
  73. {codmap-0.0.39 → codmap-0.0.41}/codemap/serve/limits.py +0 -0
  74. {codmap-0.0.39 → codmap-0.0.41}/codemap/serve/livingdocs.py +0 -0
  75. {codmap-0.0.39 → codmap-0.0.41}/codemap/serve/mermaid.py +0 -0
  76. {codmap-0.0.39 → codmap-0.0.41}/codemap/serve/pack.py +0 -0
  77. {codmap-0.0.39 → codmap-0.0.41}/codemap/serve/rag.py +0 -0
  78. {codmap-0.0.39 → codmap-0.0.41}/codemap/serve/review.py +0 -0
  79. {codmap-0.0.39 → codmap-0.0.41}/codemap/serve/scip.py +0 -0
  80. {codmap-0.0.39 → codmap-0.0.41}/codemap/serve/semantic.py +0 -0
  81. {codmap-0.0.39 → codmap-0.0.41}/codemap/serve/server.py +0 -0
  82. {codmap-0.0.39 → codmap-0.0.41}/codemap/serve/subsystems.py +0 -0
  83. {codmap-0.0.39 → codmap-0.0.41}/codemap/serve/vault.py +0 -0
  84. {codmap-0.0.39 → codmap-0.0.41}/codemap/store.py +0 -0
  85. {codmap-0.0.39 → codmap-0.0.41}/codemap/tomlio.py +0 -0
  86. {codmap-0.0.39 → codmap-0.0.41}/codemap/watch.py +0 -0
  87. {codmap-0.0.39 → codmap-0.0.41}/codmap.egg-info/dependency_links.txt +0 -0
  88. {codmap-0.0.39 → codmap-0.0.41}/codmap.egg-info/entry_points.txt +0 -0
  89. {codmap-0.0.39 → codmap-0.0.41}/codmap.egg-info/requires.txt +0 -0
  90. {codmap-0.0.39 → codmap-0.0.41}/codmap.egg-info/top_level.txt +0 -0
  91. {codmap-0.0.39 → codmap-0.0.41}/setup.cfg +0 -0
  92. {codmap-0.0.39 → codmap-0.0.41}/tests/test_epistemic.py +0 -0
  93. {codmap-0.0.39 → codmap-0.0.41}/tests/test_gitnexus_router.py +0 -0
  94. {codmap-0.0.39 → codmap-0.0.41}/tests/test_impact_depth.py +0 -0
  95. {codmap-0.0.39 → codmap-0.0.41}/tests/test_integrations.py +0 -0
  96. {codmap-0.0.39 → codmap-0.0.41}/tests/test_issue3_serve_freshness.py +0 -0
  97. {codmap-0.0.39 → codmap-0.0.41}/tests/test_livingdocs.py +0 -0
  98. {codmap-0.0.39 → codmap-0.0.41}/tests/test_m0_api_surface.py +0 -0
  99. {codmap-0.0.39 → codmap-0.0.41}/tests/test_m11_argcontract.py +0 -0
  100. {codmap-0.0.39 → codmap-0.0.41}/tests/test_m12_dataflow.py +0 -0
  101. {codmap-0.0.39 → codmap-0.0.41}/tests/test_m15_review.py +0 -0
  102. {codmap-0.0.39 → codmap-0.0.41}/tests/test_m16_architecture.py +0 -0
  103. {codmap-0.0.39 → codmap-0.0.41}/tests/test_m17_mcp.py +0 -0
  104. {codmap-0.0.39 → codmap-0.0.41}/tests/test_m18_freshness.py +0 -0
  105. {codmap-0.0.39 → codmap-0.0.41}/tests/test_m1_5_semantics.py +0 -0
  106. {codmap-0.0.39 → codmap-0.0.41}/tests/test_m1_query.py +0 -0
  107. {codmap-0.0.39 → codmap-0.0.41}/tests/test_m2_views.py +0 -0
  108. {codmap-0.0.39 → codmap-0.0.41}/tests/test_m32_watch.py +0 -0
  109. {codmap-0.0.39 → codmap-0.0.41}/tests/test_m3_serve.py +0 -0
  110. {codmap-0.0.39 → codmap-0.0.41}/tests/test_m4_behavior.py +0 -0
  111. {codmap-0.0.39 → codmap-0.0.41}/tests/test_m5_deep.py +0 -0
  112. {codmap-0.0.39 → codmap-0.0.41}/tests/test_m6_repo_scope.py +0 -0
  113. {codmap-0.0.39 → codmap-0.0.41}/tests/test_m7_dispatch.py +0 -0
  114. {codmap-0.0.39 → codmap-0.0.41}/tests/test_m9_family.py +0 -0
  115. {codmap-0.0.39 → codmap-0.0.41}/tests/test_pack_honesty.py +0 -0
  116. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c109_namespace_source.py +0 -0
  117. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c13_callgraph_accuracy.py +0 -0
  118. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c13_grep_vs_graph.py +0 -0
  119. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c16_semantic.py +0 -0
  120. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c20_attribute_edges.py +0 -0
  121. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c21_flat_layout.py +0 -0
  122. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c22_source_visible_refs.py +0 -0
  123. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c23_hard_python.py +0 -0
  124. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c24_test_mapping.py +0 -0
  125. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c25_provenance.py +0 -0
  126. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c26_deep_union.py +0 -0
  127. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c27_config_honesty.py +0 -0
  128. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c28_limit_envelope.py +0 -0
  129. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c29_lazy_imports.py +0 -0
  130. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c2_ctags.py +0 -0
  131. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c30_local_import_calls.py +0 -0
  132. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c30f1_reexport_calls.py +0 -0
  133. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c30f2_check_scope.py +0 -0
  134. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c31_path_origin.py +0 -0
  135. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c32_report_json.py +0 -0
  136. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c33_query_signature.py +0 -0
  137. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c34_signature_kinds.py +0 -0
  138. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c35_contract_location.py +0 -0
  139. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c36_target_resolution.py +0 -0
  140. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c38_tool_drift.py +0 -0
  141. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c39_edge_resolution.py +0 -0
  142. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c3_arch_contract.py +0 -0
  143. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c3_dogfood.py +0 -0
  144. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c40_flow_reach.py +0 -0
  145. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c41_scope_membership.py +0 -0
  146. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c42_deep_tier_stability.py +0 -0
  147. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c43_incremental_splice.py +0 -0
  148. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c44_absent_answers.py +0 -0
  149. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c45_repeat_union.py +0 -0
  150. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c46_shadowed_definitions.py +0 -0
  151. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c47_incremental_resample.py +0 -0
  152. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c48_type_checking_imports.py +0 -0
  153. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c49_type_only_cycles.py +0 -0
  154. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c4_complexity.py +0 -0
  155. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c50_flow_entry_points.py +0 -0
  156. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c53_narrowing_declared.py +0 -0
  157. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c54_deterministic_rendering.py +0 -0
  158. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c55_override_grade.py +0 -0
  159. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c56_stub_files.py +0 -0
  160. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c57_facade_package.py +0 -0
  161. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c58_cycle_tangles.py +0 -0
  162. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c59_completeness_drop.py +0 -0
  163. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c5_apidiff.py +0 -0
  164. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c60_nested_definitions.py +0 -0
  165. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c62_phantom_rules.py +0 -0
  166. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c63_answer_format.py +0 -0
  167. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c64_dependency_probe.py +0 -0
  168. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c66_pack_direction.py +0 -0
  169. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c68_dotted_imports.py +0 -0
  170. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c69_contract_validation.py +0 -0
  171. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c6_pack.py +0 -0
  172. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c70_check_graph_currency.py +0 -0
  173. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c71_attribute_chain_calls.py +0 -0
  174. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c72_flat_inference_in_packages.py +0 -0
  175. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c73_cli_version.py +0 -0
  176. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c74_call_site_conservation.py +0 -0
  177. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c75_reexported_class_calls.py +0 -0
  178. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c76_contract_table_typo.py +0 -0
  179. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c77_gate_probe_battery.py +0 -0
  180. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c78_forbidden_chains.py +0 -0
  181. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c7_edge_vocab.py +0 -0
  182. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c80_tests_through_helpers.py +0 -0
  183. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c81_protocol_dispatch.py +0 -0
  184. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c82_review_changed_lines.py +0 -0
  185. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c83_foreign_graph_paths.py +0 -0
  186. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c84_missing_roots.py +0 -0
  187. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c85_mcp_graph_currency.py +0 -0
  188. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c86_incremental_repo_scope.py +0 -0
  189. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c87_review_path_base.py +0 -0
  190. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c89_review_docs.py +0 -0
  191. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c8_deadcode.py +0 -0
  192. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c90_currency_without_recipe.py +0 -0
  193. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c91_route_vocabulary.py +0 -0
  194. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c92_sidecar_pair.py +0 -0
  195. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c94_root_builds.py +0 -0
  196. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c95_r1c96_foreign_trees.py +0 -0
  197. {codmap-0.0.39 → codmap-0.0.41}/tests/test_r1c9_incremental.py +0 -0
  198. {codmap-0.0.39 → codmap-0.0.41}/tests/test_scip_export.py +0 -0
  199. {codmap-0.0.39 → codmap-0.0.41}/tests/test_scope.py +0 -0
  200. {codmap-0.0.39 → codmap-0.0.41}/tests/test_subsystems.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: codmap
3
- Version: 0.0.39
3
+ Version: 0.0.41
4
4
  Summary: Static analyzer that turns a package's source into a queryable code graph.
5
5
  Author-email: kogriv <kogriv@gmail.com>
6
6
  License-Expression: MIT
@@ -42,11 +42,21 @@ the code it analyzes. One canonical, deterministic graph store → many renders:
42
42
  dependency/architecture audit, RAG chunks, an Obsidian vault, mermaid diagrams, change-set review,
43
43
  and a **SCIP index** for interop with Sourcegraph / Glean and other precise-code-intelligence tools.
44
44
 
45
+ **And the lab's measured map of the rest of the field, served to the agent.** codemap reads Python only.
46
+ Its lab measures neighbouring code-intelligence tools on one shared truth and keeps the results current.
47
+ `advise` (MCP) and `codemap advise` answer the agent's next question when the graph cannot: other
48
+ languages, duplicates, security patterns, complexity, DB query counts. For each need it gives codemap's own
49
+ coverage, proved by a named test, and the other tools. Every claim is marked `measured`, `probed`, `read`
50
+ (nobody here ran it) or `rejected`, with its version, date and evidence. Today: 21 needs, 53 tools, claims
51
+ 23 measured · 18 probed · 62 read · 9 rejected. The inventory is [`research/matrix.md`](research/matrix.md),
52
+ the guide is [`docs/advise.md`](docs/advise.md), and `codemap advise --refresh` fetches the current catalog
53
+ without a release.
54
+
45
55
  [![CI](https://github.com/kogriv/codemap/actions/workflows/ci.yml/badge.svg)](https://github.com/kogriv/codemap/actions/workflows/ci.yml)
46
56
 
47
- **Status:** 🟢 M0–M20 implemented + research track (R1/R2) — schema 0.13, **1324 tests with no failures on
57
+ **Status:** 🟢 M0–M20 implemented + research track (R1/R2) — schema 0.13, **1371 tests with no failures on
48
58
  Python 3.11–3.14** ([in CI](docs/ci.md): the full suite including the dogfood pass, a determinism check, a
49
- wheel smoke test, and ctags/SCIP interop against the real CLIs), warm serve surface with 31 ops (28 exposed
59
+ wheel smoke test, and ctags/SCIP interop against the real CLIs), warm serve surface with 32 ops (29 exposed
50
60
  as MCP tools), and SCIP export. See **[DESIGN.md](DESIGN.md)** (product design &
51
61
  v1 boundaries), **[BACKLOG.md](BACKLOG.md)** (roadmap), and **[research/](research/)** (tool landscape).
52
62
 
@@ -215,7 +225,7 @@ codemap semantic "detect swing pivots" --build ./pkg --root pkg
215
225
  # token-budgeted context pack — most relevant graph slice under N tokens (ranked; --seed to focus)
216
226
  codemap pack --graph graph.json --budget 2000 --seed analyze_zones
217
227
 
218
- # warm resident process — JSON requests over stdin/stdout (31 ops)
228
+ # warm resident process — JSON requests over stdin/stdout (32 ops)
219
229
  codemap serve --graph graph.json --source-root .
220
230
 
221
231
  # …or expose the same surface as MCP tools for an AI-agent host (needs [mcp] extra)
@@ -329,6 +339,7 @@ the live graph, findings, and the milestone that closed them.
329
339
  - **[docs/export.md](docs/export.md)** — export recipes: RAG, mermaid, Obsidian vault, SCIP + ctags interop.
330
340
  - **[docs/accuracy.md](docs/accuracy.md)** — measured call-graph accuracy, the honest static ceiling, and
331
341
  the grep-vs-graph value proof (both harnesses guarded in CI).
342
+ - **[docs/advise.md](docs/advise.md)** — `codemap advise` / MCP `advise`: what to use where codemap stops, from the lab's measured catalog
332
343
  - **[docs/devkit.md](docs/devkit.md)** — `codemap devkit`: adopt codemap in a repository in one command
333
344
  (agent rules, MCP, hooks, the ratchet contract) and keep the adoption current.
334
345
  - **[docs/architecture-contracts.md](docs/architecture-contracts.md)** — declare the intended architecture
@@ -6,11 +6,21 @@ the code it analyzes. One canonical, deterministic graph store → many renders:
6
6
  dependency/architecture audit, RAG chunks, an Obsidian vault, mermaid diagrams, change-set review,
7
7
  and a **SCIP index** for interop with Sourcegraph / Glean and other precise-code-intelligence tools.
8
8
 
9
+ **And the lab's measured map of the rest of the field, served to the agent.** codemap reads Python only.
10
+ Its lab measures neighbouring code-intelligence tools on one shared truth and keeps the results current.
11
+ `advise` (MCP) and `codemap advise` answer the agent's next question when the graph cannot: other
12
+ languages, duplicates, security patterns, complexity, DB query counts. For each need it gives codemap's own
13
+ coverage, proved by a named test, and the other tools. Every claim is marked `measured`, `probed`, `read`
14
+ (nobody here ran it) or `rejected`, with its version, date and evidence. Today: 21 needs, 53 tools, claims
15
+ 23 measured · 18 probed · 62 read · 9 rejected. The inventory is [`research/matrix.md`](research/matrix.md),
16
+ the guide is [`docs/advise.md`](docs/advise.md), and `codemap advise --refresh` fetches the current catalog
17
+ without a release.
18
+
9
19
  [![CI](https://github.com/kogriv/codemap/actions/workflows/ci.yml/badge.svg)](https://github.com/kogriv/codemap/actions/workflows/ci.yml)
10
20
 
11
- **Status:** 🟢 M0–M20 implemented + research track (R1/R2) — schema 0.13, **1324 tests with no failures on
21
+ **Status:** 🟢 M0–M20 implemented + research track (R1/R2) — schema 0.13, **1371 tests with no failures on
12
22
  Python 3.11–3.14** ([in CI](docs/ci.md): the full suite including the dogfood pass, a determinism check, a
13
- wheel smoke test, and ctags/SCIP interop against the real CLIs), warm serve surface with 31 ops (28 exposed
23
+ wheel smoke test, and ctags/SCIP interop against the real CLIs), warm serve surface with 32 ops (29 exposed
14
24
  as MCP tools), and SCIP export. See **[DESIGN.md](DESIGN.md)** (product design &
15
25
  v1 boundaries), **[BACKLOG.md](BACKLOG.md)** (roadmap), and **[research/](research/)** (tool landscape).
16
26
 
@@ -179,7 +189,7 @@ codemap semantic "detect swing pivots" --build ./pkg --root pkg
179
189
  # token-budgeted context pack — most relevant graph slice under N tokens (ranked; --seed to focus)
180
190
  codemap pack --graph graph.json --budget 2000 --seed analyze_zones
181
191
 
182
- # warm resident process — JSON requests over stdin/stdout (31 ops)
192
+ # warm resident process — JSON requests over stdin/stdout (32 ops)
183
193
  codemap serve --graph graph.json --source-root .
184
194
 
185
195
  # …or expose the same surface as MCP tools for an AI-agent host (needs [mcp] extra)
@@ -293,6 +303,7 @@ the live graph, findings, and the milestone that closed them.
293
303
  - **[docs/export.md](docs/export.md)** — export recipes: RAG, mermaid, Obsidian vault, SCIP + ctags interop.
294
304
  - **[docs/accuracy.md](docs/accuracy.md)** — measured call-graph accuracy, the honest static ceiling, and
295
305
  the grep-vs-graph value proof (both harnesses guarded in CI).
306
+ - **[docs/advise.md](docs/advise.md)** — `codemap advise` / MCP `advise`: what to use where codemap stops, from the lab's measured catalog
296
307
  - **[docs/devkit.md](docs/devkit.md)** — `codemap devkit`: adopt codemap in a repository in one command
297
308
  (agent rules, MCP, hooks, the ratchet contract) and keep the adoption current.
298
309
  - **[docs/architecture-contracts.md](docs/architecture-contracts.md)** — declare the intended architecture
@@ -0,0 +1,569 @@
1
+ """The lab's verified tool expertise, served to the agent (R1-C110, ``docs/design/advise.md``).
2
+
3
+ Two data files ship in the package and are published on ``main``:
4
+
5
+ - ``data/matrix.toml`` — needs × tools. Every claim (one tool, one need) carries a status from a closed
6
+ vocabulary (``measured`` / ``probed`` / ``read`` / ``rejected``), the version and date it was checked, and
7
+ the evidence: a heading in a research card of this repository. codemap's own coverage of each need names the
8
+ tests that prove it.
9
+ - ``data/feed.json`` — machine-written by the lab's release watch and scouting: the latest release seen per
10
+ tool and a news list.
11
+
12
+ ``codemap advise --refresh`` caches newer copies of both from ``main``; :func:`load` serves whichever is newer
13
+ per file and says so. Nothing here installs or runs a tool, and nothing here calls a model: it is a lookup over
14
+ reviewed data.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ import os
21
+ import re
22
+ import tomllib
23
+ from dataclasses import dataclass, field
24
+ from datetime import date, datetime, timezone
25
+ from pathlib import Path
26
+
27
+ SCHEMA = 1
28
+ STATUSES = ("measured", "probed", "read", "rejected")
29
+ COVERAGE = ("covered", "partial", "none")
30
+ NEWS_KINDS = ("release", "card", "finding", "advisory", "new-tool")
31
+ WATCH_KINDS = ("pypi", "npm", "github", "none")
32
+ INTERFACES = ("cli", "mcp", "lib", "saas", "plugin", "lsp")
33
+
34
+ DATA = Path(__file__).resolve().parent / "data"
35
+ DEFAULT_BASE = "https://raw.githubusercontent.com/kogriv/codemap/main/codemap/advise/data/"
36
+
37
+ # What a claim needs, per status (design D1).
38
+ _REQUIRES = {
39
+ "measured": ("version", "checked", "evidence", "summary"),
40
+ "probed": ("version", "checked", "evidence", "summary"),
41
+ "read": ("summary",),
42
+ "rejected": ("checked", "evidence", "reason"),
43
+ }
44
+
45
+ # File extensions codemap does not read, by language (design D4). Python is the graph's own.
46
+ LANGUAGES = {
47
+ ".py": "python", ".pyi": "python",
48
+ ".ts": "typescript", ".tsx": "typescript", ".mts": "typescript", ".cts": "typescript",
49
+ ".js": "javascript", ".jsx": "javascript", ".mjs": "javascript", ".cjs": "javascript",
50
+ ".vue": "vue", ".svelte": "svelte",
51
+ ".go": "go", ".rs": "rust", ".java": "java", ".kt": "kotlin", ".kts": "kotlin", ".scala": "scala",
52
+ ".rb": "ruby", ".php": "php", ".cs": "csharp", ".swift": "swift",
53
+ ".c": "c", ".h": "c", ".cpp": "cpp", ".cc": "cpp", ".cxx": "cpp", ".hpp": "cpp",
54
+ ".sql": "sql", ".sh": "shell", ".bash": "shell", ".dart": "dart",
55
+ }
56
+ #: A tool's `languages`: real names from the map above, or "any" for a language-agnostic tool (text, tokens, an
57
+ #: LLM). An empty list means "not recorded": such a tool is never shown for a language filter.
58
+ LANGUAGE_NAMES = frozenset(LANGUAGES.values()) | {"any"}
59
+ _SKIP_DIRS = {".git", ".hg", ".svn", "node_modules", ".venv", "venv", "env", "__pycache__", "dist", "build",
60
+ ".codemap", ".tox", ".nox", ".mypy_cache", ".pytest_cache", ".ruff_cache", "site-packages",
61
+ ".next", ".nuxt", "coverage", "target", "vendor", ".idea", ".vscode"}
62
+ _OUTSIDE = re.compile(r"^(?P<file>.+?(?P<ext>\.[A-Za-z]+))(?::\d+.*|::.*)?$")
63
+
64
+
65
+ # --------------------------------------------------------------------------- catalog
66
+
67
+
68
+ @dataclass
69
+ class Catalog:
70
+ matrix: dict
71
+ feed: dict
72
+ source: dict # {"matrix": "packaged"|"refreshed", "feed": ...}
73
+ notes: list[str] = field(default_factory=list)
74
+
75
+ @property
76
+ def meta(self) -> dict:
77
+ return self.matrix.get("meta", {})
78
+
79
+ @property
80
+ def needs(self) -> dict[str, dict]:
81
+ return {n["id"]: n for n in self.matrix.get("need", [])}
82
+
83
+ @property
84
+ def tools(self) -> dict[str, dict]:
85
+ return {t["id"]: t for t in self.matrix.get("tool", [])}
86
+
87
+ @property
88
+ def claims(self) -> list[dict]:
89
+ return list(self.matrix.get("claim", []))
90
+
91
+ @property
92
+ def as_of(self) -> str:
93
+ return max(self.meta.get("as_of", ""), self.feed.get("as_of", ""))
94
+
95
+ def header(self, today: date | None = None) -> dict:
96
+ today = today or datetime.now(timezone.utc).date()
97
+ a = _date(self.as_of)
98
+ return {"as_of": self.as_of, "matrix_as_of": self.meta.get("as_of"),
99
+ "feed_as_of": self.feed.get("as_of"), "source": dict(self.source),
100
+ "age_days": (today - a).days if a else None, "notes": list(self.notes)}
101
+
102
+
103
+ def cache_dir() -> Path:
104
+ base = os.environ.get("XDG_CACHE_HOME") or str(Path.home() / ".cache")
105
+ return Path(base) / "codemap" / "advise"
106
+
107
+
108
+ def _read_pair(directory: Path) -> tuple[dict | None, dict | None, list[str]]:
109
+ errs: list[str] = []
110
+ m = f = None
111
+ try:
112
+ m = tomllib.loads((directory / "matrix.toml").read_text(encoding="utf-8"))
113
+ except FileNotFoundError:
114
+ pass
115
+ except (OSError, ValueError) as exc:
116
+ errs.append(f"matrix.toml in {directory}: {exc}")
117
+ try:
118
+ f = json.loads((directory / "feed.json").read_text(encoding="utf-8"))
119
+ except FileNotFoundError:
120
+ pass
121
+ except (OSError, ValueError) as exc:
122
+ errs.append(f"feed.json in {directory}: {exc}")
123
+ return m, f, errs
124
+
125
+
126
+ def load(cache: Path | None = None, packaged: Path | None = None) -> Catalog:
127
+ """The packaged catalog, with each file replaced by its cached copy when that is newer and the pair valid."""
128
+ pm, pf, errs = _read_pair(packaged or DATA)
129
+ if pm is None or pf is None:
130
+ raise RuntimeError(f"codemap advise: packaged catalog missing or unreadable: {errs}")
131
+ cat = Catalog(pm, pf, {"matrix": "packaged", "feed": "packaged"})
132
+ cdir = cache if cache is not None else cache_dir()
133
+ if not cdir.is_dir():
134
+ return cat
135
+ cm, cf, cerrs = _read_pair(cdir)
136
+ cat.notes.extend(f"cache ignored: {e}" for e in cerrs)
137
+ m, f, src = pm, pf, {"matrix": "packaged", "feed": "packaged"}
138
+ if cm is not None and cm.get("meta", {}).get("as_of", "") > pm.get("meta", {}).get("as_of", ""):
139
+ m, src["matrix"] = cm, "refreshed"
140
+ if cf is not None and cf.get("as_of", "") > pf.get("as_of", ""):
141
+ f, src["feed"] = cf, "refreshed"
142
+ if src == cat.source:
143
+ return cat
144
+ problems = schema_problems(m, f)
145
+ if problems:
146
+ cat.notes.append(f"cached catalog ignored: {problems[0]}" + (f" (+{len(problems) - 1})" if len(problems) > 1 else ""))
147
+ return cat
148
+ return Catalog(m, f, src, cat.notes)
149
+
150
+
151
+ # --------------------------------------------------------------------------- validation
152
+
153
+
154
+ def _date(s) -> date | None:
155
+ if not isinstance(s, str) or len(s) < 10:
156
+ return None
157
+ try:
158
+ return date.fromisoformat(s[:10])
159
+ except ValueError:
160
+ return None
161
+
162
+
163
+ def schema_problems(matrix: dict, feed: dict) -> list[str]:
164
+ """Structural checks every copy must pass, packaged or downloaded (design D5, D7)."""
165
+ p: list[str] = []
166
+ meta = matrix.get("meta")
167
+ if not isinstance(meta, dict):
168
+ return ["matrix: no [meta]"]
169
+ if meta.get("schema") != SCHEMA:
170
+ p.append(f"matrix: schema {meta.get('schema')!r}, this codemap reads {SCHEMA}")
171
+ if not _date(meta.get("as_of")):
172
+ p.append("matrix: meta.as_of is not an ISO date")
173
+ if not isinstance(meta.get("stale_after_days"), int):
174
+ p.append("matrix: meta.stale_after_days must be an integer")
175
+ needs, tools = {}, {}
176
+ for n in matrix.get("need", []):
177
+ nid = n.get("id")
178
+ if not nid or nid in needs:
179
+ p.append(f"need: missing or duplicate id {nid!r}")
180
+ continue
181
+ needs[nid] = n
182
+ if not n.get("title"):
183
+ p.append(f"need {nid}: no title")
184
+ if n.get("codemap") not in COVERAGE:
185
+ p.append(f"need {nid}: codemap {n.get('codemap')!r} not in {COVERAGE}")
186
+ elif n["codemap"] != "none":
187
+ if not n.get("codemap_tests"):
188
+ p.append(f"need {nid}: codemap {n['codemap']} names no test")
189
+ if not n.get("codemap_how"):
190
+ p.append(f"need {nid}: codemap {n['codemap']} without codemap_how")
191
+ for t in matrix.get("tool", []):
192
+ tid = t.get("id")
193
+ if not tid or tid in tools:
194
+ p.append(f"tool: missing or duplicate id {tid!r}")
195
+ continue
196
+ tools[tid] = t
197
+ if not t.get("name") or not t.get("url"):
198
+ p.append(f"tool {tid}: name and url are required")
199
+ w = t.get("watch", {})
200
+ if not isinstance(w, dict) or w.get("kind") not in WATCH_KINDS:
201
+ p.append(f"tool {tid}: watch.kind not in {WATCH_KINDS}")
202
+ elif w["kind"] != "none" and not w.get("name"):
203
+ p.append(f"tool {tid}: watch.kind {w['kind']} needs watch.name")
204
+ langs = t.get("languages", [])
205
+ if not isinstance(langs, list) or any(x not in LANGUAGE_NAMES for x in langs):
206
+ p.append(f"tool {tid}: languages {langs!r} — use names from {sorted(LANGUAGE_NAMES)} "
207
+ "(free text goes to languages_note)")
208
+ bad = [i for i in t.get("interface", []) if i not in INTERFACES]
209
+ if bad:
210
+ p.append(f"tool {tid}: interface {bad} not in {INTERFACES}")
211
+ seen = set()
212
+ for c in matrix.get("claim", []):
213
+ key = (c.get("tool"), c.get("need"))
214
+ where = f"claim {key[0]}×{key[1]}"
215
+ if key in seen:
216
+ p.append(f"{where}: duplicate")
217
+ seen.add(key)
218
+ if key[0] not in tools:
219
+ p.append(f"{where}: unknown tool")
220
+ if key[1] not in needs:
221
+ p.append(f"{where}: unknown need")
222
+ st = c.get("status")
223
+ if st not in STATUSES:
224
+ p.append(f"{where}: status {st!r} not in {STATUSES}")
225
+ continue
226
+ for fld in _REQUIRES[st]:
227
+ if not c.get(fld):
228
+ p.append(f"{where}: status {st} requires {fld}")
229
+ on = c.get("measured_on")
230
+ if on is not None and (not isinstance(on, list) or not on or any(x not in LANGUAGE_NAMES for x in on)):
231
+ p.append(f"{where}: measured_on {on!r} — a non-empty list of language names")
232
+ if c.get("checked") and not _date(c["checked"]):
233
+ p.append(f"{where}: checked is not an ISO date")
234
+ for tid in tools:
235
+ if not any(c.get("tool") == tid for c in matrix.get("claim", [])):
236
+ p.append(f"tool {tid}: no claim")
237
+ # feed
238
+ if feed.get("schema") != SCHEMA:
239
+ p.append(f"feed: schema {feed.get('schema')!r}, this codemap reads {SCHEMA}")
240
+ if not _date(feed.get("as_of")):
241
+ p.append("feed: as_of is not an ISO date")
242
+ for tid, rel in (feed.get("latest") or {}).items():
243
+ if tid not in tools:
244
+ p.append(f"feed latest: unknown tool {tid!r}")
245
+ elif not isinstance(rel, dict) or not rel.get("version"):
246
+ p.append(f"feed latest {tid}: no version")
247
+ for i, item in enumerate(feed.get("news") or []):
248
+ if item.get("kind") not in NEWS_KINDS:
249
+ p.append(f"feed news #{i}: kind {item.get('kind')!r} not in {NEWS_KINDS}")
250
+ if item.get("tool") is not None and item["tool"] not in tools:
251
+ p.append(f"feed news #{i}: unknown tool {item['tool']!r}")
252
+ if not _date(item.get("date")) or not item.get("text") or not item.get("source"):
253
+ p.append(f"feed news #{i}: date, text and source are required")
254
+ if not isinstance(item.get("verified"), bool):
255
+ p.append(f"feed news #{i}: verified must be true or false")
256
+ return p
257
+
258
+
259
+ def github_anchor(heading: str) -> str:
260
+ """GitHub's heading anchor: markdown marks and punctuation dropped, lower case, spaces → hyphens."""
261
+ text = re.sub(r"\[([^\]]*)\]\([^)]*\)", r"\1", heading.strip())
262
+ text = re.sub(r"[^\w\- ]", "", text.lower())
263
+ return text.replace(" ", "-")
264
+
265
+
266
+ def anchors(md: str) -> set[str]:
267
+ out: set[str] = set()
268
+ counts: dict[str, int] = {}
269
+ in_code = False
270
+ for line in md.splitlines():
271
+ if line.lstrip().startswith("```"):
272
+ in_code = not in_code
273
+ continue
274
+ if in_code:
275
+ continue
276
+ m = re.match(r"^#{1,6}\s+(.*?)\s*#*\s*$", line)
277
+ if not m:
278
+ continue
279
+ a = github_anchor(m.group(1))
280
+ n = counts.get(a, 0)
281
+ out.add(a if n == 0 else f"{a}-{n}")
282
+ counts[a] = n + 1
283
+ return out
284
+
285
+
286
+ def repo_problems(matrix: dict, root: Path) -> list[str]:
287
+ """Checks only this repository can make: evidence resolves, cited tests exist, cards are in (design D7)."""
288
+ p: list[str] = []
289
+ cache: dict[str, set[str] | None] = {}
290
+
291
+ def resolves(ref: str) -> str | None:
292
+ path, _, anchor = ref.partition("#")
293
+ if path not in cache:
294
+ f = root / path
295
+ cache[path] = anchors(f.read_text(encoding="utf-8")) if f.is_file() else None
296
+ a = cache[path]
297
+ if a is None:
298
+ return f"{path} does not exist"
299
+ if anchor and anchor not in a:
300
+ return f"no heading #{anchor} in {path}"
301
+ return None
302
+
303
+ for c in matrix.get("claim", []):
304
+ if c.get("evidence"):
305
+ err = resolves(c["evidence"])
306
+ if err:
307
+ p.append(f"claim {c.get('tool')}×{c.get('need')}: evidence {err}")
308
+ for n in matrix.get("need", []):
309
+ for t in n.get("codemap_tests", []):
310
+ fpath, _, fn = t.partition("::")
311
+ f = root / fpath
312
+ if not f.is_file():
313
+ p.append(f"need {n['id']}: test file {fpath} does not exist")
314
+ elif fn and not re.search(rf"^\s*def {re.escape(fn)}\(", f.read_text(encoding="utf-8"), re.M):
315
+ p.append(f"need {n['id']}: no test {fn} in {fpath}")
316
+ named = set()
317
+ for t in matrix.get("tool", []):
318
+ if t.get("card"):
319
+ named.add(t["card"])
320
+ if not (root / t["card"]).is_file():
321
+ p.append(f"tool {t['id']}: card {t['card']} does not exist")
322
+ for card in sorted((root / "research" / "tools").glob("*.md")):
323
+ rel = card.relative_to(root).as_posix()
324
+ if card.name != "README.md" and rel not in named:
325
+ p.append(f"card {rel} has no tool in the matrix")
326
+ return p
327
+
328
+
329
+ # --------------------------------------------------------------------------- answers
330
+
331
+ _RANK = {s: i for i, s in enumerate(STATUSES)}
332
+
333
+
334
+ def _norm_version(v) -> str:
335
+ s = str(v or "").strip().lstrip("vV")
336
+ while s.endswith(".0") and s.count(".") > 1:
337
+ s = s[:-2]
338
+ return s
339
+
340
+
341
+ def evidence_url(cat: Catalog, ref: str | None) -> str | None:
342
+ if not ref:
343
+ return None
344
+ base = cat.meta.get("repo", "https://github.com/kogriv/codemap").rstrip("/")
345
+ return f"{base}/blob/main/{ref}"
346
+
347
+
348
+ def _claim_view(cat: Catalog, c: dict, languages: set[str] | None = None) -> dict:
349
+ t = cat.tools.get(c["tool"], {})
350
+ out = {"tool": c["tool"], "name": t.get("name", c["tool"]), "url": t.get("url"),
351
+ "license": t.get("license"), "interface": t.get("interface", []), "status": c["status"]}
352
+ # A measurement is about the language it ran on (the lab's truth so far is Python). Asked about another
353
+ # language, the claim is only what the tool says about itself: `read`, with where it was measured.
354
+ if c["status"] in ("measured", "probed"):
355
+ on = c.get("measured_on", ["python"])
356
+ out["measured_on"] = list(on)
357
+ if languages and not (set(on) & languages):
358
+ out["status"] = "read"
359
+ out["status_note"] = f"{c['status']} on {', '.join(on)} only; not run on {', '.join(sorted(languages))}"
360
+ for k in ("version", "checked", "summary", "vs_codemap", "reason", "probe"):
361
+ if c.get(k):
362
+ out[k] = c[k]
363
+ if not out.get("probe") and out["status"] in ("read", "probed"):
364
+ out["probe"] = "not scored by the lab: check it on a question whose answer you know first"
365
+ if isinstance(c.get("rank"), int):
366
+ out["_rank"] = c["rank"]
367
+ if c.get("evidence"):
368
+ out["evidence"] = evidence_url(cat, c["evidence"])
369
+ a, ch = _date(cat.meta.get("as_of")), _date(c.get("checked"))
370
+ if a and ch and c["status"] != "read" and (a - ch).days > cat.meta.get("stale_after_days", 180):
371
+ out["stale"] = True
372
+ latest = (cat.feed.get("latest") or {}).get(c["tool"])
373
+ if latest and c.get("version") and c["status"] in ("measured", "probed") \
374
+ and _norm_version(latest.get("version")) != _norm_version(c["version"]):
375
+ out["drift"] = {"measured": c["version"], "latest": latest["version"], "latest_date": latest.get("date")}
376
+ return out
377
+
378
+
379
+ def _order(views: list[dict]) -> list[dict]:
380
+ """Status first (measured before probed before read); within a status the explicit ``rank``, then the
381
+ most recently checked; then the id, so the order is stable."""
382
+ def key(v):
383
+ d = _date(v.get("checked"))
384
+ return (_RANK[v["status"]], v.get("_rank", 99), -(d.toordinal() if d else 0), v["tool"])
385
+ return sorted(views, key=key)
386
+
387
+
388
+ def _codemap_view(n: dict) -> dict:
389
+ out = {"coverage": n["codemap"]}
390
+ for k in ("codemap_how", "codemap_caveat"):
391
+ if n.get(k):
392
+ out[k[len("codemap_"):]] = n[k]
393
+ if n.get("codemap_tests"):
394
+ out["tests"] = list(n["codemap_tests"])
395
+ return out
396
+
397
+
398
+ def _speaks(tool: dict, langs: set[str]) -> bool:
399
+ have = set(tool.get("languages", []))
400
+ return "any" in have or bool(have & langs)
401
+
402
+
403
+ def need_answer(cat: Catalog, nid: str, languages: set[str] | None = None) -> dict:
404
+ """One need. With ``languages``, a tool whose recorded languages include none of them is left out and
405
+ listed in ``excluded`` — never recommended for a language it does not read."""
406
+ n = cat.needs[nid]
407
+ views, excluded = [], []
408
+ for c in cat.claims:
409
+ if c["need"] != nid:
410
+ continue
411
+ t = cat.tools.get(c["tool"], {})
412
+ if languages and not _speaks(t, languages):
413
+ excluded.append({"tool": c["tool"], "status": c["status"], "languages": t.get("languages", []),
414
+ **({"languages_note": t["languages_note"]} if t.get("languages_note") else {})})
415
+ continue
416
+ views.append(_claim_view(cat, c, languages))
417
+ usable = _order([v for v in views if v["status"] != "rejected"])
418
+ rejected = sorted((v for v in views if v["status"] == "rejected"), key=lambda v: v["tool"])
419
+ for v in usable + rejected:
420
+ v.pop("_rank", None)
421
+ out = {"need": nid, "title": n["title"], "languages": n.get("languages", []), "codemap": _codemap_view(n),
422
+ "tools": usable, "rejected": rejected}
423
+ if languages:
424
+ out["language_filter"] = sorted(languages)
425
+ out["excluded"] = sorted(excluded, key=lambda x: x["tool"])
426
+ if n.get("note"):
427
+ out["note"] = n["note"]
428
+ return out
429
+
430
+
431
+ _ALIASES = {"ts": "typescript", "tsx": "typescript", "js": "javascript", "jsx": "javascript", "py": "python",
432
+ "golang": "go", "rs": "rust", "c#": "csharp", "c++": "cpp"}
433
+
434
+
435
+ def _tokens(s: str) -> list[str]:
436
+ return [_ALIASES.get(w, w) for w in re.findall(r"[\w#+]+", s.lower())]
437
+
438
+
439
+ def match_needs(cat: Catalog, query: str) -> list[str]:
440
+ """Need ids that match ``query``: an exact id first; else the needs sharing most words with it."""
441
+ q = query.strip().lower()
442
+ if q in cat.needs:
443
+ return [q]
444
+ words = set(_tokens(q))
445
+ if not words:
446
+ return []
447
+ scored = []
448
+ for nid, n in cat.needs.items():
449
+ hay = set(_tokens(" ".join([nid.replace("-", " "), n.get("title", ""), " ".join(n.get("keywords", [])),
450
+ " ".join(n.get("languages", []))])))
451
+ s = len(words & hay)
452
+ if s:
453
+ scored.append((s, nid))
454
+ if not scored:
455
+ return []
456
+ best = max(s for s, _ in scored)
457
+ return sorted(nid for s, nid in scored if s == best)
458
+
459
+
460
+ def _applies(n: dict, languages: set[str]) -> bool:
461
+ langs = set(n.get("languages", []))
462
+ return not langs or "any" in langs or bool(langs & languages)
463
+
464
+
465
+ def overview(cat: Catalog, languages: list[str] | None = None) -> dict:
466
+ langs = {_ALIASES.get(x.lower(), x.lower()) for x in (languages or [])}
467
+ rows = []
468
+ for nid, n in cat.needs.items():
469
+ if langs and not _applies(n, langs):
470
+ continue
471
+ a = need_answer(cat, nid, langs or None)
472
+ best = a["tools"][0] if a["tools"] else None
473
+ rows.append({"need": nid, "title": n["title"], "codemap": n["codemap"],
474
+ "best": ({"tool": best["tool"], "status": best["status"]} if best else None),
475
+ "tools": len(a["tools"])})
476
+ counts = {s: sum(1 for c in cat.claims if c["status"] == s) for s in STATUSES}
477
+ return {"needs": rows, "claims": counts, "tools": len(cat.tools),
478
+ "languages": sorted(langs) if langs else None}
479
+
480
+
481
+ def tool_answer(cat: Catalog, tid: str) -> dict:
482
+ t = cat.tools[tid]
483
+ claims = [_claim_view(cat, c) | {"need": c["need"]} for c in cat.claims if c["tool"] == tid]
484
+ claims.sort(key=lambda v: (_RANK[v["status"]], v["need"]))
485
+ for v in claims:
486
+ v.pop("_rank", None)
487
+ out = {k: t[k] for k in ("id", "name", "url", "license", "languages", "interface") if k in t}
488
+ if t.get("card"):
489
+ out["card"] = evidence_url(cat, t["card"])
490
+ out["claims"] = claims
491
+ latest = (cat.feed.get("latest") or {}).get(tid)
492
+ if latest:
493
+ out["latest"] = latest
494
+ out["news"] = [n for n in cat.feed.get("news", []) if n.get("tool") == tid]
495
+ return out
496
+
497
+
498
+ def news(cat: Catalog, days: int | None = None, today: date | None = None) -> list[dict]:
499
+ today = today or datetime.now(timezone.utc).date()
500
+ items = sorted(cat.feed.get("news", []), key=lambda n: n["date"], reverse=True)
501
+ if days is not None:
502
+ floor = date.fromordinal(max(1, today.toordinal() - days))
503
+ items = [n for n in items if (_date(n["date"]) or today) >= floor]
504
+ return items
505
+
506
+
507
+ def detect_languages(root: Path, limit: int = 200_000) -> dict[str, int]:
508
+ """File counts per language under ``root``, skipping vendored and generated directories."""
509
+ counts: dict[str, int] = {}
510
+ seen = 0
511
+ for dirpath, dirnames, filenames in os.walk(root):
512
+ dirnames[:] = [d for d in dirnames if d not in _SKIP_DIRS and not d.startswith(".")]
513
+ for fn in filenames:
514
+ lang = LANGUAGES.get(os.path.splitext(fn)[1].lower())
515
+ if lang:
516
+ counts[lang] = counts.get(lang, 0) + 1
517
+ seen += 1
518
+ if seen >= limit:
519
+ return counts
520
+ return counts
521
+
522
+
523
+ def outside_graph(name: str) -> dict | None:
524
+ """``{language, advise}`` when ``name`` points at a source file codemap does not read (design D4)."""
525
+ if not isinstance(name, str):
526
+ return None
527
+ m = _OUTSIDE.match(name.strip())
528
+ if not m:
529
+ return None
530
+ # A dotted Python name can end in `.c` or `.go` too. Without a path separator, only a single-dot name
531
+ # with an extension of two letters or more reads as a file (`app.ts`), never `pkg.mod.c`.
532
+ path, ext = m.group("file"), m.group("ext")
533
+ if "/" not in path and "\\" not in path and (path.count(".") != 1 or len(ext) < 3):
534
+ return None
535
+ lang = LANGUAGES.get(ext.lower())
536
+ if lang is None or lang == "python":
537
+ return None
538
+ return {"language": lang, "advise": {"languages": [lang]}}
539
+
540
+
541
+ def answer(args: dict, cat: Catalog | None = None) -> dict:
542
+ """The MCP/serve entry point: ``{need?, languages?, tool?, news_days?}`` → one answer."""
543
+ cat = cat or load()
544
+ out: dict = {"catalog": cat.header()}
545
+ tool, need, langs = args.get("tool"), args.get("need"), args.get("languages")
546
+ if isinstance(langs, str):
547
+ langs = [langs]
548
+ if tool:
549
+ if tool not in cat.tools:
550
+ out["error"] = f"unknown tool {tool!r}"
551
+ out["tools"] = sorted(cat.tools)
552
+ return out
553
+ out["tool"] = tool_answer(cat, tool)
554
+ elif need:
555
+ ids = match_needs(cat, need)
556
+ if langs:
557
+ want = {_ALIASES.get(x.lower(), x.lower()) for x in langs}
558
+ ids = [i for i in ids if _applies(cat.needs[i], want)] or ids
559
+ if not ids:
560
+ out["error"] = f"no need matches {need!r}"
561
+ out["needs"] = sorted(cat.needs)
562
+ return out
563
+ want = {_ALIASES.get(x.lower(), x.lower()) for x in langs} if langs else None
564
+ out["matches"] = [need_answer(cat, i, want) for i in ids]
565
+ else:
566
+ out["overview"] = overview(cat, langs)
567
+ if args.get("news_days") is not None:
568
+ out["news"] = news(cat, int(args["news_days"]))
569
+ return out