feat(query): read project budget and depth defaults

Resolve CLI query defaults from the selected graph project and keep
explicit options authoritative. Preserve execution and query-log agreement.

Refs #1654.

AI-Assistance: OpenAI Codex
(cherry picked from commit f3b5a09a39)
This commit is contained in:
Alex Tumanov authored and safishamsi committed 2026-11-03 22:25:18 +00:00
1 parent 514fb6f6a9
commit 19eacc74a1
7 files changed
+389 -13

No files matched your search

+14
View File
@@ -412,6 +412,20 @@ viz_node_limit=0
The declaration flows through classification, extractor selection, grammar and resolution, imports, `graphify watch`, and the AST cache (a file re-parsed under a different language never reuses the old entry), and the same `.graphifyrc` is read by `extract`, `update`, the hooks, the MCP server, and the `/graphify` skill. A typo is reported once on stderr and the scan continues with the defaults. How declarations interact with caching, incremental rebuilds, and import resolution: **[Configuration](https://docs.graphify.com/reference/configuration)**.
**Query defaults.** Set `query_budget` to a positive integer and `query_depth` to an integer from 1 to 6:
```ini
query_budget=4000
query_depth=3
```
For `graphify query`, explicit `--budget N` / `--budget=N` and `--depth N` / `--depth=N` override these settings independently. Without a project setting or explicit option, the defaults remain budget 2000 and depth 2. These keys do not change the MCP server's defaults.
Settings come from the project owning the selected `--graph`, even when the command runs from another directory. An existing absolute directory in the graph's sibling `.graphify_root` marker identifies that project. Otherwise a matching relative `GRAPHIFY_OUT` suffix identifies it; absolute, empty, traversal-containing or nonmatching output paths fall back to the graph file's directory. Relative markers are ignored.
The query command always reads that project's `.graphifyrc`. An invalid recognized setting or an unreadable file produces one stderr warning and discards all project settings for that query; explicit options still apply. The settings parser stays strict for its other callers. Existing explicit budget values retain their behavior; persisted `query_budget` values must be positive.
---
## Team setup
+2 -1
View File
@@ -933,7 +933,8 @@ def _run_cli() -> None:
print(" --context C explicit edge-context filter (repeatable)")
print(" --seed X start at node X (id, label or file path; repeatable)")
print(" instead of the question's keyword matches")
print(" --budget N cap output at N tokens (default 2000)")
print(" --budget N token budget (project .graphifyrc, otherwise 2000)")
print(" --depth N, --depth=N traversal depth 1-6 (project .graphifyrc, otherwise 2)")
print(" --graph <path> path to graph.json (default graphify-out/graph.json)")
print(" query, path and explain exit 0 with an answer, 3 when a name is ambiguous")
print(" (the candidates are listed), 4 when no node matches")
+58 -11
View File
@@ -160,9 +160,28 @@ def _print_cloud_cta(out_dir: "Path") -> None:
def _graph_root_for(gp: Path) -> Path:
"""The analysed repo root for a graph file: <root>/<GRAPHIFY_OUT_NAME>/graph.json, else the file's own directory."""
from graphify.paths import GRAPHIFY_OUT_NAME
return gp.parent.parent if gp.parent.name == GRAPHIFY_OUT_NAME else gp.parent
"""Resolve the selected graph's project without interpreting paths via CWD."""
from graphify.paths import GRAPHIFY_OUT
try:
text = (gp.parent / ".graphify_root").read_text(encoding="utf-8-sig").strip()
if text:
root = Path(text)
if root.is_absolute():
root = root.resolve()
if root.is_dir():
return root
except (OSError, UnicodeError, ValueError, RuntimeError):
pass
# CLI-written absolute markers cover shared output. Otherwise strip only
# an exact, traversal-free relative output suffix, never a CWD-resolved one.
output = Path(GRAPHIFY_OUT)
parts = output.parts
if (parts and not output.is_absolute() and ".." not in parts
and gp.parent.parts[-len(parts):] == parts):
return gp.parent.parents[len(parts) - 1]
return gp.parent
def _default_graph_path() -> str:
@@ -1745,7 +1764,7 @@ def dispatch_command(cmd: str) -> None:
print("Usage: graphify hook [install|uninstall|status]", file=sys.stderr)
sys.exit(1)
elif cmd == "query":
_query_usage = "Usage: graphify query \"<question>\" [--dfs] [--context C] [--seed X] [--budget N] [--graph path]"
_query_usage = "Usage: graphify query \"<question>\" [--dfs] [--context C] [--seed X] [--budget N] [--depth N] [--graph path]"
if len(sys.argv) < 3:
print(_query_usage, file=sys.stderr)
sys.exit(1)
@@ -1764,7 +1783,8 @@ def dispatch_command(cmd: str) -> None:
question = sys.argv[2]
use_dfs = "--dfs" in sys.argv
budget = 2000
budget: int | None = None
depth: int | None = None
graph_path = _default_graph_path()
context_filters: list[str] = []
seeds: list[str] = []
@@ -1785,6 +1805,23 @@ def dispatch_command(cmd: str) -> None:
print(f"error: --budget must be an integer", file=sys.stderr)
sys.exit(1)
i += 1
elif args[i] == "--depth" or args[i].startswith("--depth="):
if args[i] == "--depth":
if i + 1 >= len(args):
print("error: --depth needs an integer from 1 to 6", file=sys.stderr)
sys.exit(1)
raw_depth = args[i + 1]
i += 2
else:
raw_depth = args[i].split("=", 1)[1]
i += 1
try:
depth = int(raw_depth)
if not 1 <= depth <= 6:
raise ValueError("out of range")
except ValueError:
print("error: --depth must be an integer from 1 to 6", file=sys.stderr)
sys.exit(1)
elif args[i] == "--context" and i + 1 < len(args):
context_filters.append(args[i + 1])
i += 2
@@ -1854,6 +1891,17 @@ def dispatch_command(cmd: str) -> None:
except Exception as exc:
print(f"error: could not load graph: {exc}", file=sys.stderr)
sys.exit(1)
from graphify.rcfile import RC_FILENAME, load_graphifyrc
graph_root = _graph_root_for(gp)
try:
project_settings = load_graphifyrc(graph_root)
except (ValueError, OSError) as exc:
print(f"warning: ignoring project settings in {graph_root / RC_FILENAME}: {exc}", file=sys.stderr)
project_settings = {}
effective_budget = budget if budget is not None else project_settings.get("query_budget", 2000)
effective_depth = depth if depth is not None else project_settings.get("query_depth", 2)
import time as _time
_t0 = _time.perf_counter()
_mode = "dfs" if use_dfs else "bfs"
@@ -1861,13 +1909,12 @@ def dispatch_command(cmd: str) -> None:
G,
question,
mode=_mode,
depth=2,
token_budget=budget,
depth=effective_depth,
token_budget=effective_budget,
context_filters=context_filters,
graph_path=str(gp),
seeds=seeds or None,
# Same root derivation as `affected` (#2706): <root>/graphify-out/graph.json.
seed_root=_graph_root_for(gp),
seed_root=graph_root,
)
querylog.log_query(
kind="query",
@@ -1875,8 +1922,8 @@ def dispatch_command(cmd: str) -> None:
corpus=str(gp),
result=_result,
mode=_mode,
depth=2,
token_budget=budget,
depth=effective_depth,
token_budget=effective_budget,
duration_ms=(_time.perf_counter() - _t0) * 1000,
seeds=seeds or None,
)
+18 -1
View File
@@ -5,6 +5,10 @@ One ``key=value`` per line, ``#`` comments, blank lines ignored. Keys:
``viz_node_limit=<int>``
Baked into the generated git hooks (see :mod:`graphify.hooks`).
``query_budget=<positive int>`` and ``query_depth=<int 1-6>``
Project defaults for the public ``graphify query`` command. Explicit query
options override these values; absent settings retain budget 2000, depth 2.
``language.<ext>=<language | .ext>``
Treat files with extension ``<ext>`` as the named language for
classification, extractor dispatch and cross-file resolution (#2961).
@@ -112,7 +116,8 @@ def parse_language_value(value: str) -> str:
def load_graphifyrc(root: Path) -> dict:
"""Parse ``<root>/.graphifyrc``. Returns ``{}`` when absent.
Returned keys: ``viz_node_limit`` (int) and ``languages``
Returned keys: ``viz_node_limit``, ``query_budget``, ``query_depth`` (ints),
and ``languages``
(``{".inc": ".php", ...}``) — each present only when the file sets it.
Unknown keys are ignored so a newer graphify's options do not break an
older one. Malformed lines raise ``ValueError`` naming the line.
@@ -147,6 +152,18 @@ def load_graphifyrc(root: Path) -> dict:
f"Invalid viz_node_limit in {rc_path} at line {line_num}: {val!r}. "
f"Must be a non-negative integer."
) from exc
elif key in {"query_budget", "query_depth"}:
requirement = "a positive integer" if key == "query_budget" else "an integer from 1 to 6"
try:
parsed_val = int(val)
if parsed_val <= 0 or (key == "query_depth" and parsed_val > 6):
raise ValueError(requirement)
cfg[key] = parsed_val
except ValueError as exc:
raise ValueError(
f"Invalid {key} in {rc_path} at line {line_num}: {val!r}. "
f"Must be {requirement}."
) from exc
elif key.startswith("language."):
ext_part = key[len("language."):].strip()
if not ext_part or any(ch.isspace() for ch in ext_part):
+8
View File
@@ -64,3 +64,11 @@ def test_help_lists_every_install_platform():
assert platform_name in listed, (
f"`graphify --help` must list the --platform value {platform_name!r} (#4655)"
)
def test_help_lists_project_query_defaults_and_depth_range():
result = subprocess.run([PYTHON, "-m", "graphify", "--help"], capture_output=True, text=True)
assert result.returncode == 0
assert "--depth N" in result.stdout
assert "1-6" in result.stdout
assert ".graphifyrc" in result.stdout
+27
View File
@@ -157,6 +157,33 @@ def test_the_existing_option_and_unknown_keys_still_behave(tmp_path):
assert cfg == {"viz_node_limit": 0, "languages": {".tpl": ".ts"}}
@pytest.mark.parametrize("content, expected", [
("query_budget=4000\n", {"query_budget": 4000}),
("query_depth=6\n", {"query_depth": 6}),
("query_budget=3\nquery_budget=4000\nquery_depth=1\n", {"query_budget": 4000, "query_depth": 1}),
("\ufeffquery_budget=4000\nquery_depth=3\nviz_node_limit=0\nlanguage.tpl=.ts\nfuture_key=ok\n",
{"query_budget": 4000, "query_depth": 3, "viz_node_limit": 0, "languages": {".tpl": ".ts"}}),
])
def test_query_defaults_are_optional_strict_project_settings(tmp_path, content, expected):
(tmp_path / ".graphifyrc").write_text(content, encoding="utf-8")
assert load_graphifyrc(tmp_path) == expected
@pytest.mark.parametrize("key, value", [
("query_budget", "no"), ("query_budget", "0"), ("query_budget", "-1"),
("query_budget", ""), ("query_depth", "no"), ("query_depth", "0"),
("query_depth", "-1"), ("query_depth", "7"), ("query_depth", ""),
])
def test_invalid_query_defaults_report_key_path_and_line(tmp_path, key, value):
rc = tmp_path / ".graphifyrc"
rc.write_text(f"# project settings\n{key}={value}\n", encoding="utf-8")
with pytest.raises(ValueError) as error:
load_graphifyrc(tmp_path)
assert key in str(error.value)
assert str(rc) in str(error.value)
assert "line 2" in str(error.value)
def test_hooks_still_reads_the_same_file_through_its_old_name(tmp_path):
from graphify.hooks import _load_graphifyrc
(tmp_path / ".graphifyrc").write_text("viz_node_limit=3\nlanguage.inc=php\n", encoding="utf-8")
+262
View File
@@ -2,6 +2,9 @@
from __future__ import annotations
import json
from pathlib import Path
import pytest
import pytest
@@ -188,3 +191,262 @@ def test_explain_cli_node_containing_help_text_still_runs(monkeypatch, tmp_path,
mainmod.main()
out = capsys.readouterr().out
assert not out.startswith("Usage: graphify explain")
# Project query defaults share the selected graph's identity, not process CWD.
def _capture_query_settings(monkeypatch, graph_path, flags):
captured = {}
def query(_graph, _question, **kwargs):
captured["execution"] = kwargs
return "captured query result"
def log(**kwargs):
captured["log"] = kwargs
monkeypatch.setattr("graphify.serve._query_graph_text", query)
monkeypatch.setattr("graphify.querylog.log_query", log)
monkeypatch.setattr(mainmod, "_check_skill_version", lambda _: None)
monkeypatch.setattr(mainmod.sys, "argv", [
"graphify", "query", "extract", "--graph", str(graph_path), *flags,
])
mainmod.main()
return captured
@pytest.mark.parametrize("settings, flags, expected", [
("", [], (2000, 2)),
("query_budget=4000\n", [], (4000, 2)),
("query_depth=4\n", [], (2000, 4)),
("query_budget=4000\nquery_depth=4\n", [], (4000, 4)),
("query_budget=4000\nquery_depth=4\n", ["--budget", "5000"], (5000, 4)),
("query_budget=4000\nquery_depth=4\n", ["--depth=6"], (4000, 6)),
("query_budget=4000\nquery_depth=4\n", ["--budget=5000", "--depth", "1"], (5000, 1)),
("query_budget=4000\n", ["--budget=0"], (0, 2)),
("query_budget=4000\n", ["--budget", "-2"], (-2, 2)),
("query_budget=4000\n", ["--budget"], (4000, 2)),
("", ["--budget", "3000", "--budget=5000", "--depth=3", "--depth", "5"], (5000, 5)),
])
def test_query_settings_precedence_and_execution_log_agree(monkeypatch, tmp_path, settings, flags, expected):
project = tmp_path / "project"
out = project / "graphify-out"
out.mkdir(parents=True)
graph_path = _write_graph(out)
if settings:
(project / ".graphifyrc").write_text(settings, encoding="utf-8")
other = tmp_path / "other"
other.mkdir()
(other / ".graphifyrc").write_text("query_budget=9999\nquery_depth=6\n", encoding="utf-8")
monkeypatch.chdir(other)
monkeypatch.setattr("graphify.paths.GRAPHIFY_OUT", "graphify-out")
captured = _capture_query_settings(monkeypatch, graph_path, flags)
for consumer in ["execution", "log"]:
assert (captured[consumer]["token_budget"], captured[consumer]["depth"]) == expected
assert captured["execution"]["seed_root"] == project
@pytest.mark.parametrize("flags", [
["--depth"], ["--depth="], ["--depth", "no"], ["--depth=0"],
["--depth=-1"], ["--depth=7"], ["--depth", "1.5"],
])
def test_query_rejects_invalid_explicit_depth(monkeypatch, tmp_path, capsys, flags):
with pytest.raises(SystemExit) as error:
_capture_query_settings(monkeypatch, _write_graph(tmp_path), flags)
assert error.value.code == 1
assert "--depth" in capsys.readouterr().err
@pytest.mark.parametrize("settings, flags, expected", [
("query_budget=4000\nquery_depth=7\n", [], (2000, 2)),
("query_depth=4\nviz_node_limit=-1\n", ["--budget=5000"], (5000, 2)),
("query_budget=4000\nmalformed\n", ["--depth=3"], (2000, 3)),
("query_budget=4000\nquery_depth=no\n", ["--budget=5000", "--depth=3"], (5000, 3)),
])
def test_bad_project_settings_warn_once_and_discard_all_defaults(monkeypatch, tmp_path, capsys, settings, flags, expected):
(tmp_path / ".graphifyrc").write_text(settings, encoding="utf-8")
captured = _capture_query_settings(monkeypatch, _write_graph(tmp_path), flags)
for consumer in ["execution", "log"]:
assert (captured[consumer]["token_budget"], captured[consumer]["depth"]) == expected
error = capsys.readouterr().err
assert error.count("warning:") == 1
assert str(tmp_path / ".graphifyrc") in error
assert "Invalid" in error
def test_query_settings_read_error_preserves_explicit_values(monkeypatch, tmp_path, capsys):
def unreadable(root):
assert root == tmp_path
raise OSError("unreadable project settings")
monkeypatch.setattr("graphify.rcfile.load_graphifyrc", unreadable)
captured = _capture_query_settings(monkeypatch, _write_graph(tmp_path), ["--budget=5000", "--depth=3"])
assert captured["execution"]["token_budget"] == captured["log"]["token_budget"] == 5000
assert captured["execution"]["depth"] == captured["log"]["depth"] == 3
assert "unreadable project settings" in capsys.readouterr().err
def test_query_settings_unexpected_error_is_not_hidden(monkeypatch, tmp_path):
def unexpected(_root):
raise RuntimeError("unexpected loader failure")
monkeypatch.setattr("graphify.rcfile.load_graphifyrc", unexpected)
with pytest.raises(RuntimeError, match="unexpected loader failure"):
_capture_query_settings(monkeypatch, _write_graph(tmp_path), [])
@pytest.mark.parametrize("graph_error", ["missing", "invalid-json"])
def test_graph_errors_precede_settings_loading(monkeypatch, tmp_path, capsys, graph_error):
(tmp_path / ".graphifyrc").write_text("query_depth=bad\n", encoding="utf-8")
graph_path = tmp_path / "graph.json"
if graph_error == "invalid-json":
graph_path.write_text("{broken", encoding="utf-8")
def should_not_load(_root):
pytest.fail("settings loaded before graph validation")
monkeypatch.setattr("graphify.rcfile.load_graphifyrc", should_not_load)
with pytest.raises(SystemExit) as error:
_capture_query_settings(monkeypatch, graph_path, [])
assert error.value.code == 1
assert "warning:" not in capsys.readouterr().err
@pytest.mark.parametrize("configured, graph_dir, expected_root", [
("graphify-out", "project/graphify-out", "project"),
("cache/graphs", "project/cache/graphs", "project"),
("", "project/graphify-out", "project/graphify-out"),
(".", "project/graphify-out", "project/graphify-out"),
("..", "project/graphify-out", "project/graphify-out"),
("../graphs", "project/graphs", "project/graphs"),
("cache/../graphs", "project/graphs", "project/graphs"),
("cache/..", "project/cache", "project/cache"),
("cache/graphs/..", "project/cache", "project/cache"),
("elsewhere", "project/graphify-out", "project/graphify-out"),
("ABSOLUTE", "project/graphify-out", "project/graphify-out"),
])
def test_query_root_suffix_is_native_lexical_and_cwd_independent(monkeypatch, tmp_path, configured, graph_dir, expected_root):
from graphify.cli import _graph_root_for
if configured == "ABSOLUTE":
configured = str(tmp_path / "project" / "graphify-out")
monkeypatch.setattr("graphify.paths.GRAPHIFY_OUT", configured)
directory = tmp_path / graph_dir
directory.mkdir(parents=True)
gp = directory / "graph.json"
for cwd in [tmp_path, directory]:
monkeypatch.chdir(cwd)
assert _graph_root_for(gp) == tmp_path / expected_root
@pytest.mark.parametrize("marker_kind", ["missing", "empty", "dot", "parent", "relative", "file", "nul", "bom-absolute"])
def test_query_root_marker_is_absolute_directory_or_falls_back(monkeypatch, tmp_path, marker_kind):
from graphify.cli import _graph_root_for
project = tmp_path / "selected"
project.mkdir()
directory = tmp_path / "shared" / "custom"
directory.mkdir(parents=True)
gp = directory / "graph.json"
not_dir = tmp_path / "plain-file"
not_dir.write_text("file", encoding="utf-8")
values = {"empty": " \n", "dot": ".", "parent": "..", "relative": "selected",
"file": str(not_dir), "nul": "\0", "bom-absolute": "\ufeff " + str(project) + " \n"}
if marker_kind != "missing":
(directory / ".graphify_root").write_text(values[marker_kind], encoding="utf-8")
monkeypatch.setattr("graphify.paths.GRAPHIFY_OUT", "graphify-out")
for cwd in [tmp_path, directory]:
monkeypatch.chdir(cwd)
expected = project if marker_kind == "bom-absolute" else directory
assert _graph_root_for(gp) == expected
@pytest.mark.parametrize("failure", [OSError("unreadable"), UnicodeError("bad encoding"), ValueError("invalid path"), RuntimeError("resolve loop")])
def test_query_root_expected_marker_failures_fall_back(monkeypatch, tmp_path, failure):
from graphify.cli import _graph_root_for
directory = tmp_path / "graphify-out"
directory.mkdir()
marker = directory / ".graphify_root"
original = Path.read_text
def fail_marker(path, *args, **kwargs):
if path == marker:
raise failure
return original(path, *args, **kwargs)
monkeypatch.setattr(Path, "read_text", fail_marker)
monkeypatch.setattr("graphify.paths.GRAPHIFY_OUT", "graphify-out")
assert _graph_root_for(directory / "graph.json") == tmp_path
def test_query_root_unexpected_marker_error_propagates(monkeypatch, tmp_path):
from graphify.cli import _graph_root_for
def unexpected(*_args, **_kwargs):
raise TypeError("unexpected marker failure")
monkeypatch.setattr(Path, "read_text", unexpected)
with pytest.raises(TypeError, match="unexpected marker failure"):
_graph_root_for(tmp_path / "graph.json")
def test_query_root_absolute_symlink_marker_resolves_to_project(monkeypatch, tmp_path):
from graphify.cli import _graph_root_for
project = tmp_path / "project"
project.mkdir()
link = tmp_path / "project-link"
try:
link.symlink_to(project, target_is_directory=True)
except (OSError, NotImplementedError):
pytest.skip("directory symlinks unavailable")
directory = tmp_path / "output"
directory.mkdir()
(directory / ".graphify_root").write_text(str(link), encoding="utf-8")
assert _graph_root_for(directory / "graph.json") == project
@pytest.mark.parametrize("operation, failure", [
("resolve", OSError("resolve denied")),
("resolve", ValueError("invalid marker path")),
("resolve", RuntimeError("symlink loop")),
("is_dir", OSError("stat denied")),
])
def test_query_root_path_operation_failures_fall_back(monkeypatch, tmp_path, operation, failure):
from graphify.cli import _graph_root_for
directory = tmp_path / "graphify-out"
directory.mkdir()
target = tmp_path / "selected"
target.mkdir()
(directory / ".graphify_root").write_text(str(target), encoding="utf-8")
original = getattr(Path, operation)
def fail_target(path, *args, **kwargs):
if path == target:
raise failure
return original(path, *args, **kwargs)
monkeypatch.setattr(Path, operation, fail_target)
monkeypatch.setattr("graphify.paths.GRAPHIFY_OUT", "graphify-out")
assert _graph_root_for(directory / "graph.json") == tmp_path
@pytest.mark.parametrize("layout", ["absolute-marker", "nested-relative-output"])
def test_query_reads_custom_output_selected_project_settings(monkeypatch, tmp_path, layout):
project = tmp_path / "project"
project.mkdir()
(project / ".graphifyrc").write_text("query_budget=4000\nquery_depth=4\n", encoding="utf-8")
if layout == "absolute-marker":
directory = tmp_path / "shared-output"
directory.mkdir()
(directory / ".graphify_root").write_text(str(project), encoding="utf-8")
monkeypatch.setattr("graphify.paths.GRAPHIFY_OUT", str(directory))
else:
directory = project / "cache" / "graphs"
directory.mkdir(parents=True)
monkeypatch.setattr("graphify.paths.GRAPHIFY_OUT", "cache/graphs")
graph_path = _write_graph(directory)
monkeypatch.chdir(tmp_path)
captured = _capture_query_settings(monkeypatch, graph_path, [])
for consumer in ["execution", "log"]:
assert (captured[consumer]["token_budget"], captured[consumer]["depth"]) == (4000, 4)
assert captured["execution"]["seed_root"] == project