codmap 0.0.29__tar.gz → 0.0.31__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 (165) hide show
  1. {codmap-0.0.29 → codmap-0.0.31}/PKG-INFO +4 -3
  2. {codmap-0.0.29 → codmap-0.0.31}/README.md +3 -2
  3. {codmap-0.0.29 → codmap-0.0.31}/codemap/extract/attrflow.py +121 -0
  4. {codmap-0.0.29 → codmap-0.0.31}/codemap/extract/dispatch.py +136 -0
  5. {codmap-0.0.29 → codmap-0.0.31}/codemap/extract/griffe_extractor.py +5 -1
  6. {codmap-0.0.29 → codmap-0.0.31}/codemap/extract/roots.py +146 -1
  7. {codmap-0.0.29 → codmap-0.0.31}/codemap/model.py +18 -1
  8. {codmap-0.0.29 → codmap-0.0.31}/codemap/query.py +36 -9
  9. {codmap-0.0.29 → codmap-0.0.31}/codemap/serve/review.py +112 -15
  10. {codmap-0.0.29 → codmap-0.0.31}/codmap.egg-info/PKG-INFO +4 -3
  11. {codmap-0.0.29 → codmap-0.0.31}/codmap.egg-info/SOURCES.txt +2 -0
  12. {codmap-0.0.29 → codmap-0.0.31}/pyproject.toml +1 -1
  13. {codmap-0.0.29 → codmap-0.0.31}/tests/test_m15_review.py +4 -2
  14. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c24_test_mapping.py +12 -7
  15. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c39_edge_resolution.py +22 -3
  16. codmap-0.0.31/tests/test_r1c81_protocol_dispatch.py +187 -0
  17. codmap-0.0.31/tests/test_r1c82_review_changed_lines.py +163 -0
  18. {codmap-0.0.29 → codmap-0.0.31}/LICENSE +0 -0
  19. {codmap-0.0.29 → codmap-0.0.31}/codemap/__init__.py +0 -0
  20. {codmap-0.0.29 → codmap-0.0.31}/codemap/apidiff.py +0 -0
  21. {codmap-0.0.29 → codmap-0.0.31}/codemap/arch.py +0 -0
  22. {codmap-0.0.29 → codmap-0.0.31}/codemap/cli.py +0 -0
  23. {codmap-0.0.29 → codmap-0.0.31}/codemap/diagnostics.py +0 -0
  24. {codmap-0.0.29 → codmap-0.0.31}/codemap/extract/__init__.py +0 -0
  25. {codmap-0.0.29 → codmap-0.0.31}/codemap/extract/behavior.py +0 -0
  26. {codmap-0.0.29 → codmap-0.0.31}/codemap/extract/dataflow.py +0 -0
  27. {codmap-0.0.29 → codmap-0.0.31}/codemap/extract/gsource.py +0 -0
  28. {codmap-0.0.29 → codmap-0.0.31}/codemap/extract/probe.py +0 -0
  29. {codmap-0.0.29 → codmap-0.0.31}/codemap/extract/union.py +0 -0
  30. {codmap-0.0.29 → codmap-0.0.31}/codemap/freshness.py +0 -0
  31. {codmap-0.0.29 → codmap-0.0.31}/codemap/incremental.py +0 -0
  32. {codmap-0.0.29 → codmap-0.0.31}/codemap/integrations/__init__.py +0 -0
  33. {codmap-0.0.29 → codmap-0.0.31}/codemap/integrations/base.py +0 -0
  34. {codmap-0.0.29 → codmap-0.0.31}/codemap/integrations/cocoindex.py +0 -0
  35. {codmap-0.0.29 → codmap-0.0.31}/codemap/integrations/gate.py +0 -0
  36. {codmap-0.0.29 → codmap-0.0.31}/codemap/integrations/gitnexus.py +0 -0
  37. {codmap-0.0.29 → codmap-0.0.31}/codemap/integrations/registry.py +0 -0
  38. {codmap-0.0.29 → codmap-0.0.31}/codemap/integrations/transport.py +0 -0
  39. {codmap-0.0.29 → codmap-0.0.31}/codemap/provenance.py +0 -0
  40. {codmap-0.0.29 → codmap-0.0.31}/codemap/scope.py +0 -0
  41. {codmap-0.0.29 → codmap-0.0.31}/codemap/serve/__init__.py +0 -0
  42. {codmap-0.0.29 → codmap-0.0.31}/codemap/serve/_scip_pb2.py +0 -0
  43. {codmap-0.0.29 → codmap-0.0.31}/codemap/serve/api_surface.py +0 -0
  44. {codmap-0.0.29 → codmap-0.0.31}/codemap/serve/apidiff.py +0 -0
  45. {codmap-0.0.29 → codmap-0.0.31}/codemap/serve/architecture.py +0 -0
  46. {codmap-0.0.29 → codmap-0.0.31}/codemap/serve/audit.py +0 -0
  47. {codmap-0.0.29 → codmap-0.0.31}/codemap/serve/check.py +0 -0
  48. {codmap-0.0.29 → codmap-0.0.31}/codemap/serve/ctags.py +0 -0
  49. {codmap-0.0.29 → codmap-0.0.31}/codemap/serve/currency.py +0 -0
  50. {codmap-0.0.29 → codmap-0.0.31}/codemap/serve/impact.py +0 -0
  51. {codmap-0.0.29 → codmap-0.0.31}/codemap/serve/limits.py +0 -0
  52. {codmap-0.0.29 → codmap-0.0.31}/codemap/serve/livingdocs.py +0 -0
  53. {codmap-0.0.29 → codmap-0.0.31}/codemap/serve/mcp_server.py +0 -0
  54. {codmap-0.0.29 → codmap-0.0.31}/codemap/serve/mermaid.py +0 -0
  55. {codmap-0.0.29 → codmap-0.0.31}/codemap/serve/pack.py +0 -0
  56. {codmap-0.0.29 → codmap-0.0.31}/codemap/serve/rag.py +0 -0
  57. {codmap-0.0.29 → codmap-0.0.31}/codemap/serve/scip.py +0 -0
  58. {codmap-0.0.29 → codmap-0.0.31}/codemap/serve/semantic.py +0 -0
  59. {codmap-0.0.29 → codmap-0.0.31}/codemap/serve/server.py +0 -0
  60. {codmap-0.0.29 → codmap-0.0.31}/codemap/serve/session.py +0 -0
  61. {codmap-0.0.29 → codmap-0.0.31}/codemap/serve/subsystems.py +0 -0
  62. {codmap-0.0.29 → codmap-0.0.31}/codemap/serve/vault.py +0 -0
  63. {codmap-0.0.29 → codmap-0.0.31}/codemap/store.py +0 -0
  64. {codmap-0.0.29 → codmap-0.0.31}/codemap/tomlio.py +0 -0
  65. {codmap-0.0.29 → codmap-0.0.31}/codemap/watch.py +0 -0
  66. {codmap-0.0.29 → codmap-0.0.31}/codmap.egg-info/dependency_links.txt +0 -0
  67. {codmap-0.0.29 → codmap-0.0.31}/codmap.egg-info/entry_points.txt +0 -0
  68. {codmap-0.0.29 → codmap-0.0.31}/codmap.egg-info/requires.txt +0 -0
  69. {codmap-0.0.29 → codmap-0.0.31}/codmap.egg-info/top_level.txt +0 -0
  70. {codmap-0.0.29 → codmap-0.0.31}/setup.cfg +0 -0
  71. {codmap-0.0.29 → codmap-0.0.31}/tests/test_epistemic.py +0 -0
  72. {codmap-0.0.29 → codmap-0.0.31}/tests/test_gitnexus_router.py +0 -0
  73. {codmap-0.0.29 → codmap-0.0.31}/tests/test_impact_depth.py +0 -0
  74. {codmap-0.0.29 → codmap-0.0.31}/tests/test_integrations.py +0 -0
  75. {codmap-0.0.29 → codmap-0.0.31}/tests/test_issue3_serve_freshness.py +0 -0
  76. {codmap-0.0.29 → codmap-0.0.31}/tests/test_livingdocs.py +0 -0
  77. {codmap-0.0.29 → codmap-0.0.31}/tests/test_m0_api_surface.py +0 -0
  78. {codmap-0.0.29 → codmap-0.0.31}/tests/test_m11_argcontract.py +0 -0
  79. {codmap-0.0.29 → codmap-0.0.31}/tests/test_m12_dataflow.py +0 -0
  80. {codmap-0.0.29 → codmap-0.0.31}/tests/test_m16_architecture.py +0 -0
  81. {codmap-0.0.29 → codmap-0.0.31}/tests/test_m17_mcp.py +0 -0
  82. {codmap-0.0.29 → codmap-0.0.31}/tests/test_m18_freshness.py +0 -0
  83. {codmap-0.0.29 → codmap-0.0.31}/tests/test_m1_5_semantics.py +0 -0
  84. {codmap-0.0.29 → codmap-0.0.31}/tests/test_m1_query.py +0 -0
  85. {codmap-0.0.29 → codmap-0.0.31}/tests/test_m2_views.py +0 -0
  86. {codmap-0.0.29 → codmap-0.0.31}/tests/test_m32_watch.py +0 -0
  87. {codmap-0.0.29 → codmap-0.0.31}/tests/test_m3_serve.py +0 -0
  88. {codmap-0.0.29 → codmap-0.0.31}/tests/test_m4_behavior.py +0 -0
  89. {codmap-0.0.29 → codmap-0.0.31}/tests/test_m5_deep.py +0 -0
  90. {codmap-0.0.29 → codmap-0.0.31}/tests/test_m6_repo_scope.py +0 -0
  91. {codmap-0.0.29 → codmap-0.0.31}/tests/test_m7_dispatch.py +0 -0
  92. {codmap-0.0.29 → codmap-0.0.31}/tests/test_m9_family.py +0 -0
  93. {codmap-0.0.29 → codmap-0.0.31}/tests/test_pack_honesty.py +0 -0
  94. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c13_callgraph_accuracy.py +0 -0
  95. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c13_grep_vs_graph.py +0 -0
  96. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c16_semantic.py +0 -0
  97. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c20_attribute_edges.py +0 -0
  98. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c21_flat_layout.py +0 -0
  99. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c22_source_visible_refs.py +0 -0
  100. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c23_hard_python.py +0 -0
  101. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c25_provenance.py +0 -0
  102. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c26_deep_union.py +0 -0
  103. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c27_config_honesty.py +0 -0
  104. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c28_limit_envelope.py +0 -0
  105. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c29_lazy_imports.py +0 -0
  106. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c2_ctags.py +0 -0
  107. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c30_local_import_calls.py +0 -0
  108. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c30f1_reexport_calls.py +0 -0
  109. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c30f2_check_scope.py +0 -0
  110. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c31_path_origin.py +0 -0
  111. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c32_report_json.py +0 -0
  112. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c33_query_signature.py +0 -0
  113. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c34_signature_kinds.py +0 -0
  114. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c35_contract_location.py +0 -0
  115. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c36_target_resolution.py +0 -0
  116. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c37_rule_mutation.py +0 -0
  117. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c38_tool_drift.py +0 -0
  118. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c3_arch_contract.py +0 -0
  119. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c3_dogfood.py +0 -0
  120. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c40_flow_reach.py +0 -0
  121. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c41_scope_membership.py +0 -0
  122. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c42_deep_tier_stability.py +0 -0
  123. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c43_incremental_splice.py +0 -0
  124. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c44_absent_answers.py +0 -0
  125. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c45_repeat_union.py +0 -0
  126. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c46_shadowed_definitions.py +0 -0
  127. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c47_incremental_resample.py +0 -0
  128. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c48_type_checking_imports.py +0 -0
  129. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c49_type_only_cycles.py +0 -0
  130. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c4_complexity.py +0 -0
  131. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c50_flow_entry_points.py +0 -0
  132. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c53_narrowing_declared.py +0 -0
  133. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c54_deterministic_rendering.py +0 -0
  134. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c55_override_grade.py +0 -0
  135. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c56_stub_files.py +0 -0
  136. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c57_facade_package.py +0 -0
  137. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c58_cycle_tangles.py +0 -0
  138. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c59_completeness_drop.py +0 -0
  139. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c5_apidiff.py +0 -0
  140. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c60_nested_definitions.py +0 -0
  141. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c62_phantom_rules.py +0 -0
  142. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c63_answer_format.py +0 -0
  143. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c64_dependency_probe.py +0 -0
  144. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c66_pack_direction.py +0 -0
  145. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c68_dotted_imports.py +0 -0
  146. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c69_contract_validation.py +0 -0
  147. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c6_pack.py +0 -0
  148. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c70_check_graph_currency.py +0 -0
  149. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c71_attribute_chain_calls.py +0 -0
  150. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c72_flat_inference_in_packages.py +0 -0
  151. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c73_cli_version.py +0 -0
  152. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c74_call_site_conservation.py +0 -0
  153. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c75_reexported_class_calls.py +0 -0
  154. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c76_contract_table_typo.py +0 -0
  155. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c77_gate_probe_battery.py +0 -0
  156. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c78_forbidden_chains.py +0 -0
  157. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c7_edge_vocab.py +0 -0
  158. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c80_tests_through_helpers.py +0 -0
  159. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c83_foreign_graph_paths.py +0 -0
  160. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c84_missing_roots.py +0 -0
  161. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c8_deadcode.py +0 -0
  162. {codmap-0.0.29 → codmap-0.0.31}/tests/test_r1c9_incremental.py +0 -0
  163. {codmap-0.0.29 → codmap-0.0.31}/tests/test_scip_export.py +0 -0
  164. {codmap-0.0.29 → codmap-0.0.31}/tests/test_scope.py +0 -0
  165. {codmap-0.0.29 → codmap-0.0.31}/tests/test_subsystems.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: codmap
3
- Version: 0.0.29
3
+ Version: 0.0.31
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, **1207 tests with no failures on
47
+ **Status:** 🟢 M0–M20 implemented + research track (R1/R2) — schema 0.13, **1228 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 &
@@ -222,7 +222,8 @@ codemap serve --graph graph.json --watch
222
222
  (Ca/Ce/instability), god-objects & call-hubs, per-function complexity (cyclomatic / MI)
223
223
  blended with structural coupling.
224
224
  - **Impact / blast radius** — who uses X, across the whole repo (core + tests + docs).
225
- - **Change review** — a diff → the symbols it touches, their callers, signature-change surface,
225
+ - **Change review** — a diff → the symbols its changed lines touch (context lines and comments
226
+ between definitions are not changes), their callers or readers, signature-change surface,
226
227
  touched columns, cross-root consumers, risk rank.
227
228
  - **Dispatch seams** — registry/factory families and the Protocol each impl satisfies.
228
229
  - **Dataflow** — producers/consumers of a string-keyed DataFrame column.
@@ -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, **1207 tests with no failures on
11
+ **Status:** 🟢 M0–M20 implemented + research track (R1/R2) — schema 0.13, **1228 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 &
@@ -186,7 +186,8 @@ codemap serve --graph graph.json --watch
186
186
  (Ca/Ce/instability), god-objects & call-hubs, per-function complexity (cyclomatic / MI)
187
187
  blended with structural coupling.
188
188
  - **Impact / blast radius** — who uses X, across the whole repo (core + tests + docs).
189
- - **Change review** — a diff → the symbols it touches, their callers, signature-change surface,
189
+ - **Change review** — a diff → the symbols its changed lines touch (context lines and comments
190
+ between definitions are not changes), their callers or readers, signature-change surface,
190
191
  touched columns, cross-root consumers, risk rank.
191
192
  - **Dispatch seams** — registry/factory families and the Protocol each impl satisfies.
192
193
  - **Dataflow** — producers/consumers of a string-keyed DataFrame column.
@@ -106,6 +106,16 @@ def add_attrflow(graph, griffe_root, target_pkg: str, *, deep: bool = False,
106
106
  edges.add((node_id, attr_id, access, resolution))
107
107
  if counts["out"]:
108
108
  graph.nodes[node_id].extras["attr_access"] = counts
109
+ # R1-C82 D3b: module-level code and class bodies read constants too — the
110
+ # import-time check `if set(SURFACES) != set(SURFACE_NAMES): raise` is exactly
111
+ # the reader a review of SURFACE_NAMES must name. Source: the module / class.
112
+ for src_id, scope, cls_bound in _non_function_scopes(tree, modpath):
113
+ if src_id not in graph.nodes:
114
+ continue
115
+ for attr_id, access in _scope_name_reads(scope, cls_bound, graph, modpath,
116
+ imports, modmembers, pkg):
117
+ if attr_id != src_id:
118
+ edges.add((src_id, attr_id, access, "name"))
109
119
 
110
120
  for src, attr_id, access, resolution in sorted(edges):
111
121
  graph.add_edge(Edge("accesses", src, attr_id,
@@ -149,6 +159,7 @@ def _own_attr_uses(fnode, graph, modpath, members, imports, modmembers, pkg, scr
149
159
  # Attributes that are the callee of a call (``self.foo()``) are *method calls*,
150
160
  # handled by the behavioral layer — not field access. Skip exactly those.
151
161
  call_funcs = {id(n.func) for n in nodes if isinstance(n, ast.Call)}
162
+ yield from _module_name_uses(fnode, nodes, graph, modpath, imports, modmembers, pkg)
152
163
 
153
164
  for node in nodes:
154
165
  if isinstance(node, ast.Call) and isinstance(node.func, ast.Name):
@@ -195,6 +206,116 @@ def _own_attr_uses(fnode, graph, modpath, members, imports, modmembers, pkg, scr
195
206
  yield from _deep_attr(node, graph, pkg, script)
196
207
 
197
208
 
209
+ def _bound_names(fnode, nodes) -> tuple[set[str], set[str]]:
210
+ """(names bound locally in the function, names declared ``global``)."""
211
+ bound: set[str] = set()
212
+ a = fnode.args
213
+ for arg in (*a.posonlyargs, *a.args, *a.kwonlyargs, a.vararg, a.kwarg):
214
+ if arg is not None:
215
+ bound.add(arg.arg)
216
+ glob: set[str] = set()
217
+ for n in nodes:
218
+ if isinstance(n, ast.Name) and isinstance(n.ctx, (ast.Store, ast.Del)):
219
+ bound.add(n.id)
220
+ elif isinstance(n, (ast.Import, ast.ImportFrom)):
221
+ bound.update((al.asname or al.name).split(".")[0] for al in n.names)
222
+ elif isinstance(n, ast.ExceptHandler) and n.name:
223
+ bound.add(n.name)
224
+ elif isinstance(n, ast.Global):
225
+ glob.update(n.names)
226
+ elif isinstance(n, ast.arg):
227
+ bound.add(n.arg) # lambda parameters
228
+ return bound - glob, glob
229
+
230
+
231
+ def _module_name_uses(fnode, nodes, graph, modpath, imports, modmembers, pkg):
232
+ """Bare-name reads of a module attribute: ``x in NAMES`` (R1-C82 D3).
233
+
234
+ ``from pkg.contracts import NAMES`` gave only an ``export`` edge and a read of the
235
+ name inside a function gave none, so a module constant had "no consumers" in
236
+ ``review``/``impact`` while being read everywhere. Resolved through the module's
237
+ imports or its own members; emitted only onto a real ``attribute`` node. A local
238
+ binding of the same name shadows it. Unresolved bare names are not counted —
239
+ nearly all of them are locals and builtins. Fast tier.
240
+ """
241
+ bound, glob = _bound_names(fnode, nodes)
242
+ for n in nodes:
243
+ if not isinstance(n, ast.Name):
244
+ continue
245
+ if isinstance(n.ctx, ast.Load):
246
+ if n.id in bound:
247
+ continue
248
+ access = "read"
249
+ elif isinstance(n.ctx, ast.Store) and n.id in glob:
250
+ access = "write" # global NAME; NAME = …
251
+ else:
252
+ continue
253
+ if n.id in imports:
254
+ tgt = imports[n.id]
255
+ if not tgt.startswith(pkg):
256
+ continue
257
+ elif n.id in modmembers:
258
+ tgt = f"{modpath}.{n.id}"
259
+ else:
260
+ continue
261
+ if _is_attribute_node(graph, tgt):
262
+ yield tgt, access, "name"
263
+
264
+
265
+ _SCOPE_BARRIERS = (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef, ast.Lambda)
266
+
267
+
268
+ def _scope_walk(stmts):
269
+ """Every node of ``stmts`` that belongs to this scope — not into defs, classes, lambdas."""
270
+ todo = list(stmts)
271
+ while todo:
272
+ n = todo.pop()
273
+ yield n
274
+ if isinstance(n, _SCOPE_BARRIERS):
275
+ # decorators, defaults and bases are evaluated in the enclosing scope
276
+ if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef)):
277
+ todo.extend(n.decorator_list)
278
+ todo.extend(d for d in (*n.args.defaults, *n.args.kw_defaults) if d is not None)
279
+ elif isinstance(n, ast.ClassDef):
280
+ todo.extend((*n.decorator_list, *n.bases, *(k.value for k in n.keywords)))
281
+ continue
282
+ todo.extend(ast.iter_child_nodes(n))
283
+
284
+
285
+ def _non_function_scopes(tree, modpath):
286
+ """(source id, nodes, names bound in that scope or None) for the module and each class body."""
287
+ yield modpath, list(_scope_walk(tree.body)), None
288
+
289
+ def classes(stmts, prefix):
290
+ for st in stmts:
291
+ if isinstance(st, ast.ClassDef):
292
+ cid = f"{prefix}.{st.name}"
293
+ nodes = list(_scope_walk(st.body))
294
+ bound = {n.id for n in nodes if isinstance(n, ast.Name)
295
+ and isinstance(n.ctx, (ast.Store, ast.Del))}
296
+ yield cid, nodes, bound
297
+ yield from classes(st.body, cid)
298
+ yield from classes(tree.body, modpath)
299
+
300
+
301
+ def _scope_name_reads(nodes, cls_bound, graph, modpath, imports, modmembers, pkg):
302
+ for n in nodes:
303
+ if not (isinstance(n, ast.Name) and isinstance(n.ctx, ast.Load)):
304
+ continue
305
+ if cls_bound is not None and n.id in cls_bound:
306
+ continue
307
+ if n.id in imports:
308
+ tgt = imports[n.id]
309
+ if not tgt.startswith(pkg):
310
+ continue
311
+ elif n.id in modmembers:
312
+ tgt = f"{modpath}.{n.id}"
313
+ else:
314
+ continue
315
+ if _is_attribute_node(graph, tgt):
316
+ yield tgt, "read"
317
+
318
+
198
319
  def _deep_attr(node, graph, pkg, script):
199
320
  """Resolve ``obj.field`` via jedi (deep tier); yield (attr_id | None, access, 'deep').
200
321
 
@@ -246,3 +246,139 @@ def _literal_key(call):
246
246
  and isinstance(call.args[0].value, str):
247
247
  return call.args[0].value
248
248
  return None
249
+
250
+
251
+ # -- R1-C81: structural Protocol implementers and Protocol dispatch -----------------
252
+
253
+ _PROTOCOL_BASES = ("typing.Protocol", "typing_extensions.Protocol")
254
+
255
+
256
+ def _param_shape(signature: str | None):
257
+ """(positional names, *args?, keyword-only names, **kwargs?) without self/cls; None if unparsable.
258
+
259
+ Annotations and defaults are ignored on purpose: a structural match asks whether
260
+ the same call sites fit, and those are decided by names and kinds.
261
+ """
262
+ if not signature or "(" not in signature:
263
+ return None
264
+ try:
265
+ fn = ast.parse("def f" + signature[signature.index("("):] + ": ...").body[0]
266
+ except (SyntaxError, ValueError):
267
+ return None
268
+ a = fn.args
269
+ pos = [x.arg for x in (*a.posonlyargs, *a.args)]
270
+ if pos and pos[0] in ("self", "cls"):
271
+ pos = pos[1:]
272
+ return (tuple(pos), a.vararg is not None, tuple(x.arg for x in a.kwonlyargs),
273
+ a.kwarg is not None)
274
+
275
+
276
+ class _ClassIndex:
277
+ """Methods of each class with inheritance, from `contains` / `inherits` edges."""
278
+
279
+ def __init__(self, graph):
280
+ self.graph = graph
281
+ self.kids: dict[str, list[str]] = {}
282
+ self.bases: dict[str, list[str]] = {}
283
+ for e in graph.edges:
284
+ if e.type == "contains":
285
+ self.kids.setdefault(e.source, []).append(e.target)
286
+ elif e.type == "inherits":
287
+ self.bases.setdefault(e.source, []).append(e.target)
288
+ self._cache: dict[str, dict[str, str]] = {}
289
+
290
+ def methods(self, cls: str, _seen=None) -> dict[str, str]:
291
+ """{name: function node id}, a base's method overridden by the class's own."""
292
+ if cls in self._cache:
293
+ return self._cache[cls]
294
+ seen = _seen if _seen is not None else set()
295
+ if cls in seen:
296
+ return {}
297
+ seen.add(cls)
298
+ out: dict[str, str] = {}
299
+ for b in reversed(self.bases.get(cls, [])):
300
+ out.update(self.methods(b, seen))
301
+ for k in self.kids.get(cls, []):
302
+ n = self.graph.nodes.get(k)
303
+ if n is not None and n.kind == "function":
304
+ out[k.rsplit(".", 1)[1]] = k
305
+ if _seen is None:
306
+ self._cache[cls] = out
307
+ return out
308
+
309
+ def protocols(self) -> list[str]:
310
+ return sorted(c for c, bs in self.bases.items()
311
+ if any(b in _PROTOCOL_BASES for b in bs) and c in self.graph.nodes)
312
+
313
+
314
+ def _protocol_methods(idx: _ClassIndex, proto: str) -> dict[str, str]:
315
+ return {m: i for m, i in idx.methods(proto).items()
316
+ if not (m.startswith("__") and m.endswith("__")) or m == "__call__"}
317
+
318
+
319
+ def add_structural_implements(graph) -> None:
320
+ """``implements`` edges by structure, checked by parameter names and kinds (R1-C81 D1).
321
+
322
+ Registry families (M9) link only what a ``@Registry.register`` names. A Protocol whose
323
+ implementations are built by a factory registered some other way — bquearch's
324
+ ``register = CATALOG.register`` on factory functions — had no implementers at all,
325
+ so nothing reached a method behind ``build() -> Protocol``. A name-only match was
326
+ measured and rejected: on bquant it put four swing strategies under a two-method
327
+ shape Protocol. With names *and* parameters it reproduced bquant's registry exactly.
328
+ """
329
+ idx = _ClassIndex(graph)
330
+ protos = idx.protocols()
331
+ if not protos:
332
+ return
333
+ have = {(e.source, e.target) for e in graph.edges if e.type == "implements"}
334
+ proto_set = set(protos)
335
+ classes = sorted(i for i, n in graph.nodes.items() if n.kind == "class" and i not in proto_set
336
+ and (n.extras.get("root") in (None, "core")))
337
+ for p in protos:
338
+ pm = _protocol_methods(idx, p)
339
+ if not pm:
340
+ continue
341
+ want = {m: _param_shape(graph.nodes[i].signature) for m, i in pm.items()}
342
+ if any(v is None for v in want.values()):
343
+ continue # a Protocol we cannot read is not matched against
344
+ for c in classes:
345
+ if (c, p) in have:
346
+ continue
347
+ cm = idx.methods(c)
348
+ if all(m in cm and _param_shape(graph.nodes[cm[m]].signature) == shape
349
+ for m, shape in want.items()):
350
+ graph.add_edge(Edge("implements", c, p, extras={"via": "structural"}))
351
+ have.add((c, p))
352
+
353
+
354
+ def add_protocol_dispatch(graph) -> None:
355
+ """A call on a Protocol method fans out to every implementer's method (R1-C81 D2).
356
+
357
+ ``resolution = "protocol"``, graded heuristic — the same honest over-approximation
358
+ as ``registry-candidate``: the receiver is one of these, which one is not known.
359
+ Idempotent, so it runs after the core passes and again after the consumer scans.
360
+ """
361
+ impls: dict[str, list[str]] = {}
362
+ for e in graph.edges:
363
+ if e.type == "implements":
364
+ impls.setdefault(e.target, []).append(e.source)
365
+ if not impls:
366
+ return
367
+ idx = _ClassIndex(graph)
368
+ fan: dict[str, list[str]] = {} # protocol method id -> implementer method ids
369
+ for p, cs in impls.items():
370
+ for m, pid in _protocol_methods(idx, p).items():
371
+ tg = sorted({idx.methods(c)[m] for c in cs if m in idx.methods(c)} - {pid})
372
+ if tg:
373
+ fan[pid] = tg
374
+ have = {(e.source, e.target) for e in graph.edges if e.type == "calls"}
375
+ new = []
376
+ for e in graph.edges:
377
+ if e.type != "calls" or e.target not in fan or e.extras.get("resolution") == "protocol":
378
+ continue
379
+ for t in fan[e.target]:
380
+ if (e.source, t) not in have and e.source != t:
381
+ have.add((e.source, t))
382
+ new.append(Edge("calls", e.source, t, extras={"resolution": "protocol"}))
383
+ for ed in sorted(new, key=lambda x: (x.source, x.target)):
384
+ graph.add_edge(ed)
@@ -29,7 +29,8 @@ import griffe
29
29
  from codemap.extract.attrflow import add_attrflow
30
30
  from codemap.extract.behavior import add_behavior
31
31
  from codemap.extract.dataflow import add_dataflow
32
- from codemap.extract.dispatch import add_dispatch, add_family_links
32
+ from codemap.extract.dispatch import (add_dispatch, add_family_links, add_protocol_dispatch,
33
+ add_structural_implements)
33
34
  from codemap.extract.gsource import (DOTTED_IMPORT_HINT, NESTED_IMPORT_HINT, module_file,
34
35
  module_identity)
35
36
  from codemap.extract.union import merge_samples
@@ -192,6 +193,9 @@ def add_behavioral_layer(graph, root, module_name, search_path, *, deep: bool,
192
193
  add_dispatch(graph, root, module_name)
193
194
  # M9 (F4): link registry-family members to the Protocol they satisfy.
194
195
  add_family_links(graph)
196
+ # R1-C81: structural implementers (names + parameters), then Protocol dispatch.
197
+ add_structural_implements(graph)
198
+ add_protocol_dispatch(graph)
195
199
  # M12 (F6): column/string-key dataflow (reads/writes on `df['col']`).
196
200
  add_dataflow(graph, root, module_name)
197
201
  # R1-C20 (issue #1): attribute-access edges (accesses: function → attribute).
@@ -134,6 +134,9 @@ def extract_repo(
134
134
  _scan_consumer_root(graph, Path(path).resolve(), index, mode, base)
135
135
  for path in docs:
136
136
  _scan_doc_root(graph, Path(path).resolve(), index, base)
137
+ # R1-C81 D2 again: consumer `typed` calls onto a Protocol method fan out as well.
138
+ from codemap.extract.dispatch import add_protocol_dispatch
139
+ add_protocol_dispatch(graph)
137
140
  # R1-C25: the roots are part of what this graph *is* — a core-only graph and a
138
141
  # repo-scoped one answer `impact` differently, and `diff` must not silently compare
139
142
  # the two. Relative to the graph's own origin, never an absolute location (design D5);
@@ -337,14 +340,156 @@ def _scan_consumer_module(graph, py, base, label, tree, index, mode, origin=None
337
340
  entry["called"] = True
338
341
  entry["shapes"].append(_arg_shape(call_node)) # F7: capture call-site contract
339
342
 
343
+ if mode == "full":
344
+ # R1-C81 D4: `fc = _spec().build().fit(df); fc.band(…)` — calls on objects whose
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):
347
+ if (src, target) not in uses:
348
+ uses[(src, target)] = {"called": True, "shapes": [], "local": False, "typed": True}
349
+
340
350
  for (src, target), entry in sorted(uses.items()):
341
351
  etype = "calls" if entry["called"] else "references"
342
- extras = {"resolution": "local" if entry["local"] else "imported"}
352
+ extras = {"resolution": "typed" if entry.get("typed") else
353
+ "local" if entry["local"] else "imported"}
343
354
  if etype == "calls" and entry["shapes"]:
344
355
  extras.update(_arg_contract(entry["shapes"]))
345
356
  graph.add_edge(Edge(etype, src, target, extras=extras))
346
357
 
347
358
 
359
+ class _Typer:
360
+ """Types of consumer-side expressions from constructors and return annotations (R1-C81 D4).
361
+
362
+ Nothing is guessed: a type is known only when a core class is constructed, or a core
363
+ function / method's return annotation resolves to a core class in its own module (a
364
+ member, or a name that module imports), or a local helper's every ``return`` agrees,
365
+ or a name is assigned exactly once from such an expression.
366
+ """
367
+
368
+ def __init__(self, graph, tree, symbol_map, index):
369
+ from codemap.extract.dispatch import _ClassIndex
370
+ self.graph, self.symbol_map, self.index = graph, symbol_map, index
371
+ self.classes = _ClassIndex(graph)
372
+ self.exports: dict[tuple[str, str], str] = {}
373
+ for e in graph.edges:
374
+ if e.type == "export":
375
+ self.exports.setdefault((e.source, e.target.rsplit(".", 1)[-1]), e.target)
376
+ self.helpers = {n.name: n for n in tree.body
377
+ if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))}
378
+ self._helper_types: dict[str, str | None] = {}
379
+
380
+ def _module_of(self, nid: str) -> str | None:
381
+ parts = nid.split(".")
382
+ for k in range(len(parts) - 1, 0, -1):
383
+ cand = ".".join(parts[:k])
384
+ n = self.graph.nodes.get(cand)
385
+ if n is not None and n.kind == "module":
386
+ return cand
387
+ return None
388
+
389
+ def _is_class(self, nid) -> bool:
390
+ n = self.graph.nodes.get(nid) if nid else None
391
+ return n is not None and n.kind == "class"
392
+
393
+ def resolve_annotation(self, ann: str | None, mod: str | None) -> str | None:
394
+ if not ann or not mod:
395
+ return None
396
+ a = ann.strip().strip("'\"")
397
+ for wrap in ("Optional[", "typing.Optional["):
398
+ if a.startswith(wrap) and a.endswith("]"):
399
+ a = a[len(wrap):-1].strip().strip("'\"")
400
+ if a.endswith(" | None"):
401
+ a = a[:-len(" | None")].strip()
402
+ if not a.replace(".", "").replace("_", "").isalnum():
403
+ return None # generics and unions: not resolved
404
+ for cand in (f"{mod}.{a}", self.exports.get((mod, a.rsplit(".", 1)[-1]))):
405
+ cand = self.index.resolve(cand) if cand else None
406
+ if self._is_class(cand):
407
+ return cand
408
+ return None
409
+
410
+ def returns_of(self, fid: str | None) -> str | None:
411
+ n = self.graph.nodes.get(fid) if fid else None
412
+ if n is None or n.kind != "function":
413
+ return None
414
+ return self.resolve_annotation(n.extras.get("returns"), self._module_of(fid))
415
+
416
+ def helper_type(self, name: str) -> str | None:
417
+ if name in self._helper_types:
418
+ return self._helper_types[name]
419
+ self._helper_types[name] = None # recursion guard: one level, no cycles
420
+ rets = [r.value for r in ast.walk(self.helpers[name]) if isinstance(r, ast.Return)]
421
+ types = {self.type_of(v, {}) if v is not None else None for v in rets}
422
+ self._helper_types[name] = types.pop() if len(types) == 1 else None
423
+ return self._helper_types[name]
424
+
425
+ def type_of(self, expr, env: dict) -> str | None:
426
+ if isinstance(expr, ast.Name):
427
+ return env.get(expr.id)
428
+ if not isinstance(expr, ast.Call):
429
+ return None
430
+ f = expr.func
431
+ if isinstance(f, ast.Name):
432
+ if f.id in self.symbol_map:
433
+ tgt = self.index.resolve(self.symbol_map[f.id])
434
+ return tgt if self._is_class(tgt) else self.returns_of(tgt)
435
+ if f.id in self.helpers:
436
+ return self.helper_type(f.id)
437
+ return None
438
+ if isinstance(f, ast.Attribute):
439
+ return self.returns_of(self.method(self.type_of(f.value, env), f.attr))
440
+ return None
441
+
442
+ def method(self, cls: str | None, name: str) -> str | None:
443
+ return self.classes.methods(cls).get(name) if cls else None
444
+
445
+ def env_of(self, fnode) -> dict:
446
+ assigned: dict[str, list] = {}
447
+ for n in ast.walk(fnode):
448
+ if isinstance(n, ast.Assign):
449
+ for t in n.targets:
450
+ if isinstance(t, ast.Name):
451
+ assigned.setdefault(t.id, []).append(n.value)
452
+ else:
453
+ for x in ast.walk(t):
454
+ if isinstance(x, ast.Name):
455
+ assigned.setdefault(x.id, []).append(None)
456
+ elif isinstance(n, (ast.AugAssign, ast.AnnAssign, ast.For, ast.With, ast.NamedExpr)):
457
+ for x in ast.walk(getattr(n, "target", None) or n):
458
+ if isinstance(x, ast.Name) and isinstance(x.ctx, ast.Store):
459
+ assigned.setdefault(x.id, []).append(None)
460
+ env: dict[str, str] = {}
461
+ for _ in range(3): # names typed from names typed earlier
462
+ for name, vals in assigned.items():
463
+ if name in env or len(vals) != 1 or vals[0] is None:
464
+ continue
465
+ t = self.type_of(vals[0], env)
466
+ if t:
467
+ env[name] = t
468
+ return env
469
+
470
+
471
+ 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."""
473
+ typer = _Typer(graph, tree, symbol_map, index)
474
+ out: set[tuple[str, str]] = set()
475
+ for fnode in ast.walk(tree):
476
+ if not isinstance(fnode, (ast.FunctionDef, ast.AsyncFunctionDef)):
477
+ continue
478
+ if any(a <= fnode.lineno <= b for a, b in dead):
479
+ continue
480
+ env = typer.env_of(fnode)
481
+ for call in ast.walk(fnode):
482
+ if not (isinstance(call, ast.Call) and isinstance(call.func, ast.Attribute)):
483
+ 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
487
+ src = _source_for(call, mod_id, func_ranges)
488
+ if src != mid:
489
+ out.add((src, mid))
490
+ return sorted(out)
491
+
492
+
348
493
  def _consumer_imports(tree, index: _CoreIndex):
349
494
  """Return (symbol_map, module_aliases) for imports that reach into core.
350
495
 
@@ -118,7 +118,14 @@ SCHEMA_VERSION = "0.13"
118
118
  # `--all-bands` lists every band, each row carrying its distance and confidence; a helper
119
119
  # function inside a collected test module costs no hop in `tests` and `covers`, so
120
120
  # distances move where one sits on the path (R1-C80, docs/design/tests_through_helpers.md).
121
- ANSWER_FORMAT = 5
121
+ # 6 — `review` reads changed lines, not whole hunks; a module's dossier counts direct references
122
+ # to the module (its importers), not every reference into every member, and has no call-site
123
+ # contract; module constants gain `accesses` readers (R1-C82, docs/design/review_changed_lines.md).
124
+ # 7 — `tests` row confidence is route-aware: a test reached only through a dispatch
125
+ # over-approximation (registry or Protocol fan-out) is `low`, and the caveat says so;
126
+ # Protocol implementers are linked structurally and consumer-root calls on typed receivers
127
+ # resolve (R1-C81, docs/design/protocol_dispatch.md).
128
+ ANSWER_FORMAT = 7
122
129
 
123
130
  # Closed vocabulary of edge types (R1-C7). Node ``kind`` is deliberately an OPEN set
124
131
  # (DESIGN §2 — new entity kinds may appear), but edges are TYPED: every relationship
@@ -173,6 +180,13 @@ RESOLUTIONS: dict[tuple[str, str], dict[str, str]] = {
173
180
  "means": "route", "confidence": "heuristic",
174
181
  "how": "a factory/getter call fanned out to every member of the family — an "
175
182
  "honest over-approximation, not a resolved target"},
183
+ ("calls", "protocol"): {
184
+ "means": "route", "confidence": "heuristic",
185
+ "how": "a call on a Protocol method fanned out to every structural implementer — "
186
+ "the receiver is one of them, which one is not known (R1-C81)"},
187
+ ("calls", "typed"): {"means": "route", "confidence": "exact",
188
+ "how": "a consumer-root call on an expression typed by a constructor "
189
+ "or a return annotation (R1-C81)"},
176
190
  ("accesses", "self"): {"means": "route", "confidence": "exact",
177
191
  "how": "`self.attr` inside the class that declares the attribute"},
178
192
  ("accesses", "class"): {"means": "route", "confidence": "exact",
@@ -181,6 +195,9 @@ RESOLUTIONS: dict[tuple[str, str], dict[str, str]] = {
181
195
  "how": "`Class(...).attr` — the constructor names the owner"},
182
196
  ("accesses", "deep"): {"means": "route", "confidence": "inferred",
183
197
  "how": "owner type inferred by jedi (deep tier only)"},
198
+ ("accesses", "name"): {"means": "route", "confidence": "exact",
199
+ "how": "a module attribute read by bare name — through an import "
200
+ "or in its own module; a local binding shadows it (R1-C82)"},
184
201
  ("references", "annotation"): {"means": "site", "confidence": "exact",
185
202
  "how": "the symbol appears in a type annotation"},
186
203
  ("references", "name"): {"means": "site", "confidence": "exact",
@@ -1651,26 +1651,38 @@ class Query:
1651
1651
  targets = self._member_ids(symbol_id)
1652
1652
  seen = set(targets)
1653
1653
  frontier = set(targets)
1654
+ # R1-C81 D3: nodes reached at their distance by at least one path with no
1655
+ # heuristic (dispatch over-approximation) call edge on it.
1656
+ exact = set(targets)
1654
1657
  bands: list[tuple[int, list[str]]] = []
1655
1658
  for dist in range(1, max(1, depth) + 1):
1656
1659
  nxt: set[str] = set()
1657
1660
  for node in sorted(frontier):
1658
1661
  for src, etype in self._inbound.get(node, []):
1659
- if src not in seen and etype in _TEST_WALK_EDGES:
1662
+ if etype not in _TEST_WALK_EDGES:
1663
+ continue
1664
+ if src not in seen:
1660
1665
  seen.add(src)
1661
1666
  nxt.add(src)
1667
+ if src in nxt and node in exact and not self._heuristic_call(src, node, etype):
1668
+ exact.add(src)
1662
1669
  # R1-C80 D1 (as measured): a def nested in a test or helper is part of its body, so
1663
1670
  # it leads to its container at no cost. A module-level helper costs a hop like any
1664
1671
  # other function: made free, it pulled 72–80% coverage-false tests into the nearest
1665
1672
  # band through shared helpers (design §"Measured", E6).
1666
1673
  todo = sorted(n for n in nxt if n in self._test_parent)
1667
1674
  while todo:
1668
- parent = self._test_parent[todo.pop()]
1675
+ child = todo.pop()
1676
+ parent = self._test_parent[child]
1669
1677
  if parent not in seen:
1670
1678
  seen.add(parent)
1671
1679
  nxt.add(parent)
1672
1680
  if parent in self._test_parent:
1673
1681
  todo.append(parent)
1682
+ if parent in nxt and child in exact and parent not in exact:
1683
+ exact.add(parent)
1684
+ if parent in self._test_parent:
1685
+ todo.append(parent)
1674
1686
  if not nxt:
1675
1687
  break
1676
1688
  frontier = nxt
@@ -1680,9 +1692,16 @@ class Query:
1680
1692
  # D2: the nearest band is the answer; one more band is only counted.
1681
1693
  if len(bands) == 2 and not all_bands:
1682
1694
  break
1683
- return self._tests_envelope(symbol_id, bands, cap, depth, all_bands)
1695
+ guessed = {t for _, band in bands for t in band if t not in exact}
1696
+ return self._tests_envelope(symbol_id, bands, cap, depth, all_bands, guessed)
1697
+
1698
+ def _heuristic_call(self, src: str, node: str, etype: str) -> bool:
1699
+ if etype != "calls" or not self._calls.has_edge(src, node):
1700
+ return False
1701
+ return self._calls.edges[src, node].get("confidence") == "heuristic"
1684
1702
 
1685
- def _tests_envelope(self, symbol_id, bands, cap, searched, all_bands=False) -> dict:
1703
+ def _tests_envelope(self, symbol_id, bands, cap, searched, all_bands=False,
1704
+ guessed=frozenset()) -> dict:
1686
1705
  dist, hits = bands[0] if bands else (None, [])
1687
1706
  rows = ([(t, d) for d, band in bands for t in band] if all_bands
1688
1707
  else [(t, dist) for t in hits])
@@ -1694,8 +1713,10 @@ class Query:
1694
1713
  "distance": dist,
1695
1714
  # `unknown` — never "none". A confident empty is the failure this project has
1696
1715
  # now shipped five fixes for (#1 risk:"none", #3, #5, #7, R1-C23).
1697
- "confidence": _TEST_CONFIDENCE.get(dist, "low") if dist else "unknown",
1698
- "tests": [self._test_row(t, d) for t, d in shown],
1716
+ # R1-C81 D3: a nearest band reached only through dispatch guesses is low, too.
1717
+ "confidence": (("low" if hits and all(t in guessed for t in hits)
1718
+ else _TEST_CONFIDENCE.get(dist, "low")) if dist else "unknown"),
1719
+ "tests": [self._test_row(t, d, t in guessed) for t, d in shown],
1699
1720
  "total_at_distance": len(hits),
1700
1721
  # R1-C80 D2: the band after the nearest, within `depth` — always present, null if none.
1701
1722
  "next_band": {"distance": nxt[0], "count": len(nxt[1])} if nxt else None,
@@ -1703,15 +1724,21 @@ class Query:
1703
1724
  "caveats": self._test_caveats(truncated=truncated, searched=searched,
1704
1725
  found=bool(dist), nearest=dist),
1705
1726
  }
1727
+ n_guessed = sum(1 for t, _ in rows if t in guessed)
1728
+ if n_guessed:
1729
+ out["caveats"].append(
1730
+ f"{n_guessed} test(s) reached only through a dispatch over-approximation "
1731
+ "(a registry or Protocol call fanned out to every implementation) — "
1732
+ "confidence low: the test calls one of them, not necessarily this one")
1706
1733
  if all_bands: # D3
1707
1734
  out["total"] = len(rows)
1708
1735
  return out
1709
1736
 
1710
- def _test_row(self, node_id: str, dist) -> dict:
1737
+ def _test_row(self, node_id: str, dist, guessed: bool = False) -> dict:
1711
1738
  n = self.graph.nodes.get(node_id)
1739
+ conf = ("low" if guessed else _TEST_CONFIDENCE.get(dist, "low")) if dist else "unknown"
1712
1740
  return {"id": node_id, "node_id": self.pytest_nodeid(node_id),
1713
- "line": getattr(n, "lineno", None), "distance": dist,
1714
- "confidence": _TEST_CONFIDENCE.get(dist, "low") if dist else "unknown"}
1741
+ "line": getattr(n, "lineno", None), "distance": dist, "confidence": conf}
1715
1742
 
1716
1743
  def covers(self, test_id: str, *, depth: int = _TEST_MAX_DEPTH,
1717
1744
  cap: int = _TEST_CAP) -> dict: