fix(explain,query): say how to get the full answer when output is cut

explain listed the 20 most connected neighbors and "... and N more" with
no option to see the rest, and the token-budget notices of query,
get_neighbors and get_community said "raise the token budget" without
the value that would return everything, so a caller retried with a guess.

explain gets --all, and its cut line names the total and the option.
The budget notices now give the smallest budget that returns the whole
output, computed with the same rule that does the cut.

Co-Authored-By: Claude <noreply@anthropic.com>
(cherry picked from commit 769184dc9a)
This commit is contained in:
Allionix authored and safishamsi committed 2026-10-11 20:49:48 +01:00
1 parent ddc24c76d8
commit 25452a63b8
4 files changed
+109 -9

No files matched your search

+1
View File
@@ -861,6 +861,7 @@ def _run_cli() -> None:
print(" the JSON 'directed' flag is NOT consulted)")
print(" --undirected ignore edge direction")
print(" explain \"X\" plain-language explanation of a node and its neighbors")
print(" --all list every connection (default: the 20 most connected)")
print(" --graph <path> path to graph.json (default graphify-out/graph.json)")
print(" diagnose multigraph report same-endpoint edge collapse risk in graph.json")
print(" --graph <path> path to graph/extraction JSON")
+7 -5
View File
@@ -1843,7 +1843,7 @@ def dispatch_command(cmd: str) -> None:
elif cmd == "explain":
if len(sys.argv) < 3:
print('Usage: graphify explain "<node>" [--graph path]', file=sys.stderr)
print('Usage: graphify explain "<node>" [--all] [--graph path]', file=sys.stderr)
sys.exit(1)
from graphify.serve import _is_ambiguity_refusal, _resolve_single_node
from networkx.readwrite import json_graph
@@ -1851,6 +1851,7 @@ def dispatch_command(cmd: str) -> None:
label = sys.argv[2]
graph_path = _default_graph_path()
args = sys.argv[3:]
show_all = "--all" in args
for i, a in enumerate(args):
if a == "--graph" and i + 1 < len(args):
graph_path = args[i + 1]
@@ -1924,7 +1925,8 @@ def dispatch_command(cmd: str) -> None:
if connections:
print(f"\nConnections ({len(connections)}):")
connections.sort(key=lambda c: G.degree(c[1]), reverse=True)
for direction, nb, edata in connections[:20]:
shown = connections if show_all else connections[:20]
for direction, nb, edata in shown:
rel = edata.get("relation", "")
conf = edata.get("confidence", "")
arrow = "-->" if direction == "out" else "<--"
@@ -1935,9 +1937,9 @@ def dispatch_command(cmd: str) -> None:
sfile = edata.get("source_file") or ""
at = f" {sfile}:{loc}" if loc else ""
print(f" {arrow} {G.nodes[nb].get('label', nb)} [{rel}] [{conf}]{at}")
if len(connections) > 20:
remainder = connections[20:]
print(f" ... and {len(remainder)} more")
if len(connections) > len(shown):
remainder = connections[len(shown):]
print(f" ... and {len(remainder)} more (--all lists all {len(connections)})")
# #2009: a bare count silently hides the answer on high-degree
# nodes ("who calls this, what's the impact?"). Group the cut
# connections by direction + file so their shape is visible
+10 -4
View File
@@ -1260,12 +1260,16 @@ def _subgraph_to_text(G: nx.Graph, nodes: set[str], edges: list[tuple], token_bu
# for a complete one — silence used to read as absence (#BUG2). The
# notice + end marker sit OUTSIDE char_budget by design (two bounded
# wrapper lines, like the existing end marker).
# Smallest budget whose cut keeps every NODE line; past that, edges are never dropped.
node_chars = sum(len(l) + 1 for l in lines if l.startswith("NODE "))
full_budget = (min(node_chars, len(output)) + 2) // 3
output = (
f"[!] TRUNCATED: showing {shown_nodes} of {total_nodes} nodes "
f"(~{token_budget}-token budget). The answer may be among the "
f"{cut_count} cut nodes — raise the token budget (CLI: --budget) or "
f"narrow the query (e.g. context_filter=['call'], or get_node for a "
f"specific symbol).\n\n"
f"{cut_count} cut nodes — raise the token budget to {full_budget} to get "
f"all {total_nodes} (CLI: --budget {full_budget}, MCP: "
f"token_budget={full_budget}) or narrow the query (e.g. "
f"context_filter=['call'], or get_node for a specific symbol).\n\n"
+ output[:cut_at]
+ f"\n... (truncated — {cut_count} more nodes cut by ~{token_budget}-token budget."
f" Narrow with context_filter=['call'] or use get_node for a specific symbol)"
@@ -1286,12 +1290,14 @@ def _cut_lines_to_budget(lines: list[str], token_budget: int, narrow_hint: str)
kept = output[:cut_at]
shown = kept.count("\n") + 1
cut_count = len(lines) - shown
full_budget = (len(output) + 2) // 3
# Announce truncation at the TOP as well, matching _subgraph_to_text — a
# bottom-only marker reads as silence/absence (the BUG-2 fix rationale). The
# notice sits outside char_budget by design (one bounded wrapper line).
return (
f"[!] TRUNCATED: showing {shown} of {len(lines)} lines "
f"(~{token_budget}-token budget). {narrow_hint}\n\n"
f"(~{token_budget}-token budget). Raise the token budget to {full_budget} "
f"to get all {len(lines)} (token_budget={full_budget}). {narrow_hint}\n\n"
+ kept
+ f"\n... (truncated — {cut_count} more lines cut by ~{token_budget}-token budget. "
+ narrow_hint
+91
View File
@@ -0,0 +1,91 @@
"""A truncated answer says how to get all of it: `explain --all`, and the exact
token budget that returns the complete `query` / get_neighbors output.
"""
from __future__ import annotations
import json
import re
import networkx as nx
import graphify.__main__ as mainmod
from graphify.serve import _cut_lines_to_budget, _subgraph_to_text
def _write_hub_graph(tmp_path, n_callers=25):
nodes = [{"id": "hub", "label": "hub()", "source_file": "lib/hub.py"}]
links = []
for i in range(n_callers):
fpath = f"app/mod{i % 3}.py"
nodes.append({"id": f"caller_{i}", "label": f"caller_{i}()", "source_file": fpath})
links.append({"source": f"caller_{i}", "target": "hub", "relation": "calls",
"confidence": "EXTRACTED", "source_file": fpath,
"source_location": f"L{10 + i}"})
p = tmp_path / "graph.json"
p.write_text(json.dumps({"directed": False, "multigraph": False, "graph": {},
"nodes": nodes, "links": links}))
return p
def _explain(monkeypatch, capsys, graph_path, *extra):
monkeypatch.setattr(mainmod, "_check_skill_version", lambda _: None)
monkeypatch.setattr(mainmod.sys, "argv",
["graphify", "explain", "hub", "--graph", str(graph_path), *extra])
mainmod.main()
return capsys.readouterr().out
def test_explain_cut_names_the_total_and_the_option(monkeypatch, tmp_path, capsys):
out = _explain(monkeypatch, capsys, _write_hub_graph(tmp_path))
assert "Connections (25):" in out
assert "... and 5 more (--all lists all 25)" in out
def test_explain_all_lists_every_connection(monkeypatch, tmp_path, capsys):
out = _explain(monkeypatch, capsys, _write_hub_graph(tmp_path), "--all")
listed = [l for l in out.splitlines() if l.startswith(" <-- caller_")]
assert len(listed) == 25
assert "more" not in out
assert "Grouped by file:" not in out
def _budget_hint(text: str) -> int:
m = re.search(r"token budget to (\d+)", text)
assert m, f"no budget hint in: {text[:300]!r}"
return int(m.group(1))
def _chain_graph(n=60):
G = nx.Graph()
for i in range(n):
G.add_node(f"n{i}", label=f"node_number_{i}", source_file=f"src/f{i}.py",
source_location="L1", community=0)
if i:
G.add_edge(f"n{i - 1}", f"n{i}", relation="calls", confidence="EXTRACTED")
return G
def test_query_truncation_gives_the_exact_budget_for_the_full_answer():
G = _chain_graph()
nodes, edges = set(G.nodes), list(G.edges())
cut = _subgraph_to_text(G, nodes, edges, token_budget=50, seeds=["n0"])
assert cut.startswith("[!] TRUNCATED")
needed = _budget_hint(cut)
assert f"--budget {needed}" in cut and f"token_budget={needed}" in cut
full = _subgraph_to_text(G, nodes, edges, token_budget=needed, seeds=["n0"])
assert "TRUNCATED" not in full
assert full.count("\nNODE ") + full.startswith("NODE ") == 60
assert full.count("\nEDGE ") == 59
# The smallest such budget: one token less still cuts.
assert _subgraph_to_text(G, nodes, edges, token_budget=needed - 1, seeds=["n0"]).startswith(
"[!] TRUNCATED")
def test_line_list_truncation_gives_the_exact_budget_for_the_full_answer():
lines = [f" --> node{i} [calls] [EXTRACTED]" for i in range(200)]
cut = _cut_lines_to_budget(lines, token_budget=20, narrow_hint="use relation_filter")
needed = _budget_hint(cut)
assert f"token_budget={needed}" in cut
assert _cut_lines_to_budget(lines, token_budget=needed, narrow_hint="x") == "\n".join(lines)
assert _cut_lines_to_budget(lines, token_budget=needed - 1, narrow_hint="x").startswith(
"[!] TRUNCATED")