Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion plugins/axiomcode/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Without the tools, the same from the shell: `axiomcode impact <name>`,
`axiomcode path <A> <B>`, `axiomcode tests`, `axiomcode context "<task>" --source`.
Expand Down
34 changes: 28 additions & 6 deletions plugins/axiomcode/mcp/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"""
Expand Down Expand Up @@ -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"(?<![\w(-])--(?:" + _CLI_OPTIONS + r")(?![\w-])(?!\s*:)|\b(?:task|source|name|start|end)=(?:True|False|N\b|<|\d|\"|')")
def plain(text):
out = []; code = False
Expand Down Expand Up @@ -322,13 +322,35 @@ def answer(args):
# THE SMALL SURFACE. Search is grep's job; the graph answers what grep cannot. Three questions, each answered as
# numbered places with the code of the function each sits in, so a place is understood without opening its file,
# plus context, the one narrative verb: a task in words answered as the verb's own flow. No options beyond
# context's source: the repository is the one the session works in.
# context's source and its walk bounds: the repository is the one the session works in.
@srv.tool()
def context(task: str, source: bool = False) -> 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."""
# 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
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 [])
+ (['--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:
Expand Down
6 changes: 6 additions & 0 deletions plugins/axiomcode/skills/axiomcode/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,12 @@ 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: `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

`axiomcode index` builds the graph explicitly; `--lang` and `--src` narrow it. Never re-run it on an
Expand Down
14 changes: 14 additions & 0 deletions plugins/axiomcode/skills/axiomcode/scripts/ax_walk.py
Original file line number Diff line number Diff line change
@@ -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'
2 changes: 1 addition & 1 deletion plugins/axiomcode/skills/axiomcode/scripts/ax_web.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
4 changes: 2 additions & 2 deletions plugins/axiomcode/skills/axiomcode/scripts/axiomcode
Original file line number Diff line number Diff line change
Expand Up @@ -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]}"
Expand All @@ -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
Expand Down
68 changes: 54 additions & 14 deletions plugins/axiomcode/skills/axiomcode/scripts/axiomcode-context
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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):
Expand All @@ -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


Expand Down Expand Up @@ -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, "
Expand Down Expand Up @@ -1526,7 +1537,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': []}
'entry_points': [], 'files': [], 'flow': [],
# 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}


def main(argv):
Expand All @@ -1540,6 +1555,7 @@ def main(argv):
as_json = False
explain = None # None: decided from the task's wording; --explain / --no-explain force it
starts = [] # --from <name>: where the flow starts, when the caller knows (repeatable)
direction = max_depth = continuation = branch = None # --direction, --depth, --continue, --branch
i = 0
while i < len(argv):
a = argv[i]
Expand All @@ -1554,8 +1570,23 @@ 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
# 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): 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
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 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 '.'
Expand Down Expand Up @@ -1762,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
Expand Down Expand Up @@ -1806,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'),
Expand All @@ -1817,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"
Expand All @@ -1828,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
Expand Down Expand Up @@ -1871,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
Expand Down Expand Up @@ -2004,7 +2044,7 @@ QUOTED = re.compile(r'"([^"\n]{4,120})"|(?<![\w])\'([^\'\n]{4,120})\'(?![\w])|`(


def quoted_text(argv):
skip = {'--budget', '--seeds', '--in', '--from', '--page', '--page-budget'}
skip = {'--budget', '--seeds', '--in', '--from', '--page', '--page-budget', '--direction', '--depth', '--continue', '--branch'}
pos, i = [], 0
while i < len(argv):
if argv[i] in skip: i += 2; continue
Expand Down
Loading
Loading