From fda4c6154e977f5794c8af41f93874b9f66d215d Mon Sep 17 00:00:00 2001 From: asdacdsfca Date: Mon, 23 Nov 2026 11:03:34 -0500 Subject: [PATCH 1/2] context: add walk-bound inputs and expand_context (interface only) start_symbol and token_budget map to the existing --from and --page-budget; direction and max_depth are checked but not yet used; expand_context is refused as not implemented. With the new inputs left out, answers are unchanged. --- plugins/axiomcode/AGENTS.md | 3 +- plugins/axiomcode/mcp/server.py | 33 +++++++++++++++---- plugins/axiomcode/skills/axiomcode/SKILL.md | 5 +++ .../skills/axiomcode/scripts/ax_web.py | 2 +- .../skills/axiomcode/scripts/axiomcode | 4 +-- .../axiomcode/scripts/axiomcode-context | 24 ++++++++++++-- tests/front_door.py | 7 ++-- tests/mcp.py | 14 +++++--- tests/mcp_docs.py | 2 +- tests/surfaces.py | 5 +-- 10 files changed, 76 insertions(+), 23 deletions(-) diff --git a/plugins/axiomcode/AGENTS.md b/plugins/axiomcode/AGENTS.md index dc3cd82e3..087caf457 100644 --- a/plugins/axiomcode/AGENTS.md +++ b/plugins/axiomcode/AGENTS.md @@ -13,7 +13,8 @@ that never spell the name: unresolved() every open call site that may land in the project; after a build, settle them in a subagent with /axiomcode:fill context(task) how something works, as a narrative: the call flow step by step; - context(task, source=True) carries each step's code + context(task, source=True) carries each step's code; + start_symbol, direction, max_depth and token_budget bound the walk (being built) Without the tools, the same from the shell: `axiomcode impact `, `axiomcode path `, `axiomcode tests`, `axiomcode context "" --source`. diff --git a/plugins/axiomcode/mcp/server.py b/plugins/axiomcode/mcp/server.py index c90000740..f0771e372 100755 --- a/plugins/axiomcode/mcp/server.py +++ b/plugins/axiomcode/mcp/server.py @@ -172,7 +172,7 @@ async def call_tool(self, name, arguments, *a, **k): # the SDK: refused as a SEEN = set() # the flags whose next argument is their value, as the dispatcher skips them when it looks for the repository VALUED = {'--in', '--from', '--budget', '--seeds', '--depth', '--limit', '--tests-in', '--kind', '--range', '--old', - '--new', '--file', '--page', '--page-budget', '--out'} + '--new', '--file', '--page', '--page-budget', '--out', '--direction', '--continue', '--branch'} def orphaned(root=None): """ax_orphan.orphaned for the install this server runs now (plugin_root): '' while it is current. An install whose scripts are gone cannot be imported, so that is said here""" @@ -271,7 +271,7 @@ def run(args, cwd=None, timeout=None): # and only the tools' own parameters count as a `name=` to set, never an HTML attribute (`style="…"`, `class="…"`). _CLI_OPTIONS = ('json|tests|tests-only|tests-in|why|unknown|depends|in|limit|depth|page|page-budget|budget|kind|top|warm|from-text|delete|' 'help|fresh|no-refresh|every|all|grep|grep-limit|paths|from|seeds|source|lang|language|languages|src|library|exclude-tests|' - 'debug|range|selftest|version|exact|evidence|no-evidence|verbs|alongside|drop|slug') + 'debug|range|selftest|version|exact|evidence|no-evidence|verbs|alongside|drop|slug|direction|continue|branch') _OPTION = re.compile(r"(? str: +def context(task: str, source: bool = False, start_symbol: str = '', direction: str = '', max_depth: int = 0, + token_budget: int = 0) -> str: """How something works, from a task in words: the files and callables the task touches, and for a "how does X work" question the call FLOW — every step in the order the calls are written, with ⚠ where the graph lost a - call. source=True asks for the flow with each step's code, so it is read without opening files.""" - return answer(['context', task] + (['--source'] if source else []) + [os.getcwd()]) + call. source=True asks for the flow with each step's code, so it is read without opening files. + start_symbol starts the flow at that declaration. direction (callers, callees or both) and max_depth bound the + walk; token_budget bounds the answer's size. Each is optional: left out, the answer is today's.""" + # interface only: start_symbol and token_budget map to the existing + # --from and --page-budget; direction and max_depth are checked by the CLI and not yet used by the walk + # checked here, in the tool's own words: the CLI's refusal names its flag, and plain() drops a clause that does + if direction.strip() and direction.strip() not in ('callers', 'callees', 'both'): + raise ToolError(f"direction must be callers, callees or both, not {direction!r}") + if max_depth < 0: raise ToolError(f"max_depth must be 1 or more, not {max_depth}") + if token_budget < 0: raise ToolError(f"token_budget must be a positive number of tokens, not {token_budget}") + return answer(['context', task] + (['--source'] if source else []) + + (['--from', start_symbol] if start_symbol.strip() else []) + + (['--direction', direction] if direction.strip() else []) + + (['--depth', str(max_depth)] if max_depth else []) + + (['--page-budget', str(token_budget)] if token_budget else []) + [os.getcwd()]) + +@srv.tool() +def expand_context(continuation_id: str, branch: str = '') -> str: + """Continue a context answer that stopped early: continuation_id as the answer gives it, and branch (optional) + one of the branches it lists as remaining. Not implemented yet: every call is refused.""" + # until the CLI implements --continue, refused here in the tool's own words (its refusal names the flag) + raise ToolError("expand_context is not implemented yet: call context again with the task instead") @srv.tool() def impact(name: str = '') -> str: diff --git a/plugins/axiomcode/skills/axiomcode/SKILL.md b/plugins/axiomcode/skills/axiomcode/SKILL.md index 4978387de..41c44d0ab 100644 --- a/plugins/axiomcode/skills/axiomcode/SKILL.md +++ b/plugins/axiomcode/skills/axiomcode/SKILL.md @@ -99,6 +99,11 @@ source=True)` — source carries each step's code, so the flow is read without o words land (the graph's vocabulary is the code's identifiers); any language works once the task includes one identifier as written in the code. +Optional bounds on the walk (being built): `start_symbol` starts the flow at that declaration and +`token_budget` caps the answer's size; `direction` (callers, callees or both) and `max_depth` are accepted but not +yet used. `expand_context(continuation_id, branch)` will continue an answer that stopped early; it is not +implemented yet. Leave them all out for today's answer. + ## index `axiomcode index` builds the graph explicitly; `--lang` and `--src` narrow it. Never re-run it on an diff --git a/plugins/axiomcode/skills/axiomcode/scripts/ax_web.py b/plugins/axiomcode/skills/axiomcode/scripts/ax_web.py index 573d3b86f..6441c245c 100644 --- a/plugins/axiomcode/skills/axiomcode/scripts/ax_web.py +++ b/plugins/axiomcode/skills/axiomcode/scripts/ax_web.py @@ -46,7 +46,7 @@ def language_of(db): # the options dev's verbs take with a value (review #10, #26): the value is neither the repository nor a target -VALUE_FLAGS = ('--in', '--limit', '--depth', '--kind', '--budget', '--paths', '--page', '--from', '--seeds', '--top', '--tests-in', '--page-budget', '--grep-limit') +VALUE_FLAGS = ('--in', '--limit', '--depth', '--kind', '--budget', '--paths', '--page', '--from', '--seeds', '--top', '--tests-in', '--page-budget', '--grep-limit', '--direction', '--continue', '--branch') def like_esc(s): diff --git a/plugins/axiomcode/skills/axiomcode/scripts/axiomcode b/plugins/axiomcode/skills/axiomcode/scripts/axiomcode index 8b89b0426..4b1b8e4e8 100755 --- a/plugins/axiomcode/skills/axiomcode/scripts/axiomcode +++ b/plugins/axiomcode/skills/axiomcode/scripts/axiomcode @@ -195,7 +195,7 @@ dirlike(){ [[ "$1" =~ :[0-9]+$ ]] && return 1 gone(){ echo "axiomcode $cmd: no such directory: $1 (the repository to ask). Nothing was built or asked; pass a directory that exists, or leave it out to use the current one." >&2; exit 2; } POS=(); skip=""; for a in ${ARGS[@]+"${ARGS[@]}"}; do if [ -n "$skip" ]; then skip=""; continue; fi - case "$a" in --in|--from|--budget|--seeds|--depth|--limit|--tests-in|--kind|--range|--old|--new|--file|--page|--page-budget|--out|--from-text|--top) skip=1; continue ;; -*) continue ;; esac + case "$a" in --in|--from|--budget|--seeds|--depth|--limit|--tests-in|--kind|--range|--old|--new|--file|--page|--page-budget|--out|--from-text|--top|--direction|--continue|--branch) skip=1; continue ;; -*) continue ;; esac POS+=("$a") done LASTPOS=""; [ "${#POS[@]}" -gt 0 ] && LASTPOS="${POS[${#POS[@]}-1]}" @@ -209,7 +209,7 @@ case "$cmd" in esac FR=.; skip=""; for a in ${ARGS[@]+"${ARGS[@]}"}; do if [ -n "$skip" ]; then skip=""; continue; fi - case "$a" in --in|--from|--budget|--seeds|--depth|--limit|--tests-in|--kind|--range|--old|--new|--file|--page|--page-budget|--out) skip=1; continue ;; esac + case "$a" in --in|--from|--budget|--seeds|--depth|--limit|--tests-in|--kind|--range|--old|--new|--file|--page|--page-budget|--out|--direction|--continue|--branch) skip=1; continue ;; esac [ -d "$a" ] && FR="$a" done # --grep (internal: the suites and their cases): the answer's sites one per line, `path:line: code [tag]`, the way diff --git a/plugins/axiomcode/skills/axiomcode/scripts/axiomcode-context b/plugins/axiomcode/skills/axiomcode/scripts/axiomcode-context index df420db32..51ced7724 100755 --- a/plugins/axiomcode/skills/axiomcode/scripts/axiomcode-context +++ b/plugins/axiomcode/skills/axiomcode/scripts/axiomcode-context @@ -1526,7 +1526,13 @@ def print_flow(g, roots, steps, gaps, chosen, show_source=False, marks=None): RESULT = {'task': None, 'repo': None, 'scope': None, 'scope_offered': None, 'terms': [], - 'entry_points': [], 'files': [], 'flow': []} + 'entry_points': [], 'files': [], 'flow': [], + # the walk's own account of where it stopped. Not computed yet, + # so None (unknown), never an empty list that would read as "nothing omitted" + 'depth_reached': None, 'stop_reason': None, 'branches_remaining': None, 'continuation_id': None, + 'unresolved': None, 'omitted': None} + +DIRECTIONS = ('callers', 'callees', 'both') def main(argv): @@ -1540,6 +1546,7 @@ def main(argv): as_json = False explain = None # None: decided from the task's wording; --explain / --no-explain force it starts = [] # --from : where the flow starts, when the caller knows (repeatable) + direction = depth = continuation = branch = None # --direction, --depth, --continue, --branch i = 0 while i < len(argv): a = argv[i] @@ -1554,8 +1561,21 @@ def main(argv): elif a == '--explain': explain = True; i += 1 elif a == '--from' and i + 1 < len(argv): starts.append(argv[i + 1]); explain = True if explain is None else explain; i += 2 elif a == '--no-explain': explain = False; i += 1 + # interface only: parsed and checked so a bad value is refused rather than read as task words; + # the walk does not use them yet + elif a == '--direction' and i + 1 < len(argv): direction = argv[i + 1]; i += 2 + elif a == '--depth' and i + 1 < len(argv): depth = argv[i + 1]; i += 2 + elif a == '--continue' and i + 1 < len(argv): continuation = argv[i + 1]; i += 2 + elif a == '--branch' and i + 1 < len(argv): branch = argv[i + 1]; i += 2 elif a in ('-h', '--help'): print(__doc__); return 0 else: args.append(a); i += 1 + if continuation is not None or branch is not None: + print("context --continue is not implemented yet: ask context again with the task instead") + return 2 + if direction is not None and direction not in DIRECTIONS: + print(f"--direction must be one of {', '.join(DIRECTIONS)}, not {direction!r}"); return 2 + if depth is not None and not (depth.isdigit() and int(depth) >= 1): + print(f"--depth must be a whole number, 1 or more, not {depth!r}"); return 2 if not args: print(__doc__); return 2 task = args[0] repo = args[1] if len(args) > 1 else '.' @@ -2004,7 +2024,7 @@ QUOTED = re.compile(r'"([^"\n]{4,120})"|(? 2): - bad.append(f"{label}: {name} takes {params}, want {TOOLS[name]} (at most two)") + if name in TOOLS and (sorted(params) != sorted(TOOLS[name]) or len(params) > MAX_PARAMS.get(name, 2)): + bad.append(f"{label}: {name} takes {params}, want {TOOLS[name]} (at most {MAX_PARAMS.get(name, 2)})") content = replies.get(3, {}).get('result', {}).get('content', []) if not any(c.get('type') == 'text' and c.get('text') for c in content): bad.append(f"{label}: tools/call returned no text: {replies.get(3)}") diff --git a/tests/mcp_docs.py b/tests/mcp_docs.py index 6884dab3b..c751981fc 100644 --- a/tests/mcp_docs.py +++ b/tests/mcp_docs.py @@ -130,7 +130,7 @@ def controls(tools): got = len(mismatches(documented(text), fake, 'control')) if got != want: bad.append(f"control {text!r}: {got} mismatch(es), want {want}") - if set(tools) != {'context', 'impact', 'link', 'path', 'tests', 'unresolved'}: + if set(tools) != {'context', 'expand_context', 'impact', 'link', 'path', 'tests', 'unresolved'}: bad.append(f"the server listed {sorted(tools)}; the MCP tools were not read") return bad diff --git a/tests/surfaces.py b/tests/surfaces.py index 76f9ece01..e0c38cb60 100644 --- a/tests/surfaces.py +++ b/tests/surfaces.py @@ -33,6 +33,7 @@ NO_MCP = {'index': 'setup, not a question: the first query through the MCP server builds the graph itself', 'report': 'a page for the user, not a question for the agent: the end-of-turn receipt already reaches both', 'graph': 'a page for the user to look at, not an answer for the agent'} +MCP_ONLY = {'expand_context': 'context --continue: the continuation of a context answer, so it is not a second verb'} # dispatched, not advertised: verb -> why INTERNAL = { 'build': 'the old name of index', @@ -123,8 +124,8 @@ def main(): for v in INTERNAL: if v in tools: bad.append(f"{v}: internal, and still an MCP tool") if re.search(r'^## .*\b%s\b' % re.escape(v), skill, re.M): bad.append(f"{v}: internal, and still a SKILL.md section") - if tools != {v for v in PUBLIC if v not in NO_MCP}: - bad.append(f"the MCP tools are {sorted(tools)}, want {sorted(v for v in PUBLIC if v not in NO_MCP)}") + if tools != {v for v in PUBLIC if v not in NO_MCP} | set(MCP_ONLY): + bad.append(f"the MCP tools are {sorted(tools)}, want {sorted({v for v in PUBLIC if v not in NO_MCP} | set(MCP_ONLY))}") for label, text in docs(): bad += doc_findings(label, text) From 3ca07e3da2432e1de6bd6a0e3bede2aae8547cb0 Mon Sep 17 00:00:00 2001 From: asdacdsfca Date: Mon, 23 Nov 2026 12:21:21 -0500 Subject: [PATCH 2/2] context: direction and max_depth bound the file walk and the flow The file walk follows only the edges a direction asks for, out to --depth; the flow takes --depth as its cap and is not told for callers only. Which way a direction follows an edge is defined once, in ax_walk.py, for the CLI and the MCP server. With the inputs left out, both walks keep today's bounds. --- plugins/axiomcode/AGENTS.md | 2 +- plugins/axiomcode/mcp/server.py | 9 +-- plugins/axiomcode/skills/axiomcode/SKILL.md | 9 +-- .../skills/axiomcode/scripts/ax_walk.py | 14 ++++ .../axiomcode/scripts/axiomcode-context | 64 ++++++++++++------- .../case.json | 24 +++++++ .../src/checkout.py | 5 ++ .../src/logger.py | 2 + .../src/payment.py | 5 ++ .../src/receipt.py | 5 ++ 10 files changed, 108 insertions(+), 31 deletions(-) create mode 100644 plugins/axiomcode/skills/axiomcode/scripts/ax_walk.py create mode 100644 tests/cases/python/context-walk-direction-and-depth/case.json create mode 100644 tests/cases/python/context-walk-direction-and-depth/src/checkout.py create mode 100644 tests/cases/python/context-walk-direction-and-depth/src/logger.py create mode 100644 tests/cases/python/context-walk-direction-and-depth/src/payment.py create mode 100644 tests/cases/python/context-walk-direction-and-depth/src/receipt.py diff --git a/plugins/axiomcode/AGENTS.md b/plugins/axiomcode/AGENTS.md index 087caf457..67fe582f2 100644 --- a/plugins/axiomcode/AGENTS.md +++ b/plugins/axiomcode/AGENTS.md @@ -14,7 +14,7 @@ that never spell the name: subagent with /axiomcode:fill context(task) how something works, as a narrative: the call flow step by step; context(task, source=True) carries each step's code; - start_symbol, direction, max_depth and token_budget bound the walk (being built) + start_symbol, direction, max_depth and token_budget bound the walk Without the tools, the same from the shell: `axiomcode impact `, `axiomcode path `, `axiomcode tests`, `axiomcode context "" --source`. diff --git a/plugins/axiomcode/mcp/server.py b/plugins/axiomcode/mcp/server.py index f0771e372..02075cb34 100755 --- a/plugins/axiomcode/mcp/server.py +++ b/plugins/axiomcode/mcp/server.py @@ -331,11 +331,12 @@ def context(task: str, source: bool = False, start_symbol: str = '', direction: call. source=True asks for the flow with each step's code, so it is read without opening files. start_symbol starts the flow at that declaration. direction (callers, callees or both) and max_depth bound the walk; token_budget bounds the answer's size. Each is optional: left out, the answer is today's.""" - # interface only: start_symbol and token_budget map to the existing - # --from and --page-budget; direction and max_depth are checked by the CLI and not yet used by the walk + # start_symbol and token_budget map to the existing + # --from and --page-budget; direction and max_depth map to the CLI's --direction and --depth # checked here, in the tool's own words: the CLI's refusal names its flag, and plain() drops a clause that does - if direction.strip() and direction.strip() not in ('callers', 'callees', 'both'): - raise ToolError(f"direction must be callers, callees or both, not {direction!r}") + directions = scripts_module('ax_walk').DIRECTIONS # the one list the CLI walks by (ax_walk.py) + if direction.strip() and direction.strip() not in directions: + raise ToolError(f"direction must be one of {', '.join(directions)}, not {direction!r}") if max_depth < 0: raise ToolError(f"max_depth must be 1 or more, not {max_depth}") if token_budget < 0: raise ToolError(f"token_budget must be a positive number of tokens, not {token_budget}") return answer(['context', task] + (['--source'] if source else []) diff --git a/plugins/axiomcode/skills/axiomcode/SKILL.md b/plugins/axiomcode/skills/axiomcode/SKILL.md index 41c44d0ab..54220bc9c 100644 --- a/plugins/axiomcode/skills/axiomcode/SKILL.md +++ b/plugins/axiomcode/skills/axiomcode/SKILL.md @@ -99,10 +99,11 @@ source=True)` — source carries each step's code, so the flow is read without o words land (the graph's vocabulary is the code's identifiers); any language works once the task includes one identifier as written in the code. -Optional bounds on the walk (being built): `start_symbol` starts the flow at that declaration and -`token_budget` caps the answer's size; `direction` (callers, callees or both) and `max_depth` are accepted but not -yet used. `expand_context(continuation_id, branch)` will continue an answer that stopped early; it is not -implemented yet. Leave them all out for today's answer. +Optional bounds on the walk: `start_symbol` starts the flow at that declaration and `token_budget` caps the +answer's size. `direction` is which way the walk follows calls — `callers` (who calls it, for what a change +breaks), `callees` (what it calls, for how it works) or `both`, the default; the flow is told only when the walk goes +to callees. `max_depth` is how many calls away it goes (by default 3 for the files, 4 for the flow). +`expand_context(continuation_id, branch)` will continue an answer that stopped early; it is not implemented yet. ## index diff --git a/plugins/axiomcode/skills/axiomcode/scripts/ax_walk.py b/plugins/axiomcode/skills/axiomcode/scripts/ax_walk.py new file mode 100644 index 000000000..152c08950 --- /dev/null +++ b/plugins/axiomcode/skills/axiomcode/scripts/ax_walk.py @@ -0,0 +1,14 @@ +"""ax_walk.py: which way a walk over the call graph follows a call edge. One definition, for every surface. + +A call edge points from caller to callee. A walk FORWARD reaches what a declaration calls; a walk BACKWARD reaches +what calls it. A direction is a set of ways, so a new one (say, a type's implementers) is one more entry here, not a +new branch in each verb. + +Its own module, with nothing imported, because the MCP server checks a direction before it runs the CLI (the CLI's +refusal names its flag, which the server's answer drops) and the context verb walks by it: a second list in either +would be one that drifts. +""" + +FORWARD, BACKWARD = 'forward', 'backward' +DIRECTIONS = {'callees': {FORWARD}, 'callers': {BACKWARD}, 'both': {FORWARD, BACKWARD}} +DEFAULT_DIRECTION = 'both' diff --git a/plugins/axiomcode/skills/axiomcode/scripts/axiomcode-context b/plugins/axiomcode/skills/axiomcode/scripts/axiomcode-context index 51ced7724..a28a5c3fc 100755 --- a/plugins/axiomcode/skills/axiomcode/scripts/axiomcode-context +++ b/plugins/axiomcode/skills/axiomcode/scripts/axiomcode-context @@ -39,6 +39,7 @@ import importlib.machinery, importlib.util, math, os, re, sys, collections HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) import ax_edges, ax_text +from ax_walk import FORWARD, BACKWARD, DIRECTIONS, DEFAULT_DIRECTION # which way a walk follows a call edge from ax_contract import (subtokens, TESTY, SPLIT, CAMEL, require_scope, sole_scope, best_scope, budgeted, BOUND, scope_spec, under_scope, scope_sql, dirs_with_counts, drop_ancestors, offer, task_text, task_terms, winnow, headline, is_synthetic, code_terms, @@ -1071,12 +1072,18 @@ def source_lines(repo, f): return _SRC[f] -def neighbourhood(g, seed_ids, cap=3): - """{symbol id: nearest hop} out to `cap` hops, both directions. Callers matter as much as callees for - "where is this handled" — the thing you are looking for is often what CALLS the name you recognised.""" +NEIGHBOURHOOD_DEPTH = 3 + +def neighbourhood(g, seed_ids, cap=NEIGHBOURHOOD_DEPTH, direction=DEFAULT_DIRECTION, report=None): + """{symbol id: nearest hop} out to `cap` hops, both directions by default. Callers matter as much as callees for + "where is this handled" — the thing you are looking for is often what CALLS the name you recognised. + `report`, when given, is filled with where the walk stopped: depth_reached, and stop_reason — complete when + nothing was left to reach, depth_limit when the cap cut it.""" + ways = DIRECTIONS[direction] adj = collections.defaultdict(set) for a, b, _t in g.edges(): - adj[a].add(b); adj[b].add(a) + if FORWARD in ways: adj[a].add(b) + if BACKWARD in ways: adj[b].add(a) depth = {s: 0 for s in seed_ids} frontier = list(seed_ids) for d in range(1, cap + 1): @@ -1086,6 +1093,10 @@ def neighbourhood(g, seed_ids, cap=3): if y not in depth: depth[y] = d; nxt.append(y) frontier = nxt if not frontier: break + if report is not None: + report['depth_reached'] = max(depth.values(), default=0) + report['stop_reason'] = ('depth_limit' if any(y not in depth for x in frontier for y in adj.get(x, ())) + else 'complete') return depth @@ -1465,10 +1476,10 @@ def type_members(g, types, scored): return out -def print_flow(g, roots, steps, gaps, chosen, show_source=False, marks=None): +def print_flow(g, roots, steps, gaps, chosen, show_source=False, marks=None, depth_cap=FLOW_DEPTH): if not steps: return False print("\nhow it runs — the call flow from " + ("where you started it" if chosen else "this task's entry points") - + ", every callee in the order the calls are written, to depth " + str(FLOW_DEPTH) + + ", every callee in the order the calls are written, to depth " + str(depth_cap) + " (→ resolved call, ⇢ one of a set; ⚠ a call the graph could not resolve — read that body to follow it):") if not chosen: print(" started at the entry points this task's words matched; if the mechanism begins elsewhere, " @@ -1527,13 +1538,11 @@ def print_flow(g, roots, steps, gaps, chosen, show_source=False, marks=None): RESULT = {'task': None, 'repo': None, 'scope': None, 'scope_offered': None, 'terms': [], 'entry_points': [], 'files': [], 'flow': [], - # the walk's own account of where it stopped. Not computed yet, - # so None (unknown), never an empty list that would read as "nothing omitted" + # the file walk's own account of where it stopped (neighbourhood). A field still None is not computed yet + # (unknown), never an empty list that would read as "nothing omitted" 'depth_reached': None, 'stop_reason': None, 'branches_remaining': None, 'continuation_id': None, 'unresolved': None, 'omitted': None} -DIRECTIONS = ('callers', 'callees', 'both') - def main(argv): # 12 files by default, not 40. The answer is read by an agent that pays for every line on every later @@ -1546,7 +1555,7 @@ def main(argv): as_json = False explain = None # None: decided from the task's wording; --explain / --no-explain force it starts = [] # --from : where the flow starts, when the caller knows (repeatable) - direction = depth = continuation = branch = None # --direction, --depth, --continue, --branch + direction = max_depth = continuation = branch = None # --direction, --depth, --continue, --branch i = 0 while i < len(argv): a = argv[i] @@ -1561,10 +1570,9 @@ def main(argv): elif a == '--explain': explain = True; i += 1 elif a == '--from' and i + 1 < len(argv): starts.append(argv[i + 1]); explain = True if explain is None else explain; i += 2 elif a == '--no-explain': explain = False; i += 1 - # interface only: parsed and checked so a bad value is refused rather than read as task words; - # the walk does not use them yet + # the walk's bounds: which way it follows calls, and how many hops (both walks: the files and the flow) elif a == '--direction' and i + 1 < len(argv): direction = argv[i + 1]; i += 2 - elif a == '--depth' and i + 1 < len(argv): depth = argv[i + 1]; i += 2 + elif a == '--depth' and i + 1 < len(argv): max_depth = argv[i + 1]; i += 2 elif a == '--continue' and i + 1 < len(argv): continuation = argv[i + 1]; i += 2 elif a == '--branch' and i + 1 < len(argv): branch = argv[i + 1]; i += 2 elif a in ('-h', '--help'): print(__doc__); return 0 @@ -1574,8 +1582,11 @@ def main(argv): return 2 if direction is not None and direction not in DIRECTIONS: print(f"--direction must be one of {', '.join(DIRECTIONS)}, not {direction!r}"); return 2 - if depth is not None and not (depth.isdigit() and int(depth) >= 1): - print(f"--depth must be a whole number, 1 or more, not {depth!r}"); return 2 + if max_depth is not None and not (max_depth.isdigit() and int(max_depth) >= 1): + print(f"--depth must be a whole number, 1 or more, not {max_depth!r}"); return 2 + direction = direction or DEFAULT_DIRECTION + files_depth = int(max_depth) if max_depth else NEIGHBOURHOOD_DEPTH + flow_depth = int(max_depth) if max_depth else FLOW_DEPTH if not args: print(__doc__); return 2 task = args[0] repo = args[1] if len(args) > 1 else '.' @@ -1782,6 +1793,9 @@ def main(argv): print() print(f"task terms: {' · '.join(terms[:10])}" + (f" (+{len(terms)-10})" if len(terms) > 10 else '')) if explain is None: explain = explain_intent(task) + # the flow follows calls forward, to callees: a walk asked to go only backward has no flow to tell, and its answer + # is the files around the entry points instead + if explain and FORWARD not in DIRECTIONS[direction]: explain = False # explaining: the flow below starts at its own roots and IS the answer, so the lexical entry points (a word # match per term) and the long file list are what a reader would spend the page on instead of the flow if explain: budget = min(budget, 0 if show_source else 5) # with the code shown, the flow is the whole answer @@ -1826,7 +1840,7 @@ def main(argv): roots_ = producer_first(g, roots_, [s_ for s_, _t, _sc in seeds], task, terms) # a producer joined only by name is shown as one step: its code holds the call, and the budget goes to the # mechanism the task asked about rather than to everything else the producer does - roots, steps, gaps, marks = flow(g, roots_, max_steps=FLOW_SOURCE_STEPS if show_source else FLOW_STEPS, + roots, steps, gaps, marks = flow(g, roots_, depth_cap=flow_depth, max_steps=FLOW_SOURCE_STEPS if show_source else FLOW_STEPS, shallow=frozenset(ENTRY_NOTE)) RESULT['flow'] = [{'step': k + 1, 'depth': d, 'name': g.disp(x), 'at': g.loc(x), 'called_at_line': (via[0] if via else None), 'certainty': (ax_edges.direct_cert(via[1]) if via else 'entry'), @@ -1837,7 +1851,7 @@ def main(argv): and (x, via[0], via[2]) in HANDOFF else None), 'leaves_graph': (marks.get(x, []) if again is None else [])} for k, (d, x, via, again) in enumerate(steps)] - if not print_flow(g, roots, steps, gaps, bool(starts), show_source, marks): + if not print_flow(g, roots, steps, gaps, bool(starts), show_source, marks, depth_cap=flow_depth): # the entry points and files were held back because the flow was to BE the answer; with no flow they are # the answer again, so they are printed, and the reader is told why there is no flow print("\nno call flow: " + ("none of the entry points is a callable, or a type declaring one" @@ -1848,7 +1862,9 @@ def main(argv): print(f" {g.disp(sid):46.46} {g.loc(sid):34.34} {term or 'best overall match'}") budget = max(budget, 5) - depth = neighbourhood(g, [s for s, _t, _sc in seeds]) + walk = {} + depth = neighbourhood(g, [s for s, _t, _sc in seeds], cap=files_depth, direction=direction, report=walk) + RESULT.update(walk) # A file can match the task by NAME and be reachable by no call at all — an enum of flags, a constants # module, a config surface. Those have no callers by construction, so a list built only from the call # closure drops them however well they match: on one task the file was literally named for the word the @@ -1891,12 +1907,16 @@ def main(argv): return (d - 0.8 * hit - 1.6 * pkg, d, f) if scopes and not scope_offered: files = {f: v for f, v in files.items() if in_scope(f)} order = sorted(files.items(), key=file_rank) - shown, foot = budgeted([x for x in order if not TESTY.search(x[0])], budget, "file") + listed = [x for x in order if not TESTY.search(x[0])] + shown, foot = budgeted(listed, budget, "file") + # what the budget cut, by name: the walk reached these and the answer does not list them + RESULT['omitted'] = [f for f, _v in listed[len(shown):]] + if RESULT['omitted']: RESULT['stop_reason'] = 'budget_limit' if budget > 0: - print(f"\nwhere the work is ({len(files)} file(s) within 3 hops of those entry points; " + print(f"\nwhere the work is ({len(files)} file(s) within {files_depth} hops of those entry points; " f"nearest first, then by how much of the task each matches):") else: - print(f"\n{len(files)} file(s) lie within 3 hops of the entry points; `--budget N` lists them") + print(f"\n{len(files)} file(s) lie within {files_depth} hops of the entry points; `--budget N` lists them") # Name the DECLARATIONS, not only the file. Every symbol here was already scored — that is how the file # got its rank — and then discarded, so the answer said "look in this file" where it could have said # which functions to look at. Measured over 31 real commits, naming two declarations per file roughly diff --git a/tests/cases/python/context-walk-direction-and-depth/case.json b/tests/cases/python/context-walk-direction-and-depth/case.json new file mode 100644 index 000000000..1ad5faae6 --- /dev/null +++ b/tests/cases/python/context-walk-direction-and-depth/case.json @@ -0,0 +1,24 @@ +{"lang": "python", "src": "src", + "checks": [ + {"why": "control: with no bounds the file walk goes both ways, so a declaration's caller and its callee are both listed", + "run": ["context", "change send_receipt", "--no-explain"], + "want": ["within 3 hops", "payment.py", "logger.py", "checkout.py"]}, + {"why": "direction callers follows calls backward only: who calls send_receipt, and who calls that, never what it calls", + "run": ["context", "change send_receipt", "--no-explain", "--direction", "callers"], + "want": ["payment.py", "checkout.py"], + "avoid": ["logger.py"]}, + {"why": "direction callees follows calls forward only: what send_receipt calls, never who calls it", + "run": ["context", "change send_receipt", "--no-explain", "--direction", "callees"], + "want": ["logger.py"], + "avoid": ["payment.py", "checkout.py"]}, + {"why": "depth bounds the file walk: one hop back reaches the direct caller and stops before the caller's caller", + "run": ["context", "change send_receipt", "--no-explain", "--direction", "callers", "--depth", "1"], + "want": ["within 1 hops", "payment.py"], + "avoid": ["checkout.py"]}, + {"why": "depth bounds the flow too: one hop from checkout is its own call, not the calls beneath it", + "run": ["context", "how does checkout work", "--depth", "1"], + "want": ["to depth 1", "charge_card"], + "avoid": ["send_receipt", "write_log"]}, + {"why": "the flow follows calls forward, so a walk asked to go only backward tells no flow", + "run": ["context", "how does checkout work", "--direction", "callers"], + "avoid": ["how it runs"]}]} diff --git a/tests/cases/python/context-walk-direction-and-depth/src/checkout.py b/tests/cases/python/context-walk-direction-and-depth/src/checkout.py new file mode 100644 index 000000000..bdf5d3169 --- /dev/null +++ b/tests/cases/python/context-walk-direction-and-depth/src/checkout.py @@ -0,0 +1,5 @@ +from payment import charge_card + + +def checkout(order): + return charge_card(order) diff --git a/tests/cases/python/context-walk-direction-and-depth/src/logger.py b/tests/cases/python/context-walk-direction-and-depth/src/logger.py new file mode 100644 index 000000000..40b1622c8 --- /dev/null +++ b/tests/cases/python/context-walk-direction-and-depth/src/logger.py @@ -0,0 +1,2 @@ +def write_log(order): + return order diff --git a/tests/cases/python/context-walk-direction-and-depth/src/payment.py b/tests/cases/python/context-walk-direction-and-depth/src/payment.py new file mode 100644 index 000000000..f2665817e --- /dev/null +++ b/tests/cases/python/context-walk-direction-and-depth/src/payment.py @@ -0,0 +1,5 @@ +from receipt import send_receipt + + +def charge_card(order): + return send_receipt(order) diff --git a/tests/cases/python/context-walk-direction-and-depth/src/receipt.py b/tests/cases/python/context-walk-direction-and-depth/src/receipt.py new file mode 100644 index 000000000..fc73da4bc --- /dev/null +++ b/tests/cases/python/context-walk-direction-and-depth/src/receipt.py @@ -0,0 +1,5 @@ +from logger import write_log + + +def send_receipt(order): + return write_log(order)