codmap 0.0.31__tar.gz → 0.0.33__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 (168) hide show
  1. {codmap-0.0.31 → codmap-0.0.33}/PKG-INFO +2 -2
  2. {codmap-0.0.31 → codmap-0.0.33}/README.md +1 -1
  3. {codmap-0.0.31 → codmap-0.0.33}/codemap/cli.py +33 -2
  4. {codmap-0.0.31 → codmap-0.0.33}/codemap/extract/roots.py +31 -9
  5. {codmap-0.0.31 → codmap-0.0.33}/codemap/model.py +8 -1
  6. {codmap-0.0.31 → codmap-0.0.33}/codemap/serve/mcp_server.py +8 -2
  7. {codmap-0.0.31 → codmap-0.0.33}/codemap/serve/review.py +74 -4
  8. {codmap-0.0.31 → codmap-0.0.33}/codemap/serve/session.py +33 -1
  9. {codmap-0.0.31 → codmap-0.0.33}/codmap.egg-info/PKG-INFO +2 -2
  10. {codmap-0.0.31 → codmap-0.0.33}/codmap.egg-info/SOURCES.txt +3 -0
  11. {codmap-0.0.31 → codmap-0.0.33}/pyproject.toml +1 -1
  12. {codmap-0.0.31 → codmap-0.0.33}/tests/test_m15_review.py +3 -1
  13. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c81_protocol_dispatch.py +30 -0
  14. codmap-0.0.33/tests/test_r1c85_mcp_graph_currency.py +122 -0
  15. codmap-0.0.33/tests/test_r1c87_review_path_base.py +110 -0
  16. codmap-0.0.33/tests/test_r1c89_review_docs.py +63 -0
  17. {codmap-0.0.31 → codmap-0.0.33}/LICENSE +0 -0
  18. {codmap-0.0.31 → codmap-0.0.33}/codemap/__init__.py +0 -0
  19. {codmap-0.0.31 → codmap-0.0.33}/codemap/apidiff.py +0 -0
  20. {codmap-0.0.31 → codmap-0.0.33}/codemap/arch.py +0 -0
  21. {codmap-0.0.31 → codmap-0.0.33}/codemap/diagnostics.py +0 -0
  22. {codmap-0.0.31 → codmap-0.0.33}/codemap/extract/__init__.py +0 -0
  23. {codmap-0.0.31 → codmap-0.0.33}/codemap/extract/attrflow.py +0 -0
  24. {codmap-0.0.31 → codmap-0.0.33}/codemap/extract/behavior.py +0 -0
  25. {codmap-0.0.31 → codmap-0.0.33}/codemap/extract/dataflow.py +0 -0
  26. {codmap-0.0.31 → codmap-0.0.33}/codemap/extract/dispatch.py +0 -0
  27. {codmap-0.0.31 → codmap-0.0.33}/codemap/extract/griffe_extractor.py +0 -0
  28. {codmap-0.0.31 → codmap-0.0.33}/codemap/extract/gsource.py +0 -0
  29. {codmap-0.0.31 → codmap-0.0.33}/codemap/extract/probe.py +0 -0
  30. {codmap-0.0.31 → codmap-0.0.33}/codemap/extract/union.py +0 -0
  31. {codmap-0.0.31 → codmap-0.0.33}/codemap/freshness.py +0 -0
  32. {codmap-0.0.31 → codmap-0.0.33}/codemap/incremental.py +0 -0
  33. {codmap-0.0.31 → codmap-0.0.33}/codemap/integrations/__init__.py +0 -0
  34. {codmap-0.0.31 → codmap-0.0.33}/codemap/integrations/base.py +0 -0
  35. {codmap-0.0.31 → codmap-0.0.33}/codemap/integrations/cocoindex.py +0 -0
  36. {codmap-0.0.31 → codmap-0.0.33}/codemap/integrations/gate.py +0 -0
  37. {codmap-0.0.31 → codmap-0.0.33}/codemap/integrations/gitnexus.py +0 -0
  38. {codmap-0.0.31 → codmap-0.0.33}/codemap/integrations/registry.py +0 -0
  39. {codmap-0.0.31 → codmap-0.0.33}/codemap/integrations/transport.py +0 -0
  40. {codmap-0.0.31 → codmap-0.0.33}/codemap/provenance.py +0 -0
  41. {codmap-0.0.31 → codmap-0.0.33}/codemap/query.py +0 -0
  42. {codmap-0.0.31 → codmap-0.0.33}/codemap/scope.py +0 -0
  43. {codmap-0.0.31 → codmap-0.0.33}/codemap/serve/__init__.py +0 -0
  44. {codmap-0.0.31 → codmap-0.0.33}/codemap/serve/_scip_pb2.py +0 -0
  45. {codmap-0.0.31 → codmap-0.0.33}/codemap/serve/api_surface.py +0 -0
  46. {codmap-0.0.31 → codmap-0.0.33}/codemap/serve/apidiff.py +0 -0
  47. {codmap-0.0.31 → codmap-0.0.33}/codemap/serve/architecture.py +0 -0
  48. {codmap-0.0.31 → codmap-0.0.33}/codemap/serve/audit.py +0 -0
  49. {codmap-0.0.31 → codmap-0.0.33}/codemap/serve/check.py +0 -0
  50. {codmap-0.0.31 → codmap-0.0.33}/codemap/serve/ctags.py +0 -0
  51. {codmap-0.0.31 → codmap-0.0.33}/codemap/serve/currency.py +0 -0
  52. {codmap-0.0.31 → codmap-0.0.33}/codemap/serve/impact.py +0 -0
  53. {codmap-0.0.31 → codmap-0.0.33}/codemap/serve/limits.py +0 -0
  54. {codmap-0.0.31 → codmap-0.0.33}/codemap/serve/livingdocs.py +0 -0
  55. {codmap-0.0.31 → codmap-0.0.33}/codemap/serve/mermaid.py +0 -0
  56. {codmap-0.0.31 → codmap-0.0.33}/codemap/serve/pack.py +0 -0
  57. {codmap-0.0.31 → codmap-0.0.33}/codemap/serve/rag.py +0 -0
  58. {codmap-0.0.31 → codmap-0.0.33}/codemap/serve/scip.py +0 -0
  59. {codmap-0.0.31 → codmap-0.0.33}/codemap/serve/semantic.py +0 -0
  60. {codmap-0.0.31 → codmap-0.0.33}/codemap/serve/server.py +0 -0
  61. {codmap-0.0.31 → codmap-0.0.33}/codemap/serve/subsystems.py +0 -0
  62. {codmap-0.0.31 → codmap-0.0.33}/codemap/serve/vault.py +0 -0
  63. {codmap-0.0.31 → codmap-0.0.33}/codemap/store.py +0 -0
  64. {codmap-0.0.31 → codmap-0.0.33}/codemap/tomlio.py +0 -0
  65. {codmap-0.0.31 → codmap-0.0.33}/codemap/watch.py +0 -0
  66. {codmap-0.0.31 → codmap-0.0.33}/codmap.egg-info/dependency_links.txt +0 -0
  67. {codmap-0.0.31 → codmap-0.0.33}/codmap.egg-info/entry_points.txt +0 -0
  68. {codmap-0.0.31 → codmap-0.0.33}/codmap.egg-info/requires.txt +0 -0
  69. {codmap-0.0.31 → codmap-0.0.33}/codmap.egg-info/top_level.txt +0 -0
  70. {codmap-0.0.31 → codmap-0.0.33}/setup.cfg +0 -0
  71. {codmap-0.0.31 → codmap-0.0.33}/tests/test_epistemic.py +0 -0
  72. {codmap-0.0.31 → codmap-0.0.33}/tests/test_gitnexus_router.py +0 -0
  73. {codmap-0.0.31 → codmap-0.0.33}/tests/test_impact_depth.py +0 -0
  74. {codmap-0.0.31 → codmap-0.0.33}/tests/test_integrations.py +0 -0
  75. {codmap-0.0.31 → codmap-0.0.33}/tests/test_issue3_serve_freshness.py +0 -0
  76. {codmap-0.0.31 → codmap-0.0.33}/tests/test_livingdocs.py +0 -0
  77. {codmap-0.0.31 → codmap-0.0.33}/tests/test_m0_api_surface.py +0 -0
  78. {codmap-0.0.31 → codmap-0.0.33}/tests/test_m11_argcontract.py +0 -0
  79. {codmap-0.0.31 → codmap-0.0.33}/tests/test_m12_dataflow.py +0 -0
  80. {codmap-0.0.31 → codmap-0.0.33}/tests/test_m16_architecture.py +0 -0
  81. {codmap-0.0.31 → codmap-0.0.33}/tests/test_m17_mcp.py +0 -0
  82. {codmap-0.0.31 → codmap-0.0.33}/tests/test_m18_freshness.py +0 -0
  83. {codmap-0.0.31 → codmap-0.0.33}/tests/test_m1_5_semantics.py +0 -0
  84. {codmap-0.0.31 → codmap-0.0.33}/tests/test_m1_query.py +0 -0
  85. {codmap-0.0.31 → codmap-0.0.33}/tests/test_m2_views.py +0 -0
  86. {codmap-0.0.31 → codmap-0.0.33}/tests/test_m32_watch.py +0 -0
  87. {codmap-0.0.31 → codmap-0.0.33}/tests/test_m3_serve.py +0 -0
  88. {codmap-0.0.31 → codmap-0.0.33}/tests/test_m4_behavior.py +0 -0
  89. {codmap-0.0.31 → codmap-0.0.33}/tests/test_m5_deep.py +0 -0
  90. {codmap-0.0.31 → codmap-0.0.33}/tests/test_m6_repo_scope.py +0 -0
  91. {codmap-0.0.31 → codmap-0.0.33}/tests/test_m7_dispatch.py +0 -0
  92. {codmap-0.0.31 → codmap-0.0.33}/tests/test_m9_family.py +0 -0
  93. {codmap-0.0.31 → codmap-0.0.33}/tests/test_pack_honesty.py +0 -0
  94. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c13_callgraph_accuracy.py +0 -0
  95. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c13_grep_vs_graph.py +0 -0
  96. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c16_semantic.py +0 -0
  97. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c20_attribute_edges.py +0 -0
  98. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c21_flat_layout.py +0 -0
  99. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c22_source_visible_refs.py +0 -0
  100. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c23_hard_python.py +0 -0
  101. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c24_test_mapping.py +0 -0
  102. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c25_provenance.py +0 -0
  103. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c26_deep_union.py +0 -0
  104. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c27_config_honesty.py +0 -0
  105. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c28_limit_envelope.py +0 -0
  106. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c29_lazy_imports.py +0 -0
  107. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c2_ctags.py +0 -0
  108. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c30_local_import_calls.py +0 -0
  109. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c30f1_reexport_calls.py +0 -0
  110. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c30f2_check_scope.py +0 -0
  111. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c31_path_origin.py +0 -0
  112. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c32_report_json.py +0 -0
  113. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c33_query_signature.py +0 -0
  114. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c34_signature_kinds.py +0 -0
  115. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c35_contract_location.py +0 -0
  116. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c36_target_resolution.py +0 -0
  117. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c37_rule_mutation.py +0 -0
  118. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c38_tool_drift.py +0 -0
  119. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c39_edge_resolution.py +0 -0
  120. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c3_arch_contract.py +0 -0
  121. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c3_dogfood.py +0 -0
  122. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c40_flow_reach.py +0 -0
  123. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c41_scope_membership.py +0 -0
  124. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c42_deep_tier_stability.py +0 -0
  125. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c43_incremental_splice.py +0 -0
  126. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c44_absent_answers.py +0 -0
  127. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c45_repeat_union.py +0 -0
  128. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c46_shadowed_definitions.py +0 -0
  129. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c47_incremental_resample.py +0 -0
  130. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c48_type_checking_imports.py +0 -0
  131. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c49_type_only_cycles.py +0 -0
  132. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c4_complexity.py +0 -0
  133. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c50_flow_entry_points.py +0 -0
  134. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c53_narrowing_declared.py +0 -0
  135. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c54_deterministic_rendering.py +0 -0
  136. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c55_override_grade.py +0 -0
  137. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c56_stub_files.py +0 -0
  138. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c57_facade_package.py +0 -0
  139. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c58_cycle_tangles.py +0 -0
  140. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c59_completeness_drop.py +0 -0
  141. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c5_apidiff.py +0 -0
  142. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c60_nested_definitions.py +0 -0
  143. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c62_phantom_rules.py +0 -0
  144. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c63_answer_format.py +0 -0
  145. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c64_dependency_probe.py +0 -0
  146. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c66_pack_direction.py +0 -0
  147. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c68_dotted_imports.py +0 -0
  148. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c69_contract_validation.py +0 -0
  149. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c6_pack.py +0 -0
  150. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c70_check_graph_currency.py +0 -0
  151. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c71_attribute_chain_calls.py +0 -0
  152. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c72_flat_inference_in_packages.py +0 -0
  153. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c73_cli_version.py +0 -0
  154. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c74_call_site_conservation.py +0 -0
  155. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c75_reexported_class_calls.py +0 -0
  156. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c76_contract_table_typo.py +0 -0
  157. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c77_gate_probe_battery.py +0 -0
  158. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c78_forbidden_chains.py +0 -0
  159. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c7_edge_vocab.py +0 -0
  160. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c80_tests_through_helpers.py +0 -0
  161. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c82_review_changed_lines.py +0 -0
  162. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c83_foreign_graph_paths.py +0 -0
  163. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c84_missing_roots.py +0 -0
  164. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c8_deadcode.py +0 -0
  165. {codmap-0.0.31 → codmap-0.0.33}/tests/test_r1c9_incremental.py +0 -0
  166. {codmap-0.0.31 → codmap-0.0.33}/tests/test_scip_export.py +0 -0
  167. {codmap-0.0.31 → codmap-0.0.33}/tests/test_scope.py +0 -0
  168. {codmap-0.0.31 → codmap-0.0.33}/tests/test_subsystems.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: codmap
3
- Version: 0.0.31
3
+ Version: 0.0.33
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
@@ -44,7 +44,7 @@ and a **SCIP index** for interop with Sourcegraph / Glean and other precise-code
44
44
 
45
45
  [![CI](https://github.com/kogriv/codemap/actions/workflows/ci.yml/badge.svg)](https://github.com/kogriv/codemap/actions/workflows/ci.yml)
46
46
 
47
- **Status:** 🟢 M0–M20 implemented + research track (R1/R2) — schema 0.13, **1228 tests with no failures on
47
+ **Status:** 🟢 M0–M20 implemented + research track (R1/R2) — schema 0.13, **1249 tests with no failures on
48
48
  Python 3.11–3.14** ([in CI](docs/ci.md): the full suite including the dogfood pass, a determinism check, a
49
49
  wheel smoke test, and ctags/SCIP interop against the real CLIs), warm serve surface with 31 ops (28 exposed
50
50
  as MCP tools), and SCIP export. See **[DESIGN.md](DESIGN.md)** (product design &
@@ -8,7 +8,7 @@ and a **SCIP index** for interop with Sourcegraph / Glean and other precise-code
8
8
 
9
9
  [![CI](https://github.com/kogriv/codemap/actions/workflows/ci.yml/badge.svg)](https://github.com/kogriv/codemap/actions/workflows/ci.yml)
10
10
 
11
- **Status:** 🟢 M0–M20 implemented + research track (R1/R2) — schema 0.13, **1228 tests with no failures on
11
+ **Status:** 🟢 M0–M20 implemented + research track (R1/R2) — schema 0.13, **1249 tests with no failures on
12
12
  Python 3.11–3.14** ([in CI](docs/ci.md): the full suite including the dogfood pass, a determinism check, a
13
13
  wheel smoke test, and ctags/SCIP interop against the real CLIs), warm serve surface with 31 ops (28 exposed
14
14
  as MCP tools), and SCIP export. See **[DESIGN.md](DESIGN.md)** (product design &
@@ -96,10 +96,28 @@ def _graph_from(args):
96
96
  if getattr(args, "build", None):
97
97
  return extract(args.build, deep=getattr(args, "deep", False))
98
98
  if getattr(args, "graph", None):
99
- return store.load(args.graph)
99
+ graph = store.load(args.graph)
100
+ if getattr(args, "func", None) not in (_cmd_check, _cmd_serve):
101
+ _warn_if_behind(args.graph, graph)
102
+ return graph
100
103
  raise SystemExit("error: need --graph <file> or --build <path>")
101
104
 
102
105
 
106
+ def _warn_if_behind(path: str, graph) -> None:
107
+ """R1-C85 D4: a cold read of a graph behind its tree says so, once, on stderr.
108
+
109
+ `check` prints its own currency line and `serve` puts it in every envelope; every
110
+ other reader of `--graph` answered about an older tree without a word. Silent when
111
+ current or unknown, so stdout and exit codes never change.
112
+ """
113
+ from codemap.serve.currency import graph_currency
114
+ c = graph_currency(path, (graph.provenance or {}).get("scope_id"))
115
+ if c.get("status") == "behind":
116
+ print(f"[warning] {path} is behind its source tree ({c.get('added', 0)} added, "
117
+ f"{c.get('changed', 0)} changed, {c.get('removed', 0)} removed since it was "
118
+ "built) — answers describe the older tree; rebuild", file=sys.stderr)
119
+
120
+
103
121
  def _refuse_bad_roots(args) -> bool:
104
122
  """R1-C84: print every unreadable ``--consumer``/``--docs`` root; True means refuse (exit 2).
105
123
 
@@ -757,6 +775,15 @@ def _cmd_review(args) -> int:
757
775
  print(json.dumps(build_review(q, hunks=hunks, base_graph=base), indent=2, sort_keys=True))
758
776
  else:
759
777
  print(render_review(q, hunks=hunks, base_graph=base), end="")
778
+ # R1-C87 D3: Python files in the diff and none of them in the graph is not "nothing
779
+ # touched" — it is a diff this graph cannot review.
780
+ from codemap.serve.review import place_files
781
+ pl = place_files(q, [h["file"] for h in hunks])
782
+ if pl["unplaced"] and not pl["placed"]:
783
+ print(f"error: none of the {len(pl['unplaced'])} Python file(s) in the diff is in this "
784
+ "graph — nothing was reviewed (check the diff's path base or the graph's roots)",
785
+ file=sys.stderr)
786
+ return 2
760
787
  return 0
761
788
 
762
789
 
@@ -939,7 +966,8 @@ def _cmd_serve(args) -> int:
939
966
  """
940
967
  from codemap.serve.session import Session
941
968
  session = Session(_graph_from(args), source_root=args.source_root,
942
- graph_path=getattr(args, "graph", None))
969
+ graph_path=getattr(args, "graph", None),
970
+ currency_ttl=getattr(args, "currency_ttl", 10.0))
943
971
  if getattr(args, "watch", False):
944
972
  _start_reload_watcher(session, args)
945
973
  if getattr(args, "mcp", False):
@@ -1189,6 +1217,9 @@ def build_parser() -> argparse.ArgumentParser:
1189
1217
  _add_source(s)
1190
1218
  s.add_argument("--source-root", help="Base dir for the `source` op to read files "
1191
1219
  "(node paths are repo-relative; default: cwd).")
1220
+ s.add_argument("--currency-ttl", type=float, default=10.0, metavar="SECONDS",
1221
+ help="How long a check of the graph against the source tree is reused "
1222
+ "in answers (`currency`, R1-C85); 0 checks on every call. Default 10.")
1192
1223
  s.add_argument("--mcp", action="store_true",
1193
1224
  help="Serve over the Model Context Protocol instead of JSON "
1194
1225
  "(needs the optional 'mcp' extra: pip install 'codemap[mcp]').")
@@ -343,13 +343,13 @@ def _scan_consumer_module(graph, py, base, label, tree, index, mode, origin=None
343
343
  if mode == "full":
344
344
  # R1-C81 D4: `fc = _spec().build().fit(df); fc.band(…)` — calls on objects whose
345
345
  # type a constructor or a return annotation names.
346
- for src, target in _typed_calls(graph, tree, mod_id, symbol_map, index, func_ranges, dead):
346
+ for src, target, res in _typed_calls(graph, tree, mod_id, symbol_map, index, func_ranges, dead):
347
347
  if (src, target) not in uses:
348
- uses[(src, target)] = {"called": True, "shapes": [], "local": False, "typed": True}
348
+ uses[(src, target)] = {"called": True, "shapes": [], "local": False, "typed": res}
349
349
 
350
350
  for (src, target), entry in sorted(uses.items()):
351
351
  etype = "calls" if entry["called"] else "references"
352
- extras = {"resolution": "typed" if entry.get("typed") else
352
+ extras = {"resolution": entry["typed"] if entry.get("typed") else
353
353
  "local" if entry["local"] else "imported"}
354
354
  if etype == "calls" and entry["shapes"]:
355
355
  extras.update(_arg_contract(entry["shapes"]))
@@ -373,6 +373,11 @@ class _Typer:
373
373
  for e in graph.edges:
374
374
  if e.type == "export":
375
375
  self.exports.setdefault((e.source, e.target.rsplit(".", 1)[-1]), e.target)
376
+ # R1-C88: Protocol → its implementers, for a method the Protocol does not declare
377
+ self.implementers: dict[str, list[str]] = {}
378
+ for e in graph.edges:
379
+ if e.type == "implements":
380
+ self.implementers.setdefault(e.target, []).append(e.source)
376
381
  self.helpers = {n.name: n for n in tree.body
377
382
  if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))}
378
383
  self._helper_types: dict[str, str | None] = {}
@@ -442,6 +447,19 @@ class _Typer:
442
447
  def method(self, cls: str | None, name: str) -> str | None:
443
448
  return self.classes.methods(cls).get(name) if cls else None
444
449
 
450
+ def outside_protocol(self, cls: str | None, name: str) -> list[str]:
451
+ """``name`` absent from Protocol ``cls``: the implementers' methods that have it (R1-C88).
452
+
453
+ bquearch calls ``fc.member_values(…)`` after a ``hasattr`` check on an object typed
454
+ ``PathForecaster``; only some implementations define it. Fanned out like a Protocol
455
+ call (heuristic), and never for a concrete class — a missing attribute there is not
456
+ guessed.
457
+ """
458
+ if not cls or cls not in self.implementers or self.method(cls, name):
459
+ return []
460
+ return sorted({m for c in self.implementers[cls]
461
+ if (m := self.classes.methods(c).get(name))})
462
+
445
463
  def env_of(self, fnode) -> dict:
446
464
  assigned: dict[str, list] = {}
447
465
  for n in ast.walk(fnode):
@@ -469,7 +487,7 @@ class _Typer:
469
487
 
470
488
 
471
489
  def _typed_calls(graph, tree, mod_id, symbol_map, index, func_ranges, dead):
472
- """(source id, core method id) for calls on typed receivers in a consumer module."""
490
+ """(source id, core method id, resolution) for calls on typed receivers in a consumer module."""
473
491
  typer = _Typer(graph, tree, symbol_map, index)
474
492
  out: set[tuple[str, str]] = set()
475
493
  for fnode in ast.walk(tree):
@@ -481,12 +499,16 @@ def _typed_calls(graph, tree, mod_id, symbol_map, index, func_ranges, dead):
481
499
  for call in ast.walk(fnode):
482
500
  if not (isinstance(call, ast.Call) and isinstance(call.func, ast.Attribute)):
483
501
  continue
484
- mid = typer.method(typer.type_of(call.func.value, env), call.func.attr)
485
- if mid is None or mid not in graph.nodes:
486
- continue
502
+ recv = typer.type_of(call.func.value, env)
503
+ mid = typer.method(recv, call.func.attr)
487
504
  src = _source_for(call, mod_id, func_ranges)
488
- if src != mid:
489
- out.add((src, mid))
505
+ if mid is None:
506
+ for m in typer.outside_protocol(recv, call.func.attr):
507
+ if m != src:
508
+ out.add((src, m, "protocol"))
509
+ continue
510
+ if mid in graph.nodes and src != mid:
511
+ out.add((src, mid, "typed"))
490
512
  return sorted(out)
491
513
 
492
514
 
@@ -125,7 +125,14 @@ SCHEMA_VERSION = "0.13"
125
125
  # over-approximation (registry or Protocol fan-out) is `low`, and the caveat says so;
126
126
  # Protocol implementers are linked structurally and consumer-root calls on typed receivers
127
127
  # resolve (R1-C81, docs/design/protocol_dispatch.md).
128
- ANSWER_FORMAT = 7
128
+ # 8 — `review` places diff paths by a unique suffix when they do not match exactly, and reports
129
+ # `mapped_paths`, `unplaced_files`, `skipped_files`; `unresolved_hunks` keeps only lines in
130
+ # placed files; nothing placed is exit 2 (R1-C87, docs/design/review_path_base.md).
131
+ # 9 — every serve/MCP envelope carries `currency` (the served graph against the tree now,
132
+ # cached `--currency-ttl` seconds, `checked_seconds_ago`); `stats` shows it beside
133
+ # `freshness` (R1-C85, docs/design/mcp_graph_currency.md); `review` names the doc pages a
134
+ # diff changes (`changed_docs`, R1-C89, docs/design/review_docs.md).
135
+ ANSWER_FORMAT = 9
129
136
 
130
137
  # Closed vocabulary of edge types (R1-C7). Node ``kind`` is deliberately an OPEN set
131
138
  # (DESIGN §2 — new entity kinds may appear), but edges are TYPED: every relationship
@@ -34,7 +34,10 @@ _INSTRUCTIONS = (
34
34
  "carries a `resolved.ambiguous` flag — check it before trusting the answer. "
35
35
  "Any tool that takes a `limit` always returns a `limit` block "
36
36
  "`{applied, returned, total, truncated}` — read it before concluding a list is "
37
- "complete; `total: null` means the total was not observable, not that it is zero."
37
+ "complete; `total: null` means the total was not observable, not that it is zero. "
38
+ "Every response carries `currency`: `behind` means the source tree changed since the "
39
+ "graph was built, so the answer describes the older tree — say so, or rebuild and "
40
+ "`reload` before relying on it."
38
41
  )
39
42
 
40
43
 
@@ -113,7 +116,10 @@ def build_mcp_server(session: "Session", name: str = "codemap") -> Any:
113
116
  def stats() -> dict:
114
117
  """Graph overview: target, schema version, node/edge counts by kind/type, and
115
118
  `freshness` for the graph ACTUALLY served — `stale: true` (+reason) if the
116
- on-disk artifact was rebuilt after this server loaded it. Call `reload` then."""
119
+ on-disk artifact was rebuilt after this server loaded it. Call `reload` then.
120
+ `currency` (also in EVERY answer's envelope) is the content check: `behind` means
121
+ the source tree changed since this graph was built, so answers describe the older
122
+ tree — rebuild, then `reload`."""
117
123
  return op("stats")
118
124
 
119
125
  @server.tool()
@@ -73,6 +73,42 @@ def _module_dossier(query: Query, sid: str, node) -> dict:
73
73
  }
74
74
 
75
75
 
76
+ def place_files(query: Query, files: list[str]) -> dict:
77
+ """Diff paths → graph paths: exact, else a unique suffix match either way (R1-C87 D1).
78
+
79
+ A diff is relative to the git root; a graph to the common parent of its build roots
80
+ (R1-C31). Built from a subdirectory, the two differ, and an exact-only match turned a
81
+ real change into "0 changed symbol(s)". Placed by a suffix at a ``/`` boundary — the
82
+ diff longer (``research/shared/x.py`` → ``shared/x.py``) or the graph longer — and only
83
+ when exactly one graph file fits; several are named, not chosen between.
84
+ """
85
+ known = {n.file for n in query.graph.nodes.values() if n.file}
86
+ placed: dict[str, str] = {}
87
+ mapped: dict[str, str] = {}
88
+ unplaced: list[dict] = []
89
+ skipped: list[str] = []
90
+ for f in dict.fromkeys(files):
91
+ if f in known:
92
+ placed[f] = f
93
+ continue
94
+ cands = sorted(g for g in known if f.endswith("/" + g) or g.endswith("/" + f))
95
+ if len(cands) == 1:
96
+ placed[f] = mapped[f] = cands[0]
97
+ elif f.endswith((".py", ".pyi")):
98
+ unplaced.append({"file": f, "candidates": cands})
99
+ else:
100
+ skipped.append(f)
101
+ return {"placed": placed, "mapped": mapped, "unplaced": unplaced, "skipped": skipped}
102
+
103
+
104
+ def _doc_entry(query: Query, doc_id: str) -> dict:
105
+ """A changed doc page and the symbols it documents (R1-C89)."""
106
+ node = query.graph.nodes.get(doc_id)
107
+ documents = sorted({e.target for e in query.graph.edges
108
+ if e.source == doc_id and e.type == "references"})
109
+ return {"doc": doc_id, "file": node.file if node else None, "documents": documents}
110
+
111
+
76
112
  def build_symbol_dossier(query: Query, sid: str) -> dict:
77
113
  """Everything a reviewer needs about one changed symbol (F17)."""
78
114
  node = query.graph.nodes.get(sid)
@@ -109,7 +145,8 @@ def build_review(query: Query, *, hunks: list[dict] | None = None,
109
145
 
110
146
  Returns ``{changed: [dossier…], summary}`` with dossiers risk-sorted (highest
111
147
  first). ``summary`` carries the symbol count, union blast-radius by root, and
112
- the count of unresolved hunks (module-level / unknown files) so nothing is
148
+ the count of unresolved hunks (lines in placed files outside any symbol) and, apart
149
+ from them, the diff files not in the graph (R1-C87) so nothing is
113
150
  silently dropped.
114
151
 
115
152
  ``base_graph`` (R1-C5): a 'before' graph to API-diff against. Hunk-based review
@@ -119,9 +156,18 @@ def build_review(query: Query, *, hunks: list[dict] | None = None,
119
156
  """
120
157
  ids = set(symbols or [])
121
158
  unresolved = []
159
+ placement = place_files(query, [h["file"] for h in hunks or []])
160
+ # R1-C89: a doc page is a node without lines; its hunks name the page, not nothing.
161
+ doc_of = {n.file: n.id for n in query.graph.nodes.values() if n.kind == "doc" and n.file}
162
+ docs: set[str] = set()
122
163
  if hunks:
123
164
  for h in hunks:
124
- file = h["file"]
165
+ file = placement["placed"].get(h["file"])
166
+ if file is None:
167
+ continue # R1-C87 D2: reported as unplaced, not as unresolved
168
+ if file in doc_of:
169
+ docs.add(doc_of[file])
170
+ continue
125
171
  for rng in h.get("ranges", []):
126
172
  start, end = int(rng[0]), int(rng[-1])
127
173
  got = query.symbols_in_range(file, start, end)
@@ -147,8 +193,13 @@ def build_review(query: Query, *, hunks: list[dict] | None = None,
147
193
  "blast_by_root": union_by_root,
148
194
  "high_risk": [d["symbol"] for d in dossiers if d["risk"] == "high"],
149
195
  "unresolved_hunks": unresolved,
196
+ "changed_docs": len(docs),
197
+ "mapped_paths": placement["mapped"],
198
+ "unplaced_files": placement["unplaced"],
199
+ "skipped_files": placement["skipped"],
150
200
  }
151
- result = {"changed": dossiers, "summary": summary}
201
+ result = {"changed": dossiers, "summary": summary,
202
+ "changed_docs": [_doc_entry(query, d) for d in sorted(docs)]}
152
203
  if base_graph is not None:
153
204
  from codemap.serve.apidiff import build_apidiff
154
205
  result["api_diff"] = build_apidiff(base_graph, query.graph)
@@ -161,8 +212,27 @@ def render_review(query: Query, *, hunks: list[dict] | None = None,
161
212
  rv = build_review(query, hunks=hunks, symbols=symbols, base_graph=base_graph)
162
213
  s = rv["summary"]
163
214
  out = ["# Change-set review", ""]
215
+ if s["unplaced_files"]:
216
+ names = ", ".join(u["file"] + (f" (ambiguous: {', '.join(u['candidates'])})"
217
+ if u["candidates"] else "") for u in s["unplaced_files"])
218
+ out.append(f"**{len(s['unplaced_files'])} Python file(s) in the diff are not in this graph "
219
+ f"— nothing in them was reviewed**: {names}. Build the graph over them, or check "
220
+ f"the diff's path base (`git diff --relative=<dir>`).")
164
221
  out.append(f"**{s['changed_symbols']} changed symbol(s)**; "
165
222
  f"blast by root: {s['blast_by_root'] or '—'}.")
223
+ if rv["changed_docs"]:
224
+ out.append(f"**{len(rv['changed_docs'])} changed doc page(s)** — check they still "
225
+ f"describe the code:")
226
+ for d in rv["changed_docs"]:
227
+ names = d["documents"]
228
+ more = f" (+{len(names) - 8} more)" if len(names) > 8 else ""
229
+ out.append(f"- `{d['file'] or d['doc']}` documents {', '.join(names[:8]) or '—'}{more}")
230
+ if s["mapped_paths"]:
231
+ out.append("_Diff paths placed in the graph by suffix: " + ", ".join(
232
+ f"`{a}` → `{b}`" for a, b in sorted(s["mapped_paths"].items())) + "._")
233
+ if s["skipped_files"] and not s["changed_symbols"] and not s["unplaced_files"]:
234
+ out.append(f"_{len(s['skipped_files'])} non-Python file(s) in the diff, not part of a "
235
+ f"code graph: {', '.join(s['skipped_files'])}._")
166
236
  if "api_diff" in rv:
167
237
  ad = rv["api_diff"]["summary"]
168
238
  out.append(f"**API diff vs baseline:** {ad['breaking_total']} breaking, "
@@ -170,7 +240,7 @@ def render_review(query: Query, *, hunks: list[dict] | None = None,
170
240
  if s["high_risk"]:
171
241
  out.append(f"**Review first (high risk):** {', '.join(s['high_risk'])}")
172
242
  if s["unresolved_hunks"]:
173
- out.append(f"_Unresolved hunks (module-level / unknown file): "
243
+ out.append(f"_Unresolved hunks (lines outside any symbol): "
174
244
  f"{len(s['unresolved_hunks'])} — inspect manually._")
175
245
  out.append("")
176
246
  if "api_diff" in rv:
@@ -334,8 +334,14 @@ class Session:
334
334
  """A warm, in-memory query surface over one graph."""
335
335
 
336
336
  def __init__(self, graph: Graph, source_root: str | None = None,
337
- graph_path: str | None = None) -> None:
337
+ graph_path: str | None = None, currency_ttl: float = 10.0) -> None:
338
338
  self.graph = graph
339
+ # R1-C85: is the served graph the tree it answers about? Checked like `check
340
+ # --graph` (R1-C70), cached for `currency_ttl` seconds — the check walks the tree
341
+ # (40–110 ms median measured) and an envelope is built on every call.
342
+ self.currency_ttl = currency_ttl
343
+ self._currency_cache: tuple[float, dict] | None = None
344
+ self._currency_checks = 0
339
345
  self.query = Query(graph)
340
346
  # F12: base dir to resolve node.file for the `source` op (node paths are
341
347
  # repo-relative, e.g. `bquant/…`). Defaults to cwd; best-effort.
@@ -405,6 +411,8 @@ class Session:
405
411
  "answer_format": ANSWER_FORMAT}
406
412
  except Exception as exc: # a bad arg must not kill the resident process
407
413
  return {"ok": False, "error": f"{type(exc).__name__}: {exc}"}
414
+ # R1-C85: which tree this answer is about. Always present (R1-C28).
415
+ env["currency"] = self._currency()
408
416
  r = self._resolution
409
417
  # R1-C44 / D2: three-way, not a truthiness test. "not found" is the one case the
410
418
  # block exists for and was the one case `if r and …` threw away.
@@ -477,6 +485,8 @@ class Session:
477
485
  fr = freshness(self.graph_path, served_mtime=self._served_mtime)
478
486
  if fr is not None:
479
487
  out["freshness"] = fr
488
+ # R1-C85 D3: time (freshness) and content (currency), side by side.
489
+ out["currency"] = self._currency()
480
490
  # R1-C21: same spirit as freshness — say when the graph may be *vacuous* (0 import
481
491
  # edges from a layout the extractor didn't understand), rather than letting every
482
492
  # downstream conclusion silently inherit the emptiness.
@@ -490,6 +500,27 @@ class Session:
490
500
  out["diagnostics"] = diags
491
501
  return out
492
502
 
503
+ def _currency(self) -> dict:
504
+ """The served graph against the tree now, cached for ``currency_ttl`` seconds (R1-C85)."""
505
+ import time
506
+ now = time.monotonic()
507
+ c = self._currency_cache
508
+ if c is None or now - c[0] >= self.currency_ttl: # ttl 0: every call
509
+ self._currency_checks += 1
510
+ if not self.graph_path:
511
+ res = {"status": "unknown",
512
+ "reason": "served from an in-process build; no build recipe to "
513
+ "compare against"}
514
+ else:
515
+ from codemap.serve.currency import graph_currency
516
+ res = graph_currency(self.graph_path,
517
+ (self.graph.provenance or {}).get("scope_id"))
518
+ if res.get("status") == "behind":
519
+ res["hint"] = ("the source tree changed since this graph was built — "
520
+ "rebuild it, then `reload` (or run `serve --watch`)")
521
+ c = self._currency_cache = (now, res)
522
+ return {**c[1], "checked_seconds_ago": round(now - c[0])}
523
+
493
524
  @staticmethod
494
525
  def _tool_drift() -> dict | None:
495
526
  # The two sides must be read differently or there is nothing to compare (R1-C38-f1):
@@ -524,6 +555,7 @@ class Session:
524
555
  self.graph = graph
525
556
  self.query = Query(graph)
526
557
  self._served_mtime = self._current_mtime()
558
+ self._currency_cache = None # R1-C85: a new graph is checked afresh
527
559
  after = {"nodes": len(graph.nodes), "edges": len(graph.edges)}
528
560
  out = {"reloaded": True, "before": before, "after": after,
529
561
  "changed": before != after,
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: codmap
3
- Version: 0.0.31
3
+ Version: 0.0.33
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
@@ -44,7 +44,7 @@ and a **SCIP index** for interop with Sourcegraph / Glean and other precise-code
44
44
 
45
45
  [![CI](https://github.com/kogriv/codemap/actions/workflows/ci.yml/badge.svg)](https://github.com/kogriv/codemap/actions/workflows/ci.yml)
46
46
 
47
- **Status:** 🟢 M0–M20 implemented + research track (R1/R2) — schema 0.13, **1228 tests with no failures on
47
+ **Status:** 🟢 M0–M20 implemented + research track (R1/R2) — schema 0.13, **1249 tests with no failures on
48
48
  Python 3.11–3.14** ([in CI](docs/ci.md): the full suite including the dogfood pass, a determinism check, a
49
49
  wheel smoke test, and ctags/SCIP interop against the real CLIs), warm serve surface with 31 ops (28 exposed
50
50
  as MCP tools), and SCIP export. See **[DESIGN.md](DESIGN.md)** (product design &
@@ -156,6 +156,9 @@ tests/test_r1c81_protocol_dispatch.py
156
156
  tests/test_r1c82_review_changed_lines.py
157
157
  tests/test_r1c83_foreign_graph_paths.py
158
158
  tests/test_r1c84_missing_roots.py
159
+ tests/test_r1c85_mcp_graph_currency.py
160
+ tests/test_r1c87_review_path_base.py
161
+ tests/test_r1c89_review_docs.py
159
162
  tests/test_r1c8_deadcode.py
160
163
  tests/test_r1c9_incremental.py
161
164
  tests/test_scip_export.py
@@ -9,7 +9,7 @@ build-backend = "setuptools.build_meta"
9
9
  # version. README says this plainly, since `pip install codmap` / `import codemap` is a
10
10
  # seam a reader will otherwise hit by surprise.
11
11
  name = "codmap"
12
- version = "0.0.31"
12
+ version = "0.0.33"
13
13
  description = "Static analyzer that turns a package's source into a queryable code graph."
14
14
  readme = "README.md"
15
15
  # M20/D1: measured, not assumed. Each release of the declared range runs the full suite in
@@ -66,7 +66,9 @@ def test_review_summary_counts_and_sorts(q):
66
66
 
67
67
  def test_review_reports_unresolved_hunks(q):
68
68
  rv = build_review(q, hunks=[{"file": "flowpkg/nope.py", "ranges": [[1, 9]]}])
69
- assert rv["summary"]["unresolved_hunks"] == [{"file": "flowpkg/nope.py", "range": [1, 9]}]
69
+ # R1-C87: a file not in the graph is "unplaced", apart from unresolved lines in known files
70
+ assert rv["summary"]["unresolved_hunks"] == []
71
+ assert rv["summary"]["unplaced_files"] == [{"file": "flowpkg/nope.py", "candidates": []}]
70
72
  assert rv["summary"]["changed_symbols"] == 0
71
73
 
72
74
 
@@ -185,3 +185,33 @@ def test_D2_core_callers_fan_out_in_a_single_package_build(tmp_path):
185
185
  fan = {(e.source, e.target) for e in g.edges
186
186
  if e.type == "calls" and e.extras.get("resolution") == "protocol"}
187
187
  assert (P + "evaluate", P + "KnnB.band") in fan
188
+
189
+
190
+ # -- R1-C88: a method outside the Protocol --------------------------------------
191
+
192
+ def test_R1C88_a_method_outside_the_protocol_fans_out_to_those_that_have_it(tmp_path):
193
+ root = tmp_path
194
+ (root / "pkg").mkdir()
195
+ (root / "pkg" / "__init__.py").write_text("")
196
+ (root / "pkg" / "menu.py").write_text(
197
+ MENU + "\n\nclass KnnC(Base):\n def fit(self, frame) -> 'KnnC':\n return self\n\n"
198
+ " def member_values(self, q, k):\n return []\n\n\n"
199
+ "class KnnD(KnnC):\n def fit(self, frame) -> 'KnnD':\n return self\n\n\n"
200
+ "def _knnb_member_values(self, q, k):\n return []\n\n\nKnnB.member_values = _knnb_member_values\n")
201
+ (root / "tests").mkdir()
202
+ (root / "tests" / "test_m.py").write_text(
203
+ "from pkg.menu import Spec, KnnA\n\n\n"
204
+ "def test_outside():\n fc = Spec().build().fit([1])\n fc.member_values(1, 3)\n\n\n"
205
+ "def test_nobody_has_it():\n Spec().build().nothing_like_this()\n\n\n"
206
+ "def test_concrete_missing():\n KnnA().member_values(1, 3)\n")
207
+ q = Query(extract_repo(str(root / "pkg"), consumers=(str(root / "tests"),), mode="full"))
208
+ fan = {(s.rsplit(".", 1)[1], t) for s, t in _calls(q, "protocol") if s.startswith("tests.")}
209
+ assert ("test_outside", P + "KnnC.member_values") in fan
210
+ # KnnC defines it and KnnD inherits it (one method, one edge); KnnA/KnnB do not have it
211
+ # as a method in the graph (KnnB's is a module-level assignment), so they get nothing
212
+ assert {t for s, t in fan if s == "test_outside" and t.endswith(".member_values")} == {
213
+ P + "KnnC.member_values"}
214
+ assert P + "KnnD" in q.implementers(P + "PathForecaster")
215
+ assert not any(s in ("test_nobody_has_it", "test_concrete_missing") for s, _ in fan)
216
+ r = q.tests_for(P + "KnnC.member_values")
217
+ assert {t["id"]: t["confidence"] for t in r["tests"]} == {"tests.test_m.test_outside": "low"}
@@ -0,0 +1,122 @@
1
+ """R1-C85 — every served answer says whether its graph matches the tree.
2
+
3
+ Design `docs/design/mcp_graph_currency.md` (pre-registered 79a7fd2).
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from pathlib import Path
9
+
10
+ import pytest
11
+
12
+ from codemap import store
13
+ from codemap.cli import main
14
+ from codemap.extract import extract
15
+ from codemap.serve.session import Session
16
+
17
+
18
+ @pytest.fixture
19
+ def built(tmp_path, monkeypatch):
20
+ pkg = tmp_path / "pkg"
21
+ pkg.mkdir()
22
+ (pkg / "__init__.py").write_text("")
23
+ (pkg / "m.py").write_text("def f():\n return 1\n")
24
+ monkeypatch.chdir(tmp_path)
25
+ g = tmp_path / "g.json"
26
+ assert main(["build", "pkg", "-o", str(g)]) == 0
27
+ return tmp_path, g
28
+
29
+
30
+ def _session(g, ttl=10.0):
31
+ return Session(store.load(str(g)), graph_path=str(g), currency_ttl=ttl)
32
+
33
+
34
+ def _edit(root):
35
+ (root / "pkg" / "m.py").write_text("def f():\n return 2\n")
36
+
37
+
38
+ def test_E1_every_envelope_carries_currency(built):
39
+ root, g = built
40
+ s = _session(g, ttl=0)
41
+ for op, args in (("stats", {}), ("search", {"term": "f"}), ("query", {"name": "f"})):
42
+ env = s.handle({"op": op, "args": args})
43
+ assert env["ok"] and env["currency"]["status"] == "current", (op, env.get("currency"))
44
+ _edit(root)
45
+ c = s.handle({"op": "search", "args": {"term": "f"}})["currency"]
46
+ assert c["status"] == "behind" and c["changed"] == 1 and "rebuild" in c["hint"]
47
+
48
+
49
+ def test_E1_an_in_process_build_is_unknown_with_a_reason(built):
50
+ root, _ = built
51
+ s = Session(extract(str(root / "pkg")))
52
+ c = s.handle({"op": "stats"})["currency"]
53
+ assert c["status"] == "unknown" and "in-process build" in c["reason"]
54
+
55
+
56
+ def test_E2_the_check_is_cached_for_the_ttl(built):
57
+ _, g = built
58
+ s = _session(g, ttl=10)
59
+ for _ in range(5):
60
+ s.handle({"op": "search", "args": {"term": "f"}})
61
+ assert s._currency_checks == 1
62
+ s0 = _session(g, ttl=0)
63
+ for _ in range(3):
64
+ s0.handle({"op": "search", "args": {"term": "f"}})
65
+ assert s0._currency_checks == 3
66
+
67
+
68
+ def test_E2_a_cached_answer_states_its_age(built):
69
+ _, g = built
70
+ c = _session(g).handle({"op": "search", "args": {"term": "f"}})["currency"]
71
+ assert c["checked_seconds_ago"] == 0
72
+
73
+
74
+ def test_E3_reload_drops_the_cache(built):
75
+ root, g = built
76
+ s = _session(g, ttl=3600)
77
+ assert s.handle({"op": "stats"})["currency"]["status"] == "current"
78
+ _edit(root)
79
+ assert s.handle({"op": "stats"})["currency"]["status"] == "current" # cached, by design
80
+ assert main(["build", "pkg", "-o", str(g)]) == 0
81
+ s.handle({"op": "reload"})
82
+ assert s.handle({"op": "stats"})["currency"]["status"] == "current"
83
+ _edit(root) # same content as the rebuild: still current; now change it again
84
+ (root / "pkg" / "m.py").write_text("def f():\n return 3\n")
85
+ s.handle({"op": "reload"}) # the graph on disk is the older one
86
+ assert s.handle({"op": "stats"})["currency"]["status"] == "behind"
87
+
88
+
89
+ def test_D3_stats_shows_currency_beside_freshness(built):
90
+ _, g = built
91
+ r = _session(g).handle({"op": "stats"})["result"]
92
+ assert "freshness" in r and r["currency"]["status"] == "current"
93
+
94
+
95
+ def test_E4_a_cold_cli_read_warns_when_behind(built, capsys):
96
+ root, g = built
97
+ capsys.readouterr()
98
+ assert main(["query", "f", "--graph", str(g)]) == 0
99
+ before = capsys.readouterr()
100
+ assert before.err == ""
101
+ _edit(root)
102
+ assert main(["query", "f", "--graph", str(g)]) == 0
103
+ after = capsys.readouterr()
104
+ assert after.out == before.out
105
+ assert "[warning]" in after.err and "behind its source tree" in after.err and "1 changed" in after.err
106
+
107
+
108
+ def test_E4_check_keeps_its_own_line_and_gets_no_second_warning(built, capsys):
109
+ root, g = built
110
+ _edit(root)
111
+ capsys.readouterr()
112
+ main(["check", "--graph", str(g)])
113
+ assert "[warning]" not in capsys.readouterr().err
114
+
115
+
116
+ def test_D1_it_is_the_served_graph_that_is_judged_not_the_file_on_disk(built):
117
+ """Edit, rebuild on disk, no reload: the file matches the tree, the served graph does not."""
118
+ root, g = built
119
+ s = _session(g, ttl=0)
120
+ _edit(root)
121
+ assert main(["build", "pkg", "-o", str(g)]) == 0
122
+ assert s.handle({"op": "stats"})["currency"]["status"] == "behind"