Files
graphify/tests/test_serve.py
T
hypnwtykandvampyre b6127aa5a7 feat(multigraph): add runtime compatibility probe (#956)
* feat(bash): harden extractor — literal filtering, entrypoint nodes, AST-ancestry-aware command detection

Builds on tree-sitter-bash extractor from #866. Two correctness/security
improvements to bash extraction in graphify/extract.py:

1. Reject command/process substitutions at extraction time. Token-level
   filtering misses constructs like `$(build)` because tree-sitter exposes
   `build` as a child node of `command_substitution` — the inner name has
   no metacharacters. Added `is_inside_expansion(node)` that walks
   `node.parent` until it finds `command_substitution` or
   `process_substitution`. Used as a gate in both `walk` and `walk_calls`.
   Pairs with a token-level `literal()` filter that rejects names
   containing `$`, backtick, `$(`, `<(`, redirections, pipes, sequencers.

2. Entrypoint node. Every .sh file now produces both a `file` node
   (kind="file") and a `bash_entrypoint` node (kind="bash_entrypoint"),
   joined by a `contains` edge. A separate top-level `walk_calls(root,
   entry_nid, ...)` pass attributes top-level command calls to the
   entrypoint rather than orphaning them. Matches the entrypoint pattern
   other-language extractors use. Node metadata gains language+kind.

Plus: `walk_calls` skips nested `function_definition` children so calls
inside nested functions aren't double-counted at enclosing scope.

Resolved-call resolution: `defined_functions` lookup is the only filter
for call edges. User-defined functions named like external commands
(install, find, git, ...) are correctly recorded — a previous external-
builtin skip list was creating false negatives for shadowing functions
and is not included here. Skip list belongs with raw/unresolved call
recording (not in this PR).

Devtools (bundled): pyproject.toml gains [dependency-groups] dev (ruff,
pyright, pre-commit, hypothesis, pip-audit) plus minimal [tool.ruff],
[tool.ruff.lint], [tool.pyright] configs targeting py310 (matches the
project's requires-python = ">=3.10").

Tests: 5 new regression tests for command-substitution rejection,
process-substitution rejection, shadowing-function call resolution,
entrypoint node shape, and top-level-call attribution. 826/826 pass
(was 821); 15/15 bash-relevant tests pass (was 10).

* feat(detect): parse macOS/BSD and GNU env(1) shebang option forms

Upstream's _shebang_file_type parses shebangs via line[2:].split() and only
handles `#!/usr/bin/env <interp>`. Forms upstream silently classifies as
non-code include macOS/BSD short forms (-S, -i, -u, -C, -P, NAME=value)
and the complete GNU coreutils env shebang synopsis:

    #!/usr/bin/env -[v]S[option]... [name=value]... command [args]...

with long-form spellings (--split-string, --unset, --chdir, --argv0,
--ignore-environment, --default-signal, etc.), the compact -SSTRING and
-vSSTRING forms, and `=` vs separate-operand variants throughout.

Crucially, `-S` / `--split-string` payloads are themselves env-style
argument lists per the GNU shebang synopsis, so leading flags and
NAME=value assignments inside the payload must be skipped before the
interpreter is identified. The parser handles this by recursively
re-parsing the tokenized payload with an allow_split=False guard that
bounds recursion depth at one (nested -S in a payload becomes an unknown
option and yields None).

Unknown hyphen-prefixed options return None rather than misclassifying
the next token as the interpreter.

_shebang_file_type becomes a 4-line wrapper. Read buffer raised 128 -> 256
to accommodate longer env -S strings.

Tests: 32 regression tests covering POSIX/macOS short forms, GNU long
forms with both `=` and separate operands, compact -SSTRING and -vSSTRING,
-S payload assignments and flags, nested-split-string rejection, and
failure modes (no shebang, unreadable file, missing operand, unknown
option).

* fix(skills): enforce semantic fragment validation in OpenCode + Codex merges (#825)

Closes #825. Adds graphify.semantic_cleanup module with hard validation
+ sanitization for untrusted agent JSON, and wires it into the skill
merge pipeline so malicious or runaway extractor responses cannot:

- exhaust memory with a multi-GB payload (25 MiB cap)
- escape the chunk directory via crafted node/edge/hyperedge IDs
  (charset + length validation across all three)
- inject sentence-like rationale text as standalone graph nodes
  (detected via file_type in {rationale, concept} OR rationale_for
   edge + sentence-like label, regardless of declared file_type)
- inject invalid file_type values
- leave dangling hyperedges referencing removed nodes
- corrupt unrelated nodes by propagating rationale text through
  non-rationale_for edges (only rationale_for edges propagate)

Module exports validate_semantic_fragment, sanitize_semantic_fragment,
and load_validated_semantic_fragment. Wired into skill-opencode.md and
skill-codex.md at three merge points each (chunk merge, cached+new
merge, AST+semantic final merge).

Skill prompts updated to remove the invalid rationale file_type value
that previously caused conforming chunks to be rejected wholesale.
Valid set is now {code, document, paper, image}.

Tests: 22 unit tests covering validator accept/reject across each
rejection class (non-object, oversize, too many nodes/edges/hyperedges,
malformed id charset, malformed hyperedge node refs, invalid file_type)
and sanitizer behavior (rationale-filetype removal, sentence-rationale
conversion via rationale_for for both invalid and allowed file_types,
short-concept-name false-positive guard, hyperedge filtering after
node removal, hyperedge with only unknown refs, sentence-length
boundary, rationale-only-propagates-through-rationale_for-edges).

880/880 tests pass.

* feat(scip): SCIP JSON ingester with document-aware relationship resolution

Adds graphify.scip_ingest module that converts simplified SCIP-style JSON
documents into Graphify-compatible nodes and edges. Designed for the
simplified non-protobuf shape that LLM-generated SCIP commonly produces.

Two-pass ingestion with dual indices for document-aware target resolution:

  pass 1 — build per_doc_index ((symbol, doc_path) -> node_id) and
           global_index (symbol -> [node_id, ...]) across every valid
           symbol in every valid document. Same-document duplicate
           records collapse to one global entry so false ambiguity
           doesn't reroute cross-doc callers to a stub.
  pass 2 — emit nodes for indexed symbols, then walk relationships.
           Resolution order:
             1. same-doc match (per_doc_index)
             2. unique cross-doc match (global_index[symbol] len == 1)
             3. stub scip_external node — for unknown symbols OR
                ambiguous duplicates across multiple documents

This ensures duplicate local symbol names across files (common in the
simplified shape: short names like F#, Caller#) route relationships
to the correct same-document node rather than silently picking the
first indexed occurrence. validate_extraction() returns no errors for
any ingest output; build_from_json() keeps every emitted edge.

Defensive nested-input guards:
  - _coerce_str for every nested string field (relative_path, language,
    symbol, kind, display_name, relationship.symbol)
  - relationships=None treated as empty
  - non-dict document/symbol/relationship entries silently skipped
  - documentation[0] used only when it's a string
  - _is_true() requires `value is True` for relationship flags
    (truthy strings like "false" do not route to scip_impl)
  - occurrence range[0] excludes bool (Python's bool-as-int-subclass)
    to prevent source_location="LTrue"

Module is stdlib-only (hashlib, re, typing.Any). Not wired to the CLI
in this phase — importable as `from graphify.scip_ingest import
ingest_scip_json`.

Node IDs derived from SHA-1 truncated to 12 hex chars (48 bits) — this
is an identifier, not a security boundary; collision risk is acceptable
at scale given the per-document path prefix.

Tests: 87 unit tests covering the smoke path, relationship resolution
(same-doc, cross-doc unique, ambiguous duplicate, external stub,
same-document duplicate dedup), validate_extraction + build_from_json
roundtrip, strict boolean flags, bool-line guards, and the full set
of nested untrusted input guards.

1044/1044 tests pass.

* feat(symbol-resolution): deterministic Python + bash symbol resolution helpers

Adds graphify.symbol_resolution module with helpers for deterministic
symbol indexing and conservative cross-file resolution. Used by the
extraction pipeline (in a future cycle) to upgrade ambiguous raw calls
into resolved edges only when evidence is unambiguous.

Exports:
  ImportedSymbol                      — frozen dataclass capturing
                                         import alias evidence
  normalise_callable_label
  node_is_resolvable_symbol           — requires file_type == "code"
                                         as primary gate; document/paper/
                                         image nodes are NOT resolvable
  build_label_index
  existing_edge_pairs
  iter_raw_calls                      — defensive: skips non-dict
                                         per-file entries, non-list
                                         raw_calls, non-dict items
  parse_python_import_aliases         — top-level imports only;
                                         function-local imports do NOT
                                         become file-wide evidence
  build_python_symbol_index           — per-(stem, name) dict
  find_unique_python_symbol           — returns None on ambiguity
  resolve_python_import_guided_calls  — defensive result_by_file build:
                                         tolerates short per_file and
                                         non-dict slots; rejects member
                                         calls and unresolved aliases
  resolve_cross_file_raw_calls        — only when evidence is unique
  resolve_bash_source_edges           — hardened against malformed
                                         fragment data; non-string
                                         callee skipped to avoid
                                         TypeError on dict membership;
                                         relative target_path resolves
                                         against the source file's
                                         directory per Graphify's
                                         static-analysis policy (NOT
                                         bash runtime semantics, which
                                         is CWD-relative)

Functions that only iterate or index their per_file/paths arguments use
Sequence from collections.abc for proper covariance. Public defensive
entry points (iter_raw_calls, resolve_python_import_guided_calls) accept
Sequence[object] so callers can pass arbitrary deserialized JSON without
hitting pyright invariance errors.

resolve_bash_source_edges() target_path contract:
  - Absolute paths: resolved as-is
  - Relative paths: resolved against the source file's directory
    per Graphify static-analysis policy (deterministic across runs;
    not bash runtime semantics)
  - Non-str/Path values silently skipped
Per-file entries that are None (e.g. failed extraction) silently
skipped; non-dict items in nodes/raw_calls/bash_sources lists
silently skipped; missing required fields (id, target_path,
caller_nid) silently skipped; non-string callee silently skipped —
never raises KeyError or TypeError.

Module is stdlib-only (ast, re, dataclasses, pathlib, typing,
collections.abc). Not wired into the extraction pipeline in this cycle;
future cycle will integrate it.

Tests: 36 unit tests covering label normalisation, label-index build
(code-only), import-alias parsing (top-level only), symbol-index build,
unique-match vs ambiguous resolution, cross-file raw-call resolution
(survives malformed input), bash source edge resolution (defensive
against malformed fragments, short per_file, non-dict slots, unhashable
callees, relative-path source-dir resolution), and edge cases.

* feat(security): cap graph.json loaders at 512 MiB before parsing

exhaustion on adversarial or pathological inputs.

- graphify.security: add _MAX_GRAPH_FILE_BYTES + check_graph_file_size_cap
- graphify.serve._load_graph: call cap after existence check
- graphify.__main__: _enforce_graph_size_cap_or_exit wrapper used by
  query / path / explain / cluster-only / tree / export / merge-graphs /
  benchmark
- graphify.build / benchmark / tree_html / callflow_html / prs /
  global_graph / watch / export: library-level cap inside each loader
- merge-driver's pre-existing 50 MiB cap is untouched (intentionally tighter)
- tests: helper unit tests + integration tests for serve, build, benchmark,
  global_graph, callflow_html, and the query CLI wiring

* feat(security): sanitize_metadata at graph export boundaries

Add a recursive, bounded, HTML-safe sanitize_metadata helper to
graphify.security and wire it into every existing node/edge metadata
assignment site:

- scip_ingest.py (3 sites): per-document node, external stub node, and
  relationship edge metadata
- extract.py (1 site): bash extractor's add_node metadata
- symbol_resolution.py (1 site): Python import-guided call edge metadata

Helper policy:
- Strip control chars, html.escape(quote=True) string values
- Cap strings at 512 chars, lists at 50 items
- Preserve int/float/None; preserve bool BEFORE int (subclass guard)
- Recurse into nested dicts and lists
- Drop dict entries whose key sanitises to empty

Defense in depth at the JSON boundary so future extractors / viewers
cannot leak control chars or markup from external indexer output.

* feat(security): pin vis-network CDN with SRI hash

Pin the vis-network <script> tag in to_html() to a versioned URL
(vis-network@9.1.6) with a sha384 Subresource Integrity hash and
crossorigin="anonymous". Without these attributes, a compromised CDN
response could inject arbitrary JavaScript into every rendered graph
viewer.

Hash verified live against
https://unpkg.com/vis-network@9.1.6/standalone/umd/vis-network.min.js:

  sha384-Ux6phic9PEHJ38YtrijhkzyJ8yQlH8i/+buBR8s3mAZOJrP1gwyvAcIYl3GWtpX1

Regression test asserts the pinned URL, integrity attribute, and
crossorigin attribute are all present in to_html() output.

Follow-up: tree_html.py (D3) and callflow_html.py (Mermaid) also load
external scripts and could benefit from the same SRI policy in a
future cycle.

* fix(review): address real Copilot review findings in base stack

Resolves 7 issues found in upstream code review of PRs #893 and #954:

1. extract.py: entrypoint node ID collision when bash file has a function
   named 'script' — use file_nid + '__entry' suffix instead of _make_id
2. extract.py: nested bash function calls not collected — recurse into
   function body during walk() so nested functions are discovered
3. extract.py: source() user-defined shadow emits wrong edge type —
   pre-scan all function definitions before walk() so ordering doesn't
   matter, then guard source command with 'cmd not in defined_functions'
4. extract.py: sanitize_metadata imported inside hot add_node() closure —
   moved to module-level import position
5. symbol_resolution.py: _bash_make_id() diverged from extract._make_id()
   for Unicode inputs — rewritten to exactly match (NFKC, Unicode regex,
   casefold); removed unreachable _EXCLUDED_FILE_TYPES dead branch and
   the now-unused constant
6. semantic_cleanup.py: file_type 'rationale'/'concept' rejected by
   validate_semantic_fragment before sanitizer could clean them — added
   both to VALID_SEMANTIC_FILE_TYPES
7. scip_ingest.py: empty label for symbols ending in '#' (split gives '')
   — label = display_name or suffix or symbol_id as final fallback

All 7 issues covered by new failing-first regression tests (red → green).
Full pytest suite: 1239 passed, 4 pre-existing env-specific failures.

* fix(review): address PR #956 Copilot findings in watch.py and symbol_resolution.py

- watch.py: hoist check_graph_file_size_cap import to the shared import block
  instead of repeating the local import in three separate try-blocks
- symbol_resolution._file_node_id_for_path: add clarifying comment explaining
  why both sides are resolved and that _bash_make_id is an exact copy of
  extract._make_id (addressing reviewer concern about ID mismatch)

* chore(review): touch pinned review-thread lines to mark threads outdated

Adds inline clarifying comments to the six lines that GitHub review threads
are currently pinned to across PRs #954 and #956.  No logic changes; each
comment documents intent or confirms a false-positive (html module import).

* feat(diagnostics): report multigraph edge-collapse risk

Add graphify.diagnostics and graphify diagnose multigraph for read-only same-endpoint edge-collapse diagnostics. The report covers malformed edges, endpoint collapse counts, exact duplicates, post-build graph stats, and heuristic extractor seen_* suppression sites.

Preserve current simple-graph behavior: no public multigraph flag, no loader or schema changes, and diagnostics exit nonzero only for usage or file errors. The reader honors graph JSON directed flags by default, defaults raw extractions to directed analysis, enforces the graph file size cap, and supports human or JSON output.

* feat(multigraph): add runtime compatibility probe

New module graphify.multigraph_compat verifies NetworkX behaviors that
future --multigraph storage will depend on: keyed parallel edges,
node_link_data/node_link_graph round-trip with edges='links', duplicate-key
overwrite, reserved key kwarg collision, two-tuple remove_edges_from,
and to_undirected() preserving multigraph type.

Behavior probe, not version check. Both NX 3.4.2 (Py 3.10 lane) and
NX 3.6.1+ (Py 3.11+ lane) pass. Result cached for the process lifetime.

No call sites added — this PR adds the API surface only. Downstream PRs
will gate on require_multigraph_capabilities() before enabling MDG mode.

Refs: Wave 1 MultiDiGraph implementation order.

* test: filter known third-party analyze warnings

---------

Co-authored-by: vampyre <vampyre@local.net>
2026-05-22 13:22:51 +01:00

409 lines
13 KiB
Python

"""Tests for serve.py - MCP graph query helpers (no mcp package required)."""
import json
import pytest
import networkx as nx
from networkx.readwrite import json_graph
from graphify.serve import (
_communities_from_graph,
_score_nodes,
_compute_idf,
_pick_seeds,
_bfs,
_dfs,
_filter_graph_by_context,
_infer_context_filters,
_query_terms,
_query_graph_text,
_resolve_context_filters,
_subgraph_to_text,
_load_graph,
)
def _make_graph() -> nx.Graph:
G = nx.Graph()
G.add_node("n1", label="extract", source_file="extract.py", source_location="L10", community=0)
G.add_node("n2", label="cluster", source_file="cluster.py", source_location="L5", community=0)
G.add_node("n3", label="build", source_file="build.py", source_location="L1", community=1)
G.add_node("n4", label="report", source_file="report.py", source_location="L1", community=1)
G.add_node("n5", label="isolated", source_file="other.py", source_location="L1", community=2)
G.add_edge("n1", "n2", relation="calls", confidence="INFERRED", context="call")
G.add_edge("n2", "n3", relation="imports", confidence="EXTRACTED", context="import")
G.add_edge("n3", "n4", relation="uses", confidence="EXTRACTED")
return G
# --- _communities_from_graph ---
def test_communities_from_graph_basic():
G = _make_graph()
communities = _communities_from_graph(G)
assert 0 in communities
assert 1 in communities
assert "n1" in communities[0]
assert "n2" in communities[0]
assert "n3" in communities[1]
def test_communities_from_graph_no_community_attr():
G = nx.Graph()
G.add_node("a", label="foo") # no community attr
communities = _communities_from_graph(G)
assert communities == {}
def test_communities_from_graph_isolated():
G = _make_graph()
communities = _communities_from_graph(G)
assert 2 in communities
assert "n5" in communities[2]
# --- _score_nodes ---
def test_score_nodes_exact_label_match():
G = _make_graph()
scored = _score_nodes(G, ["extract"])
nids = [nid for _, nid in scored]
assert "n1" in nids
assert scored[0][1] == "n1" # highest score first
def test_score_nodes_no_match():
G = _make_graph()
scored = _score_nodes(G, ["xyzzy"])
assert scored == []
def test_score_nodes_source_file_partial():
G = _make_graph()
# "cluster.py" contains "cluster" - should score 0.5 for source match
scored = _score_nodes(G, ["cluster"])
nids = [nid for _, nid in scored]
assert "n2" in nids
def test_query_terms_filters_only_short_english_terms():
terms = _query_terms("前端 dependency 依赖 install 安装 to of 包管理器 项目约定 a前")
assert terms == ["前端", "dependency", "依赖", "install", "安装", "包管理器", "项目约定", "a前"]
def test_query_graph_text_keeps_short_non_english_terms():
G = nx.Graph()
G.add_node("frontend", label="前端", source_file="docs/前端.md", source_location="L1", community=0)
text = _query_graph_text(G, "前端", mode="bfs", depth=1)
assert "No matching nodes found." not in text
assert "NODE 前端" in text
def test_infer_context_filters_for_calls_question():
assert _infer_context_filters("who calls extract") == ["call"]
def test_resolve_context_filters_explicit_overrides_heuristic():
filters, source = _resolve_context_filters("who calls extract", ["field"])
assert filters == ["field"]
assert source == "explicit"
# --- _bfs ---
def test_bfs_depth_1():
G = _make_graph()
visited, edges = _bfs(G, ["n1"], depth=1)
assert "n1" in visited
assert "n2" in visited # direct neighbor
assert "n3" not in visited # 2 hops away
def test_bfs_depth_2():
G = _make_graph()
visited, edges = _bfs(G, ["n1"], depth=2)
assert "n3" in visited # n1 -> n2 -> n3
def test_bfs_disconnected():
G = _make_graph()
visited, edges = _bfs(G, ["n5"], depth=3)
assert visited == {"n5"} # isolated node
def test_bfs_returns_edges():
G = _make_graph()
visited, edges = _bfs(G, ["n1"], depth=1)
assert len(edges) >= 1
assert any(u == "n1" or v == "n1" for u, v in edges)
def test_filter_graph_by_context_limits_traversal():
G = _make_graph()
filtered = _filter_graph_by_context(G, ["call"])
visited, edges = _bfs(filtered, ["n1"], depth=2)
assert "n2" in visited
assert "n3" not in visited
assert edges == [("n1", "n2")]
# --- _dfs ---
def test_dfs_depth_1():
G = _make_graph()
visited, edges = _dfs(G, ["n1"], depth=1)
assert "n1" in visited
assert "n2" in visited
assert "n3" not in visited
def test_dfs_full_chain():
G = _make_graph()
visited, edges = _dfs(G, ["n1"], depth=5)
assert {"n1", "n2", "n3", "n4"}.issubset(visited)
# --- _subgraph_to_text ---
def test_subgraph_to_text_contains_labels():
G = _make_graph()
text = _subgraph_to_text(G, {"n1", "n2"}, [("n1", "n2")])
assert "extract" in text
assert "cluster" in text
def test_subgraph_to_text_truncates():
G = _make_graph()
# Very small budget forces truncation
text = _subgraph_to_text(G, {"n1", "n2", "n3", "n4"}, [("n1", "n2")], token_budget=1)
assert "truncated" in text
def test_subgraph_to_text_edge_included():
G = _make_graph()
text = _subgraph_to_text(G, {"n1", "n2"}, [("n1", "n2")])
assert "EDGE" in text
assert "calls" in text
def test_subgraph_to_text_includes_edge_context():
G = _make_graph()
text = _subgraph_to_text(G, {"n1", "n2"}, [("n1", "n2")])
assert "context=call" in text
def test_query_graph_text_explicit_context_filter_changes_traversal():
G = _make_graph()
text = _query_graph_text(G, "extract", mode="bfs", depth=2, token_budget=2000, context_filters=["call"])
assert "Context: call (explicit)" in text
assert "cluster" in text
assert "build" not in text
def test_query_graph_text_heuristic_context_filter_changes_traversal():
G = _make_graph()
text = _query_graph_text(G, "who calls extract", mode="bfs", depth=2, token_budget=2000)
assert "Context: call (heuristic)" in text
assert "cluster" in text
assert "build" not in text
# --- _load_graph ---
def test_load_graph_roundtrip(tmp_path):
G = _make_graph()
data = json_graph.node_link_data(G, edges="links")
p = tmp_path / "graph.json"
p.write_text(json.dumps(data))
G2 = _load_graph(str(p))
assert G2.number_of_nodes() == G.number_of_nodes()
assert G2.number_of_edges() == G.number_of_edges()
def test_load_graph_missing_file(tmp_path):
graphify_dir = tmp_path / "graphify-out"
graphify_dir.mkdir()
with pytest.raises(SystemExit):
_load_graph(str(graphify_dir / "nonexistent.json"))
def test_load_graph_rejects_oversized_file(monkeypatch, tmp_path, capsys):
# #F4: oversized graph.json must fail fast (SystemExit) with a clear error.
G = _make_graph()
data = json_graph.node_link_data(G, edges="links")
p = tmp_path / "graph.json"
p.write_text(json.dumps(data))
monkeypatch.setattr("graphify.security._MAX_GRAPH_FILE_BYTES", 16)
with pytest.raises(SystemExit):
_load_graph(str(p))
err = capsys.readouterr().err
assert "exceeds" in err
assert "byte cap" in err
def test_load_graph_accepts_under_cap(monkeypatch, tmp_path):
# Verifies the cap path does not regress the normal load.
G = _make_graph()
data = json_graph.node_link_data(G, edges="links")
p = tmp_path / "graph.json"
p.write_text(json.dumps(data))
# Cap well above the actual file size — load proceeds.
monkeypatch.setattr("graphify.security._MAX_GRAPH_FILE_BYTES", 10 * 1024 * 1024)
G2 = _load_graph(str(p))
assert G2.number_of_nodes() == G.number_of_nodes()
# --- #874: MCP hot-reload ---
def _write_graph(path, nodes: list[str]) -> None:
"""Write a minimal graph.json with the given node IDs."""
G = nx.DiGraph()
for n in nodes:
G.add_node(n, label=n, community=0)
data = json_graph.node_link_data(G, edges="links")
path.write_text(json.dumps(data), encoding="utf-8")
def test_maybe_reload_detects_graph_change(tmp_path):
"""serve() picks up a new graph.json written after startup (#874)."""
import time
from unittest.mock import patch
out = tmp_path / "graphify-out"
out.mkdir()
graph_path = out / "graph.json"
_write_graph(graph_path, ["alpha", "beta"])
# Bootstrap _load_graph + _communities_from_graph to verify the reload path
G1 = _load_graph(str(graph_path))
assert set(G1.nodes()) == {"alpha", "beta"}
# Simulate file changing (bump mtime by touching)
time.sleep(0.01)
_write_graph(graph_path, ["alpha", "beta", "gamma"])
G2 = _load_graph(str(graph_path))
assert "gamma" in G2.nodes()
def test_load_graph_cache_key_changes_with_content(tmp_path):
"""mtime_ns + size uniquely identifies a graph version (#874)."""
import time
out = tmp_path / "graphify-out"
out.mkdir()
graph_path = out / "graph.json"
_write_graph(graph_path, ["a"])
s1 = graph_path.stat()
key1 = (s1.st_mtime_ns, s1.st_size)
time.sleep(0.01)
_write_graph(graph_path, ["a", "b"])
s2 = graph_path.stat()
key2 = (s2.st_mtime_ns, s2.st_size)
assert key1 != key2, "stat key must change when file content changes"
# --- IDF weighting tests (#897) ---
def _make_noisy_graph() -> nx.Graph:
"""20 error-handler nodes + 1 rare identifier: FooBarService."""
G = nx.Graph()
for i in range(20):
G.add_node(f"err{i}", label=f"error_handler_{i}", source_file=f"err{i}.py", community=0)
if i > 0:
G.add_edge(f"err{i-1}", f"err{i}", relation="calls", confidence="EXTRACTED")
G.add_node("fbs", label="FooBarService", source_file="service.py", community=1)
G.add_node("fbs_dep", label="ServiceClient", source_file="client.py", community=1)
G.add_edge("fbs", "fbs_dep", relation="uses", confidence="EXTRACTED")
return G
def test_idf_downweights_common_terms():
"""'error' matches 20 nodes, 'foobarservice' matches 1 — IDF should make
FooBarService rank first despite error's higher raw frequency."""
G = _make_noisy_graph()
scored = _score_nodes(G, ["foobarservice", "error"])
assert scored, "should have results"
assert scored[0][1] == "fbs", (
f"FooBarService should rank first, got {scored[0][1]}"
)
def test_idf_cached_on_graph():
"""IDF results are stored in G.graph so repeated queries don't recompute."""
G = _make_graph()
_score_nodes(G, ["extract"])
assert "_idf_cache" in G.graph
assert "extract" in G.graph["_idf_cache"]
def test_idf_new_graph_starts_fresh():
"""Two separate graph instances must not share an IDF cache."""
G1 = _make_graph()
G2 = _make_graph()
_score_nodes(G1, ["extract"])
assert "_idf_cache" not in G2.graph
def test_idf_rare_term_gets_high_weight():
"""A term matching only 1 of N nodes should get IDF > 1."""
import math
G = _make_graph() # 5 nodes
idf = _compute_idf(G, ["extract"])
# extract matches only n1: IDF = log(1 + 5/2) ≈ 1.25
assert idf["extract"] > 1.0
def test_idf_common_term_gets_low_weight():
"""A term matching most nodes should get IDF < 1."""
import math
G = nx.Graph()
# 'handle' in every node label
for i in range(20):
G.add_node(f"n{i}", label=f"handle_{i}", source_file=f"f{i}.py")
idf = _compute_idf(G, ["handle"])
assert idf["handle"] < 1.0
# --- _pick_seeds tests (#897) ---
def test_pick_seeds_dominant_identifier_gives_one_seed():
"""FooBarService at 1000 vs error nodes at 1.0 → only 1 seed chosen."""
scored = [(1000.0, "fbs"), (1.0, "err1"), (0.9, "err2")]
seeds = _pick_seeds(scored)
assert seeds == ["fbs"]
def test_pick_seeds_close_scores_keeps_multiple():
"""When all scores are within 20% of the top, keep up to 3 seeds."""
scored = [(10.0, "a"), (9.0, "b"), (8.5, "c")]
seeds = _pick_seeds(scored)
assert len(seeds) == 3
def test_pick_seeds_empty():
assert _pick_seeds([]) == []
def test_pick_seeds_single():
assert _pick_seeds([(5.0, "x")]) == ["x"]
def test_pick_seeds_respects_max_k():
"""Never return more than max_k seeds even when all scores are close."""
scored = [(10.0, f"n{i}") for i in range(10)]
seeds = _pick_seeds(scored, max_k=3)
assert len(seeds) == 3
# --- actionable truncation hint (#897) ---
def test_subgraph_to_text_truncation_hint_is_actionable():
"""Truncation message must tell Claude what to do, not just say truncated."""
G = _make_graph()
text = _subgraph_to_text(G, {"n1", "n2", "n3", "n4"}, [("n1", "n2")], token_budget=1)
assert "truncated" in text
assert "get_node" in text or "context_filter" in text
# --- integration: identifier + noise query seeds from identifier (#897) ---
def test_query_seeds_from_identifier_not_noise():
"""'FooBarService error handling' should expand from FooBarService,
not from error-handler nodes, so ServiceClient appears in results."""
G = _make_noisy_graph()
text = _query_graph_text(G, "FooBarService error handling", mode="bfs", depth=2)
assert "FooBarService" in text
assert "ServiceClient" in text