diff --git a/gemini-extension.json b/gemini-extension.json index 61a14197f..9cfece080 100644 --- a/gemini-extension.json +++ b/gemini-extension.json @@ -1,6 +1,6 @@ { "name": "axiomcode", - "version": "0.2.3", + "version": "0.2.4", "description": "Ask your repository how its code connects: who calls this, what breaks if I change it, which tests an edit reaches, how A reaches B. Answers come from a resolved call graph and are verified against it; nothing is guessed.", "contextFileName": "plugins/axiomcode/AGENTS.md", "mcpServers": { diff --git a/hooks/hooks.json b/hooks/hooks.json index 8f6c08289..67d8fbdf0 100644 --- a/hooks/hooks.json +++ b/hooks/hooks.json @@ -5,7 +5,8 @@ "hooks": [ { "type": "command", "command": "node \"${extensionPath}${/}plugins${/}axiomcode${/}hooks${/}run.js\" changes.py", "timeout": 25000 }, { "type": "command", "command": "node \"${extensionPath}${/}plugins${/}axiomcode${/}hooks${/}run.js\" orient.py", "timeout": 20000 }, - { "type": "command", "command": "node \"${extensionPath}${/}plugins${/}axiomcode${/}hooks${/}run.js\" refresh.py", "timeout": 5000 } + { "type": "command", "command": "node \"${extensionPath}${/}plugins${/}axiomcode${/}hooks${/}run.js\" refresh.py", "timeout": 5000 }, + { "type": "command", "command": "node \"${extensionPath}${/}plugins${/}axiomcode${/}hooks${/}run.js\" fill.py", "timeout": 10000 } ] } ], diff --git a/package.json b/package.json index c1fd43e95..144dabe85 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@axiomcode/code-graph", - "version": "0.2.3", + "version": "0.2.4", "description": "AxiomCode Graph: a resolved call graph of your codebase grounded in formal methods, so you and your coding agents can see who calls what, what a change breaks, and which tests it reaches.", "repository": { "type": "git", @@ -31,11 +31,11 @@ ], "license": "FSL-1.1-Apache-2.0", "optionalDependencies": { - "@axiomcode/engine-darwin-arm64": "0.2.3", - "@axiomcode/engine-darwin-x64": "0.2.3", - "@axiomcode/engine-linux-x64": "0.2.3", - "@axiomcode/engine-linux-arm64": "0.2.3", - "@axiomcode/engine-win32-x64": "0.2.3" + "@axiomcode/engine-darwin-arm64": "0.2.4", + "@axiomcode/engine-darwin-x64": "0.2.4", + "@axiomcode/engine-linux-x64": "0.2.4", + "@axiomcode/engine-linux-arm64": "0.2.4", + "@axiomcode/engine-win32-x64": "0.2.4" }, "bin": { "axiomcode": "bin/axiomcode.js" diff --git a/plugins/axiomcode/.claude-plugin/plugin.json b/plugins/axiomcode/.claude-plugin/plugin.json index a45810eee..55c135b5e 100644 --- a/plugins/axiomcode/.claude-plugin/plugin.json +++ b/plugins/axiomcode/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "axiomcode", "description": "Ask your repository how its code connects: who calls this, what breaks if I change it, which tests an edit reaches, how A reaches B. Answers come from a resolved call graph and are verified against it; nothing is guessed.", - "version": "0.2.3", + "version": "0.2.4", "author": { "name": "AxiomCode" } diff --git a/plugins/axiomcode/.codex-plugin/plugin.json b/plugins/axiomcode/.codex-plugin/plugin.json index 29c2ba521..c5a0c074c 100644 --- a/plugins/axiomcode/.codex-plugin/plugin.json +++ b/plugins/axiomcode/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "axiomcode", - "version": "0.2.3", + "version": "0.2.4", "description": "Ask your repository how its code connects: who calls this, what breaks if I change it, which tests an edit reaches, how A reaches B. Answers come from a resolved call graph and are verified against it; nothing is guessed.", "author": { "name": "AxiomCode", "url": "https://github.com/AxiomCodeAI/axiomcodegraph" }, "homepage": "https://github.com/AxiomCodeAI/axiomcodegraph", diff --git a/plugins/axiomcode/.cursor-plugin/plugin.json b/plugins/axiomcode/.cursor-plugin/plugin.json index fadd636d0..a797bda89 100644 --- a/plugins/axiomcode/.cursor-plugin/plugin.json +++ b/plugins/axiomcode/.cursor-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "axiomcode", - "version": "0.2.3", + "version": "0.2.4", "description": "Ask your repository how its code connects: who calls this, what breaks if I change it, which tests an edit reaches, how A reaches B. Answers come from a resolved call graph and are verified against it; nothing is guessed. Java, TypeScript, Python, JavaScript.", "author": { "name": "AxiomCode" }, "homepage": "https://github.com/AxiomCodeAI/axiomcodegraph", diff --git a/plugins/axiomcode/AGENTS.md b/plugins/axiomcode/AGENTS.md index 4d8b8abb9..dc3cd82e3 100644 --- a/plugins/axiomcode/AGENTS.md +++ b/plugins/axiomcode/AGENTS.md @@ -10,6 +10,8 @@ that never spell the name: tests() the tests your uncommitted edits reach, and the command that runs them link(site, target) record where an unresolved call lands, when the code makes it certain; impact, path and tests then walk it, labelled [asserted] + 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 diff --git a/plugins/axiomcode/hooks/fill.py b/plugins/axiomcode/hooks/fill.py new file mode 100644 index 000000000..aa04d4b17 --- /dev/null +++ b/plugins/axiomcode/hooks/fill.py @@ -0,0 +1,34 @@ +#!/usr/bin/env python3 +"""UserPromptSubmit: after a build, tell the agent once that the engine left call sites it could not resolve. + +The engine has done what it can by the end of a build; what is left is for someone who reads the code. This says so +ONCE per build (ax_fill.notice keeps the stamp in .axiomcode/.fill-noted-hook) and only when sites that may land in the +project are open, naming the one command that starts the pass: /axiomcode:fill. Silent with no graph, with nothing open, +and on every prompt after the first that heard about this build. +""" +import os, subprocess, sys +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import _host + +try: + ev = _host.read() +except Exception: + sys.exit(0) + +def repo_root(start): + cur = os.path.realpath(start) + while True: + if os.path.exists(os.path.join(cur, '.axiomcode', 'out', 'graph.sqlite')): return cur + parent = os.path.dirname(cur) + if parent == cur: return None + cur = parent + +root = repo_root(ev.get('cwd') or os.getcwd()) +if not root: sys.exit(0) +script = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'skills', 'axiomcode', 'scripts', 'ax_fill.py') +try: + r = subprocess.run([sys.executable, script, root, '--notice', 'hook'], capture_output=True, text=True, timeout=8) + line = r.stdout.strip() +except Exception: + sys.exit(0) +if line: _host.emit('UserPromptSubmit', line) diff --git a/plugins/axiomcode/hooks/hooks.json b/plugins/axiomcode/hooks/hooks.json index afe4941a9..a43d477a7 100644 --- a/plugins/axiomcode/hooks/hooks.json +++ b/plugins/axiomcode/hooks/hooks.json @@ -61,6 +61,15 @@ "timeout": 5 } ] + }, + { + "hooks": [ + { + "type": "command", + "command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/run.js\" fill.py", + "timeout": 10 + } + ] } ], "Stop": [ diff --git a/plugins/axiomcode/mcp/server.py b/plugins/axiomcode/mcp/server.py index cf1c3bda4..c90000740 100755 --- a/plugins/axiomcode/mcp/server.py +++ b/plugins/axiomcode/mcp/server.py @@ -282,12 +282,41 @@ def plain(text): if keep and ''.join(keep).strip(): out.append(' '.join(keep).rstrip(' ;,')) return '\n'.join(out) +def fill_notice(args): + """once per build, on the first query answer after it: the unresolved sites that may land in the project, and the + tools that settle them (ax_fill.notice). Every host reads a tool answer; not every host runs hooks. '' otherwise""" + if not args or args[0] not in ('impact', 'path', 'context', 'tests'): return '' + repo = repository(args) + if not os.path.isfile(os.path.join(repo, '.axiomcode', 'out', 'graph.sqlite')): return '' + # the common case, a build already told about, is a few stats and a small read here: no process is started for it. + # The stamp is ax_fill.build_stamp's: every live graph, main then each language's, each real file once + try: + ax = os.path.join(repo, '.axiomcode'); lang = os.path.join(ax, 'lang') + dbs = [os.path.join(ax, 'out', 'graph.sqlite')] + [os.path.join(lang, l, 'out', 'graph.sqlite') + for l in (sorted(os.listdir(lang)) if os.path.isdir(lang) else [])] + seen, parts = set(), [] + for db in dbs: + rp = os.path.realpath(db) + if os.path.isfile(rp) and rp not in seen: + seen.add(rp); parts.append(f"{rp}@{int(os.stat(db).st_mtime)}") + with open(os.path.join(ax, '.fill-noted-mcp'), encoding='utf-8') as fh: + if fh.read().strip() == '|'.join(parts): return '' + except OSError: pass + try: + r = subprocess.run([sys.executable, os.path.join(scripts_dir(), 'ax_fill.py'), repo, '--notice', 'mcp'], + capture_output=True, text=True, timeout=10) + return r.stdout.strip() + except Exception: return '' + + def answer(args): """a tool's answer: the CLI's words with the option-naming clauses dropped. A failure run() raises goes the same way — its words through plain(), then on as the ToolError the client marks isError — so the model reads the correction (the nearest names, the fix) either way, and a flag it cannot pass is named in neither.""" - try: return plain(run(args)) + try: out = plain(run(args)) except ToolError as e: raise ToolError(plain(str(e))) from None + note = fill_notice(args) + return f"{out}\n{note}" if note else out # THE SMALL SURFACE. Search is grep's job; the graph answers what grep cannot. Three questions, each answered as @@ -314,6 +343,25 @@ def path(start: str, end: str) -> str: written on. start / end as written in the code (Owner.method, function, Type).""" return answer(['path', start, end, os.getcwd()]) +@srv.tool() +def unresolved(limit: int = 25, decisions: str = '') -> str: + """The calls the graph could not resolve, over the whole graph: a summary line, then the next `limit` open sites + (inside the most called callers first), each with its code, the engine's reason and the graph's candidates. Read + each call, then send one decision per line as `decisions`: ` ` only when the code makes the target + CERTAIN, ` not:` for a wrong candidate, ` ?` to leave it open. The answer says what was taken + and lists the next page; settled sites drop off. Never link a guess.""" + n = str(max(1, min(int(limit or 25), 200))) + if not decisions.strip(): return answer(['unresolved', '--limit', n, os.getcwd()]) + import tempfile + with tempfile.NamedTemporaryFile('w', suffix='.tsv', delete=False, encoding='utf-8') as fh: fh.write(decisions) + try: + try: took = answer(['link', '--batch', fh.name, os.getcwd()]) + except ToolError as e: took = str(e) # a refused line is reported with the next page, not as a failure + finally: + try: os.unlink(fh.name) + except OSError: pass + return took + '\n\n' + answer(['unresolved', '--limit', n, os.getcwd()]) + @srv.tool() def link(site: str = '', target: str = '') -> str: """Record where an unresolved call lands, when you have read the code and the target is CERTAIN: site is the call's @@ -321,7 +369,7 @@ def link(site: str = '', target: str = '') -> str: its file:line). impact, path and tests then walk the edge, labelled [asserted]. With no arguments: every link and whether the graph took it (a link whose line changed is dropped, never trusted). target "-" removes the site's links; target "not:" rejects a lead (a by-name or one-of-a-set guess) at that site, which is then not walked. - Never link a guess, and never link a candidate for its rank alone.""" + Never link a guess, and never link a candidate for its rank alone. Many sites at once: unresolved(decisions=...).""" return answer(['link'] + ([site] if site.strip() else []) + ([target] if site.strip() and target.strip() else []) + [os.getcwd()]) @srv.tool() diff --git a/plugins/axiomcode/rules/axiomcode.mdc b/plugins/axiomcode/rules/axiomcode.mdc index d36b30c5a..f58580be0 100644 --- a/plugins/axiomcode/rules/axiomcode.mdc +++ b/plugins/axiomcode/rules/axiomcode.mdc @@ -15,6 +15,8 @@ that never spell the name: tests() the tests your uncommitted edits reach, and the command that runs them link(site, target) record where an unresolved call lands, when the code makes it certain; impact, path and tests then walk it, labelled [asserted] + 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 diff --git a/plugins/axiomcode/skills/axiomcode/SKILL.md b/plugins/axiomcode/skills/axiomcode/SKILL.md index e01093337..4978387de 100644 --- a/plugins/axiomcode/skills/axiomcode/SKILL.md +++ b/plugins/axiomcode/skills/axiomcode/SKILL.md @@ -19,6 +19,7 @@ Search with grep as usual; the graph answers what grep cannot. Use the MCP tools | how does A reach B? | `path(start, end)` | `axiomcode path ` | | which tests do my edits need, and how do I run them? | `tests()` | `axiomcode tests` | | an answer lists an unresolved call I can see the target of | `link(site, target)` | `axiomcode link ` | +| the graph says sites are left unresolved after a build | `unresolved()`, then `unresolved(decisions)` — or `/axiomcode:fill` | `axiomcode unresolved` | | how does this work, start to finish? | `context(task, source=True)` | `axiomcode context "" --source` | Names are written as in the code: `Owner.method`, `function`, `Type`, or `file.py:123` for the declaration at that @@ -80,6 +81,16 @@ one. A link is refused when the call written there names a different declaration the line it was made on is edited, it is dropped and listed as stale, and the site is to resolve again. Never link a guess: an asserted edge is trusted by every answer after it. +## unresolved + +After a build, a note says how many call sites the engine left unresolved that may land in the project's own code +(a library's method on a receiver it could not type is counted, not listed: reading the project does not settle it). +`/axiomcode:fill` works through them in a subagent; without it, `unresolved(limit=25)` lists the next open sites, the +ones inside the most called callers first, each with its code, the engine's reason and the candidates, and +`unresolved(decisions="...")` takes one decision per line and answers with the next page: ` ` when the code makes it certain, ` not:` +for a wrong candidate, ` ?` to leave it open (not asked again until its line changes). Settled sites drop off the +list. The same rule as `link`: never link a guess. + ## context How something works, from a task in your own words: the files and callables the task touches and, for a diff --git a/plugins/axiomcode/skills/axiomcode/scripts/ax_fill.py b/plugins/axiomcode/skills/axiomcode/scripts/ax_fill.py new file mode 100755 index 000000000..23b2da58e --- /dev/null +++ b/plugins/axiomcode/skills/axiomcode/scripts/ax_fill.py @@ -0,0 +1,431 @@ +#!/usr/bin/env python3 +"""ax_fill.py — the whole graph's unresolved call sites as a worklist, and a batch of decisions on them. + +An answer lists the unresolved sites it stopped at (ax_links.unknown_sites); nothing listed them all. The engine has done +what it can by the end of a build, so what is left is for an agent who reads the code: + + axiomcode unresolved [--limit N] [--json] the summary, then the next N open sites, the ones on the most + walked callers first, each with its code, the engine's reason and + the graph's candidates + axiomcode unresolved --summary the one-line summary only + axiomcode link --batch decisions, one per line: ` ` links, + ` not:` rejects a lead, ` ?` leaves it open + +A SITE IS OPEN when the graph holds no edge for it, no link settles it, and it was not left open by an earlier pass on +the same line text. A `?` is kept in .axiomcode/fill-skipped.tsv: derived, like everything under .axiomcode, so losing +it only asks again; a skip whose line was edited is asked again. Links go through ax_links, validated and applied the +same way as one `link` at a time, with one apply for the whole batch. +""" +import json, os, re, sqlite3, sys, time +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import ax_links + +SKIP_FILE = os.path.join('.axiomcode', 'fill-skipped.tsv') +SKIP_HEADER = '# axiomcode fill: unresolved sites an agent read and left open (`?`). Derived; deleting it only asks again. file line line_sha by at' + + +# ── the sites an earlier pass left open ────────────────────────────────────────────────────────────────────────── +def skip_path(repo): + return os.path.join(repo, SKIP_FILE) + + +def read_skips(repo): + """{(file, line): line_sha}""" + out = {} + try: + with open(skip_path(repo), encoding='utf-8', errors='replace') as fh: + for raw in fh.read().split('\n'): + if not raw.strip() or raw.startswith('#'): continue + p = raw.split('\t') + if len(p) >= 3 and p[1].isdigit(): out[(p[0], int(p[1]))] = p[2] + except OSError: pass + return out + + +def write_skips(repo, skips, by='agent'): + p = skip_path(repo) + if not os.path.isdir(os.path.dirname(p)): return + tmp = f"{p}.{os.getpid()}.tmp"; at = time.strftime('%Y-%m-%dT%H:%M:%S') + with open(tmp, 'w', encoding='utf-8') as fh: + fh.write(SKIP_HEADER + '\n') + for (f, l), sha in sorted(skips.items()): fh.write(f"{f}\t{l}\t{sha}\t{by}\t{at}\n") + os.replace(tmp, p) + + +def skipped(skips, reader, f, line): + sha = skips.get((f, line)) + if not sha: return False + L = reader.lines(f) + return bool(L) and 0 < line <= len(L) and ax_links.line_sha(L[line - 1]) == sha + + +# ── one graph's open sites ─────────────────────────────────────────────────────────────────────────────────────── +def _site_file(con): + try: m = {r[0]: r[1] for r in con.execute("SELECT raw, rel FROM paths")} + except sqlite3.Error: m = {} + return lambda raw: m.get(raw, raw) + + +def _tables(con): + return {r[0] for r in con.execute("SELECT name FROM sqlite_master WHERE type IN ('table','view')")} + + +def graph_counts(con): + """{calls, project, boundary, asserted} of one graph: every call site; those with an engine edge into the project's + own code; those whose engine edges all stop at a library or builtin; those a link settled""" + t = _tables(con) + if not all(x in t for x in ('call_sites', 'call_edges')): return dict(calls=0, project=0, boundary=0, asserted=0) + one = lambda sql: (con.execute(sql).fetchone() or [0])[0] + return dict( + calls=one("SELECT COUNT(*) FROM call_sites"), + project=one("SELECT COUNT(DISTINCT call_site_id) FROM call_edges WHERE tier <> 'asserted' AND callee_provenance = 'client'"), + boundary=one("SELECT COUNT(DISTINCT e.call_site_id) FROM call_edges e WHERE e.tier <> 'asserted' AND NOT EXISTS (SELECT 1 FROM call_edges x " + "WHERE x.call_site_id = e.call_site_id AND x.tier <> 'asserted' AND x.callee_provenance = 'client')"), + asserted=one("SELECT COUNT(DISTINCT call_site_id) FROM call_edges WHERE tier = 'asserted'")) + + +def _project_names(con): + """(the names a bare call may reach: functions, classes, consts, variables; the names a call on a receiver may + reach: methods, constructors, fields). A bare `fetch()` never reaches a method called fetch, `x.add()` never a + nested function called add""" + try: + rows = con.execute("SELECT DISTINCT name, kind FROM symbols WHERE method_id IS NOT NULL AND kind <> 'module'").fetchall() + except sqlite3.Error: return set(), set() + return {n for n, k in rows if k not in ('method', 'constructor')}, {n for n, k in rows if k in ('method', 'constructor', 'field')} + + +# a call written as a bare name or a computed callee: when the name declares nothing, it is a parameter, a local or a +# computed value, so the target may be anywhere +# (Python SIMPLE_CALL, TypeScript / JavaScript FUNCTION_CALL and JSX_COMPONENT_CALL, C# INVOCATION and DELEGATE_INVOKE) +BARE_VALUE_KINDS = {'SIMPLE_CALL', 'FUNCTION_CALL', 'LOCAL_FUNCTION_CALL', 'JSX_COMPONENT_CALL', 'INVOCATION', + 'DELEGATE_INVOKE', 'DYNAMIC_CALL', 'COMPUTED_CALL', 'FUNCTION_CALL_APPLY', 'FUNCTION_CALL_CALL', + 'FUNCTION_CALL_BIND', 'IIFE_CALL', 'DYNAMIC_CODE_CALL'} +# names a JavaScript runtime or test runner provides without an import: a bare call of one is the platform's +JS_GLOBALS = {'fetch', 'setTimeout', 'setInterval', 'setImmediate', 'clearTimeout', 'clearInterval', 'queueMicrotask', + 'structuredClone', 'require', 'atob', 'btoa', 'describe', 'it', 'test', 'expect', 'beforeEach', 'afterEach', + 'beforeAll', 'afterAll', 'suite', 'bench', 'expectTypeOf', 'assertType', 'assert', 'vi', 'jest', 'parseInt', 'parseFloat', 'isNaN', 'encodeURIComponent', + 'decodeURIComponent', 'encodeURI', 'decodeURI', 'Symbol', 'BigInt', 'String', 'Number', 'Boolean', 'Array', + 'Object', 'Date', 'Error', 'Promise', 'RegExp', 'Map', 'Set', 'WeakMap', 'WeakSet', 'Proxy', 'Reflect'} + + +def workspace_packages(repo): + """the package names the repository itself declares (a monorepo's workspaces): an import from one is project code""" + names = set() + if not repo: return names + for dirpath, dirs, files in os.walk(repo): + dirs[:] = [d for d in dirs if d not in ('node_modules', '.git', '.axiomcode', 'dist', 'build') and not d.startswith('.')] + if 'package.json' in files: + try: + with open(os.path.join(dirpath, 'package.json'), encoding='utf-8') as fh: n = json.load(fh).get('name') + if isinstance(n, str) and n: names.add(n) + except (OSError, ValueError): pass + return names + + +# an import clause: braces, names, commas, `* as x`, `type` — never a quote, a semicolon or a paren, so a Python file's +# `import os` lines cannot drag the match across the file (bounded, no backtracking past the clause) +_JS_IMPORT_ALL = re.compile(r'(?m)^[ \t]*import[ \t]+((?:type[ \t]+)?[\w$*{},\s]{1,2000}?)[ \t]*\bfrom[ \t]+[\'"]([^\'"\n]+)[\'"]') + + +def _package(spec): + """the package a bare import specifier names: `@scope/pkg/sub` -> `@scope/pkg`, `pkg/sub` -> `pkg`""" + parts = spec.split('/') + return '/'.join(parts[:2]) if spec.startswith('@') else parts[0] + + +def relative_names(lines, own=frozenset()): + """the names a JS/TS file imports from the project itself: a relative path or one of its own workspace packages""" + out = set(); text = '\n'.join(lines or []) + for m in (_JS_IMPORT_ALL.finditer(text) if ("from '" in text or 'from "' in text) else ()): + if not (m.group(2).startswith('.') or _package(m.group(2)) in own): continue + for part in re.sub(r'[{}]', ',', m.group(1)).split(','): + part = re.sub(r'\s+', ' ', part).strip() + part = part[5:] if part.startswith('type ') else part + if part and part != '*': out.add(part.split(' as ')[-1].strip()) + return out + + +def imported_names(lines, own=frozenset()): + """the names a file binds by importing them from a PACKAGE: Python `from x import a, b as c` / `import a`, and a JS/TS + import from a bare specifier (a relative one is the project's own, which declares the name anyway)""" + out = set() + for t in lines or []: + st = t.split('#')[0].strip() + if st.startswith('from ') and ' import ' in st and not st.rstrip(';').endswith(("'", '"')): # Python from-import + if st.split()[1].startswith('.'): continue # the project's own + for part in st.split(' import ', 1)[1].strip('() ').split(','): + part = part.strip().strip('()') + if part and part != '*': out.add(part.split(' as ')[-1].strip()) + continue + if re.fullmatch(r'import\s+[\w.]+(\s+as\s+\w+)?(\s*,\s*[\w.]+(\s+as\s+\w+)?)*', st): # Python import + for part in st[len('import '):].split(','): + part = part.strip() + if part: out.add(part.split(' as ')[-1].strip().split('.')[0]) + continue + # JS / TS, over the whole text: an import's braces often span lines + text = '\n'.join(lines or []) + for m in (_JS_IMPORT_ALL.finditer(text) if ("from '" in text or 'from "' in text) else ()): + if m.group(2).startswith('.') or _package(m.group(2)) in own: continue + for part in re.sub(r'[{}]', ',', m.group(1)).split(','): + part = re.sub(r'\s+', ' ', part).strip() + part = part[5:] if part.startswith('type ') else part + if part and part != '*': out.add(part.split(' as ')[-1].strip()) + return out + + +def fillable(names, reader=None, site_file=lambda f: f): + """keep(row, reason) for unknown_sites: a site whose target may be the project's own code. A call through a VALUE + (a bare name that is a parameter or a local, a computed or reflective call, a value a library runs) may land + anywhere; a member call lands in the project only when some project declaration carries the name called. The rest, + a library's method on a receiver the engine could not type (`text.strip()`, `path.exists()`), is not linked by + reading the project: --library stages the library so the engine resolves it.""" + every, members = names + seen = {} + own = workspace_packages(getattr(reader, 'repo', None)) + def imported(f): + if f not in seen: + L = reader.lines(site_file(f)) if reader else None + # a runtime global, unless this file imports the project's own declaration of that name + seen[f] = imported_names(L, own) | (JS_GLOBALS - relative_names(L, own)) + return seen[f] + def keep(row, reason): + _sid, _c, kind, callee, _f, _l = row + nm = (callee or '').split('.')[-1] + on_receiver = kind in ax_links.MEMBER_KINDS or reason.startswith('untyped_receiver') or '.' in (callee or '') + # a bare call of a name the runtime provides, or the file imports from a package, is the platform's or the + # package's, whatever the project also declares under that name elsewhere + if not on_receiver and nm in imported(_f): return False + if nm in (members if on_receiver else every): return True + # no project declaration carries the name: only a call THROUGH A VALUE may still land in the project. A member + # called on a receiver the engine could not type (`s[:1].isupper()` is a SUBSCRIPT_CALL, `p.exists()` can be an + # UNKNOWN_CALLEE_CALL), or a library's decorator, is the library's + if reason.startswith('untyped_receiver'): return False + if reason.startswith('runs a value through '): return True # process launchers are already left out (ax_links) + if reason in ax_links.VALUE_REASONS or reason == 'escape_hatch': return True + # a bare name the project does not declare: a parameter or a local holding a function — unless the file imports + # it, which makes it a library's function (`from html import escape`) + return kind in BARE_VALUE_KINDS and '.' not in (callee or '') + return keep + + +def _leads(site, names): + """a member call's candidates are the declarations of its name; any other candidate is not a lead for it""" + if site['kind'] in ax_links.MEMBER_KINDS or str(site.get('reason', '')).startswith('untyped_receiver'): + nm = site['call'].split('.')[-1] + site['candidates'] = [c for c in site.get('candidates') or [] if c['target'].split('.')[-1] == nm] + return site + + +def open_sites(con, repo, reader, skips, every=False, cands=True): + """([site dict] of one graph, unresolved, library-only): every unresolved site that may land in the project, with + no link settling it and no skip covering it, the sites inside the most called callers first (a gap in a hub breaks + every chain through it). every=True keeps the library-only sites too.""" + t = _tables(con) + if 'unresolved_sites' not in t: return [], 0, 0, 0 + q = lambda sql, *a: con.execute(sql, a).fetchall() + fan = dict(q("SELECT s.id, COUNT(e.call_site_id) FROM symbols s JOIN call_edges e ON e.callee_method_id = s.method_id " + "WHERE s.id IN (SELECT DISTINCT caller_id FROM unresolved_sites) GROUP BY s.id")) + callers = [r[0] for r in q("SELECT DISTINCT caller_id FROM unresolved_sites")] + order = sorted(callers, key=lambda c: (-fan.get(c, 0), str(c))) + names = _project_names(con) + _all, n_all = ax_links.unknown_sites(q, callers, _site_file(con), limit=0, order=order, repo=repo) + sites, n_proj = ax_links.unknown_sites(q, callers, _site_file(con), limit=10 ** 9, order=order, repo=repo, + keep=fillable(names, reader, _site_file(con)), with_candidates=cands and not every) + def still_open(rows): + out = [] + for s in rows: + if s['linked']: continue + f, _, ln = s['at'].rpartition(':') + if skipped(skips, reader, f, int(ln or 0)): continue + out.append(_leads(s, names)) + return out + proj = still_open(sites) + # the listing may take every site (--all); the counts stay the project/library split + listing = still_open(ax_links.unknown_sites(q, callers, _site_file(con), limit=10 ** 9, order=order, repo=repo, + with_candidates=cands)[0]) if every else proj + return listing, n_all, n_all - n_proj, len(proj) + + +def worklist(repo, limit=25, every=False): + """(summary dict, [open site]) over every live graph of the repository; limit 0 counts only (no candidates)""" + cands = limit > 0 + # the links file may have changed since the graphs were last given it (edited, pulled, deleted): as before a query + try: ax_links.sync(repo) + except Exception: pass + reader = ax_links.Reader(repo); skips = read_skips(repo) + summ = dict(calls=0, project=0, boundary=0, asserted=0, unresolved=0, library=0, open=0, skipped=0, graphs=0) + sites = [] + for db, _rd, live in ax_links.graph_dbs(repo): + if not live: continue + try: con = sqlite3.connect(f"file:{db}?mode=ro", uri=True) + except sqlite3.Error: continue + try: + for k, v in graph_counts(con).items(): summ[k] += v + got, n_all, n_lib, n_open = open_sites(con, repo, reader, skips, every, cands) + summ['graphs'] += 1; summ['unresolved'] += n_all; summ['library'] += n_lib; summ['open'] += n_open + sites += got + except sqlite3.Error: pass + finally: con.close() + summ['skipped'] = sum(1 for (f, l) in skips if skipped(skips, reader, f, l)) + return summ, sites[:limit] + + +def mcp_surface(): + return os.environ.get('AXIOMCODE_SURFACE') == 'mcp' + + +def fill_verb(): + """how this surface starts a fill pass: the MCP tools name no flags (the server drops a clause naming one)""" + return 'unresolved(), then unresolved(decisions=...)' if mcp_surface() else '/axiomcode:fill (shell: axiomcode unresolved)' + + +def summary_line(s, verb=None): + """one line: what the graph resolved, and what is left for someone who reads the code""" + verb = verb or fill_verb() + if not s['graphs']: return '' + left = s['unresolved'] - s['library'] + tail = (f" — {s['open']} open: link them with {verb}" if s['open'] else ' — none open') + return (f"graph: {s['calls']} call sites · {s['project']} resolved into the project · {s['boundary']} into a library · " + f"{s['asserted']} asserted by a link · {s['unresolved']} unresolved: {left} may land in the project " + f"({s['skipped']} left open by a fill pass), {s['library']} a library's method on an untyped value{tail}") + + +def print_worklist(repo, limit, as_json, every=False): + s, sites = worklist(repo, limit, every) + if as_json: + print(json.dumps(dict(summary=s, sites=sites), indent=1)); return 0 + print(summary_line(s)) + if not sites: return 0 + print(f"next {len(sites)} open site(s)" + (' (library ones included)' if every else f" of {s['open']}") + ", the most called callers first:") + for x in sites: + code = ax_links.code_at(repo, x['at']) + print(f" {x['site']} {code[:100]}") + print(f" in {x['caller']} · calls `{x['call']}` · {x['reason']}") + cs = x.get('candidates') or [] + print(" candidates: " + ('; '.join(f"{c['target']} {c['at']} ({c['why']})" for c in cs[:4]) if cs else 'none in the graph')) + how = 'unresolved(decisions=""), which answers with the next page' if mcp_surface() else '`axiomcode link --batch -` (decisions on stdin)' + print("decide each from the code, one line per site: ` ` when the code makes it CERTAIN, ` not:` " + f"for a wrong candidate, ` ?` to leave it open; send them with {how}. A candidate is a lead: never link one for its rank.") + return 0 + + +# ── a batch of decisions ───────────────────────────────────────────────────────────────────────────────────────── +def parse_batch(text): + """[(site, target)] from ` ` lines (tab or spaces); comments and blanks skipped""" + out, bad = [], [] + for n, raw in enumerate((text or '').split('\n'), 1): + s = raw.strip() + if not s or s.startswith('#'): continue + p = s.split(None, 1) + if len(p) != 2: bad.append((n, s, 'expected ` `')); continue + out.append((p[0], p[1].strip())) + return out, bad + + +def run_batch(repo, text, as_json=False): + """apply a batch: skips are recorded, links and rejections validated one by one (ax_links.validate) and written + together, then applied once. -> exit code (0 when every decision was taken)""" + pairs, bad = parse_batch(text) + reader = ax_links.Reader(repo) + skips = read_skips(repo) + links, malformed = ax_links.read_links(repo) + res = [dict(line=n, site=s, target='', status='malformed', reason=why) for n, s, why in bad] + nskip = 0 + for site, target in pairs: + f, line, col = ax_links.site_arg(repo, site) + if f is None: + res.append(dict(site=site, target=target, status='malformed', reason='the site is written file:line[:col]')); continue + if target == '?': + L = reader.lines(f) + if not L or not (0 < line <= len(L)): + res.append(dict(site=site, target='?', status='rejected', reason='not a line of a file in this repository')); continue + skips[(f, line)] = ax_links.line_sha(L[line - 1]); nskip += 1 + res.append(dict(site=site, target='?', status='left open', reason='')); continue + ok, why, links = ax_links.validate(repo, links, f, line, col, target, reader) + if ok and target.startswith('not:'): + # the agent read the site and rejected a lead: unless it links a target too, nothing certain is left there + # this pass, so it is not asked again until its line changes + L = reader.lines(f); skips[(f, line)] = ax_links.line_sha(L[line - 1]); nskip += 1 + res.append(dict(site=site, target=target, status='linked' if ok and not target.startswith('not:') else ('rejected lead' if ok else 'refused'), reason=why)) + for r in res: + if r['status'] == 'linked': + f, line, _c = ax_links.site_arg(repo, r['site']); skips.pop((f, line), None); nskip += 1 + if nskip: write_skips(repo, skips, os.environ.get('AXIOMCODE_LINK_BY') or 'agent') + t0 = time.time() + if any(r['status'] in ('linked', 'rejected lead') for r in res): + ax_links.write_links(repo, links); ax_links._restore_bad(repo, malformed) + ax_links.apply_repo(repo) + ms = (time.time() - t0) * 1000 + s, _ = worklist(repo, 0) + if as_json: + print(json.dumps(dict(results=res, summary=s, apply_ms=round(ms)), indent=1)) + else: + cnt = {} + for r in res: cnt[r['status']] = cnt.get(r['status'], 0) + 1 + print(f"batch: {', '.join(f'{n} {k}' for k, n in sorted(cnt.items())) or 'nothing'} — applied in {ms:.0f} ms") + for r in res: + if r['status'] in ('refused', 'malformed', 'rejected'): print(f" {r['status']}: {r['site']} → {r['target']} — {r['reason']}") + print(summary_line(s)) + return 0 if all(r['status'] in ('linked', 'rejected lead', 'left open') for r in res) else 1 + + +# ── telling the agent, once per build ─────────────────────────────────────────────────────────────────────────── +def build_stamp(repo): + """what identifies the graphs a repository has now: each live graph's file and modification time""" + parts = [] + for db, _r, live in ax_links.graph_dbs(repo): + if not live: continue + try: st = os.stat(db); parts.append(f"{os.path.realpath(db)}@{int(st.st_mtime)}") + except OSError: pass + return '|'.join(parts) + + +def notice(repo, surface): + """the line that starts a fill pass, ONCE per build per surface ('hook', 'mcp'), and only when sites are open; + '' otherwise. A build the agent already heard about stays quiet whatever is left in it.""" + stamp = build_stamp(repo) + if not stamp: return '' + mark = os.path.join(repo, '.axiomcode', f'.fill-noted-{surface}') + try: + with open(mark, encoding='utf-8') as fh: + if fh.read().strip() == stamp: return '' + except OSError: pass + s, _ = worklist(repo, 0) + try: + with open(mark, 'w', encoding='utf-8') as fh: fh.write(stamp) + except OSError: pass + if not s['open']: return '' + how = ('call unresolved(), and settle each page with unresolved(decisions=...)' if surface == 'mcp' + else 'run /axiomcode:fill (it reads them in a subagent and links only what the code makes certain)') + return (f"graph: the engine left {s['open']} call site(s) unresolved that may land in this project's own code — " + f"answers stop there. To fill them: {how}. " + f"({s['library']} more are a library's method on an untyped value; those are not linked by reading.)") + + +def main(argv): + as_json = '--json' in argv; argv = [a for a in argv if a != '--json'] + limit = 25 + if '--limit' in argv: + i = argv.index('--limit') + try: limit = max(0, int(argv[i + 1])) + except (IndexError, ValueError): print("axiomcode unresolved: --limit takes a number", file=sys.stderr); return 2 + del argv[i:i + 2] + if '--notice' in argv: + i = argv.index('--notice'); surface = argv[i + 1] if i + 1 < len(argv) else 'hook'; del argv[i:i + 2] + repo, _ = ax_links.find_repo(argv) + line = notice(repo, surface) if os.path.isdir(os.path.join(repo, '.axiomcode')) else '' + if line: print(line) + return 0 + only = '--summary' in argv; argv = [a for a in argv if a != '--summary'] + every = '--all' in argv; argv = [a for a in argv if a != '--all'] + repo, _ = ax_links.find_repo(argv) + if not os.path.isdir(os.path.join(repo, '.axiomcode')): + print(f"axiomcode unresolved: no graph for {repo} — `axiomcode index` builds it", file=sys.stderr); return 2 + if only: + s, _ = worklist(repo, 0) + print(json.dumps(s) if as_json else summary_line(s)); return 0 + return print_worklist(repo, limit, as_json, every) + + +if __name__ == '__main__': + sys.exit(main(sys.argv[1:])) diff --git a/plugins/axiomcode/skills/axiomcode/scripts/ax_links.py b/plugins/axiomcode/skills/axiomcode/scripts/ax_links.py index 103edbba5..403c646a2 100644 --- a/plugins/axiomcode/skills/axiomcode/scripts/ax_links.py +++ b/plugins/axiomcode/skills/axiomcode/scripts/ax_links.py @@ -45,6 +45,35 @@ # the methods every language invokes a held callable or a reflected member through REFLECTIVE = {'invoke', 'Invoke', 'DynamicInvoke', 'InvokeMember', 'apply', 'call', 'accept', 'test', 'run', 'applyAsInt', 'applyAsLong', 'applyAsDouble', 'handle', 'execute', 'Execute', '__call__', 'emit', 'dispatch'} +# a library function named like a reflective one that runs a PROCESS or an event loop, not a value it is handed: +# `subprocess.run(cmd)`, `asyncio.run(main())`, `child_process.exec(..)`. Matched on the module the call is written on, +# after an import alias (`import subprocess as sp`) is read back to its module +PROCESS_MODULES = {'subprocess', 'asyncio', 'os', 'shutil', 'child_process', 'execa', 'uvicorn', 'trio', 'anyio'} +_JS_NS = re.compile(r'^\s*import\s+\*\s+as\s+(\w+)\s+from\s+[\'"]([^\'"]+)[\'"]') + + +def _aliases(lines): + """{alias: module} from `import a as b, c as d` (Python) and `import * as b from 'a'` (JS/TS)""" + out = {} + for t in lines or []: + st = t.strip() + if st.startswith('import ') and ' as ' in st and ' from ' not in st: + for part in st[len('import '):].split('#')[0].split(','): + m = re.fullmatch(r'\s*([\w.]+)\s+as\s+(\w+)\s*', part) + if m: out[m.group(2)] = m.group(1).split('.')[0] + continue + m = _JS_NS.match(t) + if m: out[m.group(1)] = m.group(2).split('/')[-1] + return out + + +def runs_a_process(callee, label, lines=None): + """True when a reflective-looking library call (`run`, `call`, `exec`) is a process or event-loop launcher""" + owner = (label or '').split(':')[-1].rsplit('.', 1)[0] or (callee or '').rsplit('.', 1)[0] + root = owner.split('.')[0] + return root in PROCESS_MODULES or _aliases(lines).get(root) in PROCESS_MODULES + + RANK = {'applied': 0, 'moved': 1, 'redundant': 2, 'changed': 3, 'stale': 3, 'rejected': 4, 'malformed': 5} # the library methods that run a callable or a member someone else chose: a site resolved to one of them is as unknown as an # unresolved one, and is listed with them (unknown_sites) @@ -1006,9 +1035,21 @@ def add(mid, why): return out -def unknown_sites(q, callers, site_file, limit=30, order=None, repo=None): +_LINES = {} +def _lines_of(repo, rel): + """a file's lines for the alias check, read once per file per process""" + k = (repo, rel) + if k not in _LINES: + try: + with open(os.path.join(repo, rel), encoding='utf-8', errors='replace') as fh: _LINES[k] = fh.read().split('\n') + except OSError: _LINES[k] = [] + return _LINES[k] + + +def unknown_sites(q, callers, site_file, limit=30, order=None, repo=None, keep=None, with_candidates=True): """the unresolved call sites inside these callables: where the answer stops being complete. Each with the call as - written, the engine's own reason, and the targets it was linked to (if any).""" + written, the engine's own reason, and the targets it was linked to (if any). `keep(row, reason)` narrows the rows + before any candidate is worked out (row = site id, caller, kind, callee, file, line); total counts the kept ones.""" callers = [c for c in dict.fromkeys(callers) if c] if not callers: return [], 0 tabs = {r[0] for r in q("SELECT name FROM sqlite_master WHERE type IN ('table','view')")} @@ -1022,7 +1063,9 @@ def unknown_sites(q, callers, site_file, limit=30, order=None, repo=None): # resolved it (to the library method), so it is no unresolved site, and what it runs is as unknown as one's for sid, c, k, n, f, l, lib in q(f"SELECT s.id, s.caller_id, s.kind, s.callee_name, s.file_path, s.start_line, e.callee_label FROM call_edges e " f"JOIN call_sites s ON s.id = e.call_site_id WHERE e.tier = 'boundary_lib' AND e.caller_id IN ({ph})", *ch): - if (n or '').split('.')[-1] in REFLECTIVE_LIB: rows.append((sid, c, k, n, f, l)); libcall[sid] = lib + if (n or '').split('.')[-1] in REFLECTIVE_LIB: + if runs_a_process(n, lib, _lines_of(repo, site_file(f)) if repo and f else None): continue + rows.append((sid, c, k, n, f, l)); libcall[sid] = lib # …and a typed front end's call through a holder of a FUNCTION TYPE: resolved to a signature with no body, so the # function the holder is given is what runs (axiomcode-path's value calls, FUNCTION_TYPE_KINDS there) for sid, c, k, n, f, l, qn in q(f"SELECT s.id, s.caller_id, s.kind, s.callee_name, s.file_path, s.start_line, m.qualified_name FROM call_edges e " @@ -1037,6 +1080,14 @@ def unknown_sites(q, callers, site_file, limit=30, order=None, repo=None): "(SELECT 1 FROM asserted_rejections r WHERE r.call_site_id = e.call_site_id AND r.callee_id = e.callee_method_id AND r.status IN ('applied','moved')) LIMIT 1", sid) if not left: rows.append((sid, c, k, n, f, l)) rows = list(dict.fromkeys(rows)) + if keep is not None: + why_all = {} + if 'ext_call_site_unresolved' in tabs: + ids_all = [r[0] for r in rows] + for i in range(0, len(ids_all), 500): + ch = ids_all[i:i + 500] + for sid, why in q(f"SELECT c0, c2 FROM ext_call_site_unresolved WHERE c0 IN ({','.join('?' * len(ch))})", *ch): why_all.setdefault(sid, why) + rows = [r for r in rows if keep(r, why_all.get(r[0]) or (f"runs a value through {libcall[r[0]]}" if r[0] in libcall else ''))] total = len(rows) rank = {c: i for i, c in enumerate(order or callers)} rows.sort(key=lambda r: (rank.get(r[1], len(rank)), str(r[4]), r[5] or 0)) @@ -1077,7 +1128,7 @@ def col_of(sid, f, callee): lc = str(libcall.get(sid, '')) why = reasons.get(sid) or ((f"calls a value typed by {lc}" if ' ' in lc else f"runs a value through {lc.split(':')[-1]}") if sid in libcall else 'unresolved') rf = site_file(f) if f else '?' - try: cands = candidates(qm, sid, caller, callee, kind, rf, ln, reasons.get(sid), rd) + try: cands = candidates(qm, sid, caller, callee, kind, rf, ln, reasons.get(sid), rd) if with_candidates else [] except Exception: cands = [] site = f"{rf}:{ln or 0}:{col_of(sid, rf, callee)}" out.append(dict(at=f"{rf}:{ln or 0}", site=site, call=callee or '', kind=kind, caller=disp[caller], candidates=cands, @@ -1222,7 +1273,59 @@ def removal_targets(repo, at_site, tgt): return hit +def validate(repo, links, f, line, col, target, reader, callee='', detail=False): + """one link (target `not:` rejects a lead) checked against the live graphs and merged into `links`, not written. + -> (ok, reason, links) — and (new row, verdict) as a fourth when detail. A link no graph would take is refused.""" + reject = target.startswith('not:') + if reject: target = target[4:] + fail = lambda why: (False, why, links) + ((None,) if detail else ()) + L = reader.lines(f) + if L is None or not (0 < line <= len(L)): return fail(f"{f}:{line} is not a line of a file in this repository") + new = dict(file=f, line=line, line_sha=line_sha(L[line - 1]), callee=callee, caller='', target=target, target_file='', + col=col, ncol=norm_col(L[line - 1], col) if col else None, + by=os.environ.get('AXIOMCODE_LINK_BY') or os.environ.get('USER') or 'agent', at=time.strftime('%Y-%m-%dT%H:%M:%S'), n=0) + verdicts = [] + for db, rd, live in graph_dbs(repo): + if not live: continue + con = sqlite3.connect(f"file:{db}?mode=ro", uri=True) + try: + g = Graph(con) + if reject: + ap = {(a, b) for a, b in g.q("SELECT call_site_id, callee_method_id FROM call_edges WHERE tier = ?", TIER)} + verdicts.append((resolve_not(g, rd, new, ap), g)) + else: verdicts.append((resolve(g, rd, new), g)) + except sqlite3.Error: con.close() + good = [(r, g) for r, g in verdicts if r['status'] in ('applied', 'redundant')] + if not good: + why = sorted(verdicts, key=lambda x: (x[0]['reason'].startswith('no call is written'), x[0]['reason'].startswith('the target is not'))) + for _r, g in verdicts: g.con.close() + return fail(why[0][0]['reason'] if why else 'no graph to check it against') + r, g = good[0] + new.update(callee=r.get('callee_written') or callee, caller=g.display(r['caller']) if r.get('caller') else '', + target=r['target_display'], target_file=r.get('target_file') or '', **({'not': True} if reject else {})) + new['target'], new['target_file'] = stable_name(g, r['callee_id'], r['target_display'], new['target_file']) + # the column the link resolved to is recorded even when none was given: it is what the link names from now on + if r.get('col') and not new.get('col'): new['col'] = r['col']; new['ncol'] = norm_col(L[line - 1], r['col']) + # re-linking the same site to the same DECLARATION replaces that row; the same name declared elsewhere (two arrows + # handed to one registry) is another link + dup = [l for l in links if l['file'] == f and l['line'] == line and l.get('col') == new.get('col') + and bool(l.get('not')) == bool(new.get('not')) and same_target(l, new, g, r['callee_id'])] + for _r, gg in verdicts: gg.con.close() + links = [l for l in links if l not in dup] + [new] + return (True, '', links) + (((new, r),) if detail else ()) + + def main(argv): + if '--batch' in argv: + i = argv.index('--batch'); src = argv[i + 1] if i + 1 < len(argv) else '-' + rest = argv[:i] + argv[i + 2:] + try: text = sys.stdin.read() if src == '-' else open(src, encoding='utf-8').read() + except OSError as e: print(f"axiomcode link --batch: {e}", file=sys.stderr); return 2 + import ax_fill + repo, _ = find_repo([a for a in rest if a != '--json']) + if not os.path.isdir(os.path.join(repo, '.axiomcode')): + print(f"axiomcode link: no graph for {repo}", file=sys.stderr); return 2 + return ax_fill.run_batch(repo, text, '--json' in rest) as_json = '--json' in argv argv = [a for a in argv if a != '--json'] remove = '--remove' in argv @@ -1257,42 +1360,13 @@ def main(argv): return 0 if gone else 1 if len(args) < 2: print(USAGE, file=sys.stderr); return 2 - target = args[1]; callee = args[2] if len(args) > 2 else '' - if target.startswith('not:'): reject, target = True, target[4:] - reader = Reader(repo); L = reader.lines(f) - if L is None or not (0 < line <= len(L)): - print(f"axiomcode link: rejected — {f}:{line} is not a line of a file in this repository", file=sys.stderr); return 1 - new = dict(file=f, line=line, line_sha=line_sha(L[line - 1]), callee=callee, caller='', target=target, target_file='', - col=col, ncol=norm_col(L[line - 1], col) if col else None, - by=os.environ.get('AXIOMCODE_LINK_BY') or os.environ.get('USER') or 'agent', at=time.strftime('%Y-%m-%dT%H:%M:%S'), n=0) - # validate against the live graphs first: a link no graph would take is refused, not written - verdicts = [] - for db, rd, live in graph_dbs(repo): - if not live: continue - con = sqlite3.connect(f"file:{db}?mode=ro", uri=True) - try: - g = Graph(con) - if reject: - ap = {(a, b) for a, b in g.q("SELECT call_site_id, callee_method_id FROM call_edges WHERE tier = ?", TIER)} - verdicts.append((resolve_not(g, rd, new, ap), g)) - else: verdicts.append((resolve(g, rd, new), g)) - except sqlite3.Error: pass - good = [(r, g) for r, g in verdicts if r['status'] in ('applied', 'redundant')] - if not good: - why = sorted(verdicts, key=lambda x: (x[0]['reason'].startswith('no call is written'), x[0]['reason'].startswith('the target is not'))) - print(f"axiomcode link: rejected — {why[0][0]['reason'] if why else 'no graph to check it against'}", file=sys.stderr); return 1 - r, g = good[0] - new.update(callee=r.get('callee_written') or callee, caller=g.display(r['caller']) if r.get('caller') else '', - target=r['target_display'], target_file=r.get('target_file') or '', **({'not': True} if reject else {})) - new['target'], new['target_file'] = stable_name(g, r['callee_id'], r['target_display'], new['target_file']) - # the column the link resolved to is recorded even when none was given: it is what the link names from now on - if r.get('col') and not new.get('col'): new['col'] = r['col']; new['ncol'] = norm_col(L[line - 1], r['col']) - # re-linking the same site to the same DECLARATION replaces that row; the same name declared elsewhere (two arrows - # handed to one registry) is another link - dup = [l for l in links if l['file'] == f and l['line'] == line and l.get('col') == new.get('col') - and bool(l.get('not')) == bool(new.get('not')) and same_target(l, new, g, r['callee_id'])] - g.con.close() - links = [l for l in links if l not in dup] + [new] + target = args[1] if not reject or args[1].startswith('not:') else 'not:' + args[1] + callee = args[2] if len(args) > 2 else '' + ok, why, links, extra = validate(repo, links, f, line, col, target, Reader(repo), callee, detail=True) + if not ok: + print(f"axiomcode link: rejected — {why}", file=sys.stderr); return 1 + new, r = extra + reject = bool(new.get('not')) t0 = time.time() write_links(repo, links); _restore_bad(repo, bad) res = apply_repo(repo) diff --git a/plugins/axiomcode/skills/axiomcode/scripts/axiomcode b/plugins/axiomcode/skills/axiomcode/scripts/axiomcode index 669ee227e..8b89b0426 100755 --- a/plugins/axiomcode/skills/axiomcode/scripts/axiomcode +++ b/plugins/axiomcode/skills/axiomcode/scripts/axiomcode @@ -15,6 +15,9 @@ # axiomcode link # record where an unresolved call lands, when the code makes it certain: impact, path and tests then walk it, # labelled [asserted]. Alone, lists every link and whether the graph took it; `link -` removes one. +# axiomcode unresolved +# the calls the graph could not resolve, over the whole graph: a summary, then the next open sites (the most +# called callers first) with their code, the reason and the candidates, to settle with link, many at once. # axiomcode index [] [--lang [,…]] [--src ] [--library [,…]] # build the graph (the first query builds it too). defaults to the current directory. # axiomcode report [] @@ -130,7 +133,7 @@ public_verbs(){ helptext | sed -n 's/^ axiomcode \([a-z][a-z-]*\).*/\1/p'; } # leading comment block. The verb documents itself once, where it is implemented. verbhelp(){ # a verb of the small surface is explained by its own entry in the help above: what it answers, no options - case "$1" in impact|path|tests|link|report) + case "$1" in impact|path|tests|link|unresolved|report) helptext | awk -v v="$1" '$0 ~ "^ axiomcode "v"( |$)" {on=1; print; next} on && /^ axiomcode / {exit} on && /^$/ {exit} on {print}' return 0 ;; esac @@ -267,6 +270,7 @@ case "$cmd" in changed) exec python3 ${Q:+"$Q" "$FR"} "$H/axiomcode-changed" ${ARGS[@]+"${ARGS[@]}"} ;; test-impact|tests) exec ${G[@]+"${G[@]}"} python3 ${Q:+"$Q" "$FR"} "$H/axiomcode-test-impact" ${ARGS[@]+"${ARGS[@]}"} ;; link) exec python3 "$H/axiomcode-link" ${ARGS[@]+"${ARGS[@]}"} ;; + unresolved) exec python3 "$H/axiomcode-unresolved" ${ARGS[@]+"${ARGS[@]}"} ;; report) exec python3 "$H/ax_assists.py" report ${ARGS[@]+"${ARGS[@]}"} ;; graph) exec python3 "$H/axiomcode-graph" ${ARGS[@]+"${ARGS[@]}"} ;; --verbs) verbs ;; # the dispatch table, internal verbs included; tests/surfaces.py audits it diff --git a/plugins/axiomcode/skills/axiomcode/scripts/axiomcode-build b/plugins/axiomcode/skills/axiomcode/scripts/axiomcode-build index 28ec84d31..cfaa8a308 100755 --- a/plugins/axiomcode/skills/axiomcode/scripts/axiomcode-build +++ b/plugins/axiomcode/skills/axiomcode/scripts/axiomcode-build @@ -603,6 +603,11 @@ warm_wait(){ [ -n "${WARM_PID:-}" ] || return 0 kill -0 "$WARM_PID" 2>/dev/null && echo "graph ready; precomputing impact facts in the background" return 0; } warm_wait +# WHAT THE ENGINE LEFT: one line over every graph — resolved into the project, into a library, asserted by a link, and the +# unresolved sites that may land in the project, which an agent settles by reading them (/axiomcode:fill, ax_fill.py). +# Counting only, no candidates; a failure here never fails the build. It comes before the warnings and the graph line, so +# the build still ends with `graph at `, which callers read as its last line. +python3 "$H/ax_fill.py" "$REPO" --summary 2>/dev/null || true if [ ${#FAILED[@]} -gt 0 ]; then for l in "${FAILED[@]}"; do if [ -f "$LANGDIR/$l/out/graph.sqlite" ]; then echo "⚠️ the $l graph did not build: $l questions are answered from its PREVIOUS graph, which predates this tree; see $REPO/.axiomcode/build.log" diff --git a/plugins/axiomcode/skills/axiomcode/scripts/axiomcode-unresolved b/plugins/axiomcode/skills/axiomcode/scripts/axiomcode-unresolved new file mode 100755 index 000000000..6ae6c0287 --- /dev/null +++ b/plugins/axiomcode/skills/axiomcode/scripts/axiomcode-unresolved @@ -0,0 +1,14 @@ +#!/usr/bin/env python3 +"""axiomcode unresolved [] [--limit N] [--summary] [--json] + +The call sites the graph could not resolve, over the whole graph: a one-line summary (call sites, resolved, asserted, +unresolved, open), then the next N open sites, the ones inside the most called callers first, each with its code, the +engine's reason and the graph's candidates. A site is open until a link settles it or a fill pass leaves it open (`?`). +Decide them with `axiomcode link --batch -`. See ax_fill.py. +""" +import os, sys +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import ax_fill + +if __name__ == '__main__': + sys.exit(ax_fill.main(sys.argv[1:])) diff --git a/plugins/axiomcode/skills/fill/SKILL.md b/plugins/axiomcode/skills/fill/SKILL.md new file mode 100644 index 000000000..860afc5ee --- /dev/null +++ b/plugins/axiomcode/skills/fill/SKILL.md @@ -0,0 +1,47 @@ +--- +name: fill +description: >- + Link the call sites the graph could not resolve, after a build. Use when an axiomcode note says the engine left + unresolved call sites ("To fill them: run /axiomcode:fill"), or when asked to fill, link or complete the call graph. + Reads each open site's code and records a link only where the code makes the target certain; everything else is + left open. Returns one line: how many sites were linked, rejected and left open. +context: fork +--- + +# fill + +The engine has done what it can by the end of a build. The sites it could not follow are calls through a value (a +handler table, a callback parameter, `getattr`, reflection) or a member called on a receiver it could not type. You +settle them by reading the code. Every link you make is trusted by every answer after it, so a wrong link is worse +than a missing one. + +## The loop + +1. Get the next page of open sites: `unresolved(limit=25)`, or `axiomcode unresolved --limit 25` from the shell. Each + site comes with its `file:line:col`, the line's code, the caller it sits in, the engine's reason and the graph's + candidates. +2. For each site, read enough code to know what runs there: the caller's body, where the value comes from (the + parameter's callers, the table's entries, the attribute's assignment). A candidate is a lead, not an answer. +3. Write one decision per site: + - ` ` when the code makes the target CERTAIN. The target is a declaration as the graph names it + (`Owner.method`, `function`) or its `file:line`. A site that reaches two targets (a table of two handlers) gets + two lines. + - ` not:` when a candidate is wrong (`d.update(x)` on a dict is not the project's `Cache.update`). + - ` ?` when you cannot be certain: the value comes from outside the repository, or it could be any of + many. This is the right answer for most library calls. +4. Send the page's decisions in one call: `unresolved(decisions="")`, which answers with what was taken + and the next page, or `axiomcode link --batch -` with the lines on stdin. A refused line says why (the target is + not a declaration, no call is written there); fix it or mark it `?`. +5. Repeat until no site is open or you have done 8 pages, whichever is first. + +## Rules + +- Never link by name alone, and never link a candidate because it is ranked first. +- Never link a call into a library or the standard library; those are not project code. +- A link adds an edge and never removes one. Do not use it to "correct" an edge the engine resolved. +- Do not edit source files. This pass only reads code and records decisions. + +## What to return + +One line, nothing else: `fill: linked N, rejected R, left open K; S still open` with the summary line the last batch +printed. The links are kept in `axiomcode-links.tsv` at the repository root, which the user may want to commit. diff --git a/skills/axiomcode/SKILL.md b/skills/axiomcode/SKILL.md index 65d012940..fb873eb6f 100644 --- a/skills/axiomcode/SKILL.md +++ b/skills/axiomcode/SKILL.md @@ -19,6 +19,7 @@ Search with grep as usual; the graph answers what grep cannot. Use the MCP tools | how does A reach B? | `path(start, end)` | `axiomcode path ` | | which tests do my edits need, and how do I run them? | `tests()` | `axiomcode tests` | | an answer lists an unresolved call I can see the target of | `link(site, target)` | `axiomcode link ` | +| the graph says sites are left unresolved after a build | `unresolved()`, then `unresolved(decisions)` — or `/axiomcode:fill` | `axiomcode unresolved` | | how does this work, start to finish? | `context(task, source=True)` | `axiomcode context "" --source` | Names are written as in the code: `Owner.method`, `function`, `Type`, or `file.py:123` for the declaration at that @@ -80,6 +81,16 @@ one. A link is refused when the call written there names a different declaration the line it was made on is edited, it is dropped and listed as stale, and the site is to resolve again. Never link a guess: an asserted edge is trusted by every answer after it. +## unresolved + +After a build, a note says how many call sites the engine left unresolved that may land in the project's own code +(a library's method on a receiver it could not type is counted, not listed: reading the project does not settle it). +`/axiomcode:fill` works through them in a subagent; without it, `unresolved(limit=25)` lists the next open sites, the +ones inside the most called callers first, each with its code, the engine's reason and the candidates, and +`unresolved(decisions="...")` takes one decision per line and answers with the next page: ` ` when the code makes it certain, ` not:` +for a wrong candidate, ` ?` to leave it open (not asked again until its line changes). Settled sites drop off the +list. The same rule as `link`: never link a guess. + ## context How something works, from a task in your own words: the files and callables the task touches and, for a diff --git a/tests/README.md b/tests/README.md index a0056b56e..ccf768816 100644 --- a/tests/README.md +++ b/tests/README.md @@ -40,6 +40,10 @@ One check needs no graph and is its own script: python3 tests/graph_verb.py `axiomcode graph` draws the existing graph and rebuilds a stale one with the flags it was indexed with; no rebuild path (refresh, repair, bare index) solves a language an explicit --lang left out (builds real graphs, needs the engine) + python3 tests/fill.py `unresolved` lists only the sites that may land in the project (a library's method + on an untyped value is counted, not listed), `link --batch` takes links, rejected + leads and `?` skips in one apply, and the build's notice is said once per build + (builds a small Python graph, needs the engine) python3 tests/repo_arg.py a repository argument that is not there (every verb, the MCP tools' repo=, --src) is an error naming it, with nothing built in the working directory; an absolute --src is used as given (indexes a small Python project, so it needs the engine) diff --git a/tests/fill.py b/tests/fill.py new file mode 100644 index 000000000..44cf0230c --- /dev/null +++ b/tests/fill.py @@ -0,0 +1,164 @@ +#!/usr/bin/env python3 +"""tests/fill.py — the whole graph's unresolved sites as a worklist, settled in batches, told to the agent once per build. + +One throwaway Python repository with four unresolved sites: `cb(i)`, a callback read out of a dict, which may land in +the project, and three a library's methods on untyped values (`opts.get(..)` twice, `text.strip()`). + + build the index prints the summary line: 1 site may land in the project, 3 are a library's; it still ends + with `graph at `, the line callers read last + worklist `unresolved` lists the callback site only, with the function handed in as its candidate; --all lists all + four (the control: the three are filtered, not missing); the counts are the same either way + batch `link --batch -` links the callback to `progress` and refuses a target that is not a declaration (exit 1, + with the reason); impact then walks the edge as [asserted]; the site drops off the list + skip `?` leaves a site open: it drops off the list until its line's text changes, then it is listed again + notice `--notice hook` speaks once per build: again only after the graph changes, never with nothing open + + python3 tests/fill.py [-v] +""" +import json, os, shutil, subprocess, sys, tempfile, time + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +SCRIPTS = os.path.join(ROOT, 'plugins', 'axiomcode', 'skills', 'axiomcode', 'scripts') +AX = os.path.join(SCRIPTS, 'axiomcode') +FILL = os.path.join(SCRIPTS, 'ax_fill.py') + +JOBS = '''from html import escape + + +def progress(i): + return i + + +def run(opts, items): + cb = opts.get("cb") + for i in items: + cb(i) + text = opts.get("title") + return text.strip() + + +def page(s): + return escape(s) + + +def main(): + run({"cb": progress, "title": " x "}, [1, 2]) + page("") +''' +CB_LINE = 11 +VERBOSE = '-v' in sys.argv + + +def sh(cwd, *cmd, stdin=None): + r = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True, input=stdin) + if VERBOSE: print(f"$ {' '.join(cmd)}\n{r.stdout}{r.stderr}") + return r + + +def summary(repo): + return json.loads(sh(repo, 'python3', FILL, repo, '--summary', '--json').stdout) + + +def listing(repo, *flags): + return json.loads(sh(repo, AX, 'unresolved', '--json', '--limit', '50', *flags, repo).stdout)['sites'] + + +def main(): + bad = []; checks = 0 + def check(ok, what): + nonlocal checks + checks += 1 + if not ok: bad.append(what) + if VERBOSE: print(('ok ' if ok else 'FAIL ') + what) + + # no graph: what counts as a library's call, both directions + sys.path.insert(0, SCRIPTS) + import ax_links, ax_fill + rp = ax_links.runs_a_process + check(not rp('m.invoke', 'external:java.lang.reflect.Method.invoke') and not rp('fn.apply', 'builtin:Function.apply') + and not rp('t.run', 'external:Thread.run'), 'library: a call that runs a value it is handed stays a site (control)') + check(rp('run', 'external:subprocess.run') and rp('run', 'external:_sp.run', [' import platform as _p, subprocess as _sp']) + and rp('cp.exec', 'external:cp.exec', ["import * as cp from 'child_process'"]), + 'library: a process launcher is not one, through an alias too') + names = ax_fill.imported_names(['from html import escape', 'import os.path as osp', "import { z } from 'zod'", + "import { local } from './mine'"]) + check({'escape', 'osp', 'z'} <= names and 'local' not in names, f'library: imported names, a relative import excluded (got {sorted(names)})') + multi = ax_fill.imported_names(['import {', ' describe,', ' expectTypeOf,', '} from "vitest";', "import { b } from '@acme/core'", + 'import os'], {'@acme/core'}) + check(multi == {'describe', 'expectTypeOf', 'os'}, f'library: a multi-line import is read; a workspace package is the project (got {sorted(multi)})') + rel = ax_fill.relative_names(["import { assert } from '../utils'", "import { z } from 'zod'"]) + check(rel == {'assert'}, f'library: a relative import of a global-named function is the project\'s (got {sorted(rel)})') + + repo = tempfile.mkdtemp(prefix='ax-fill-') + try: + os.makedirs(os.path.join(repo, 'app')) + open(os.path.join(repo, 'app', '__init__.py'), 'w').close() + open(os.path.join(repo, 'app', 'jobs.py'), 'w').write(JOBS) + sh(repo, 'git', 'init', '-q'); sh(repo, 'git', 'add', '-A') + sh(repo, 'git', '-c', 'user.email=t@t', '-c', 'user.name=t', 'commit', '-qm', 'init') + b = sh(repo, AX, 'index', repo) + check(b.returncode == 0 and os.path.isfile(os.path.join(repo, '.axiomcode', 'out', 'graph.sqlite')), 'build: the graph is built') + lines = [l for l in b.stdout.split('\n') if l.strip()] + line = next((l for l in lines if l.startswith('graph: ')), '') + check('1 may land in the project' in line and "3 a library's method" in line, + f'build: the index prints the summary line (got {line[:160]!r})') + check(bool(lines) and lines[-1].startswith('graph at '), + f'build: the index still ends with the graph line (got {(lines or [""])[-1][:160]!r})') + + s = summary(repo) + check((s['unresolved'], s['library'], s['open']) == (4, 3, 1), f"worklist: 4 unresolved, 3 library, 1 open (got {s})") + sites = listing(repo) + cb = [x for x in sites if x['call'] == 'cb'] + check(len(sites) == 1 and len(cb) == 1 and cb[0]['at'] == f'app/jobs.py:{CB_LINE}', f"worklist: only the callback site is listed (got {[x['site'] for x in sites]})") + check(bool(cb) and any(c['target'] == 'progress' for c in cb[0]['candidates']), 'worklist: the function handed in is its candidate') + every = listing(repo, '--all') + check(len(every) == 4 and {x['call'] for x in every} == {'cb', 'get', 'strip'}, f"worklist --all: the control lists all four (got {[x['call'] for x in every]})") + check(summary(repo)['open'] == 1, 'worklist --all: the counts do not change') + site = cb[0]['site'] if cb else f'app/jobs.py:{CB_LINE}' + + r = sh(repo, AX, 'link', '--batch', '-', repo, stdin=f"{site} progress\n{site} no_such_function_here\n") + check(r.returncode == 1 and 'refused' in r.stdout and 'not a declaration' in r.stdout, f'batch: a bad target is refused with its reason, exit 1 (rc {r.returncode})') + check('1 linked' in r.stdout, 'batch: the good line is linked anyway') + s = summary(repo) + check((s['asserted'], s['open']) == (1, 0), f"batch: 1 asserted, nothing open (got {s})") + imp = sh(repo, AX, 'impact', 'progress', repo) + check('[asserted]' in imp.stdout and f'app/jobs.py:{CB_LINE}' in imp.stdout, 'batch: impact walks the asserted edge') + links = open(os.path.join(repo, 'axiomcode-links.tsv')).read() + check('no_such_function_here' not in links and '\tprogress\t' in links, 'batch: only the validated link is written') + + sh(repo, AX, 'link', f'app/jobs.py:{CB_LINE}', '-', repo) + check(summary(repo)['open'] == 1, 'skip: removing the link opens the site again') + r = sh(repo, AX, 'link', '--batch', '-', repo, stdin=f"{site} ?\n") + s = summary(repo) + check(r.returncode == 0 and (s['open'], s['skipped']) == (0, 1), f"skip: `?` leaves it open and off the list (got {s})") + p = os.path.join(repo, 'app', 'jobs.py') + L = open(p).read().split('\n'); L[CB_LINE - 1] = L[CB_LINE - 1] + ' # now reads the callback twice' + open(p, 'w').write('\n'.join(L)) + check(summary(repo)['open'] == 1, 'skip: an edit to the skipped line lists it again') + open(p, 'w').write(JOBS) + check(summary(repo)['open'] == 0, 'skip: restoring the line text skips it again (the skip is keyed by the text)') + os.remove(os.path.join(repo, '.axiomcode', 'fill-skipped.tsv')) + check(summary(repo)['open'] == 1, 'skip: the skips are derived; deleting them only asks again') + + n1 = sh(repo, 'python3', FILL, repo, '--notice', 'hook').stdout.strip() + n2 = sh(repo, 'python3', FILL, repo, '--notice', 'hook').stdout.strip() + check(n1.startswith('graph: the engine left 1 call site') and '/axiomcode:fill' in n1, f'notice: the first prompt after the build hears it (got {n1[:120]!r})') + check(n2 == '', 'notice: the second does not') + m = sh(repo, 'python3', FILL, repo, '--notice', 'mcp').stdout.strip() + check('unresolved()' in m and 'unresolved(decisions' in m and '/axiomcode:fill' not in m, 'notice: the MCP surface names its tools, not the slash command') + db = os.path.join(repo, '.axiomcode', 'out', 'graph.sqlite') + t = time.time() + 5; os.utime(os.path.realpath(db), (t, t)) + check(sh(repo, 'python3', FILL, repo, '--notice', 'hook').stdout.strip() != '', 'notice: a new build is heard about again') + sh(repo, AX, 'link', '--batch', '-', repo, stdin=f"{site} progress\n") + t += 5; os.utime(os.path.realpath(db), (t, t)) + check(sh(repo, 'python3', FILL, repo, '--notice', 'hook').stdout.strip() == '', 'notice: silent when nothing is open') + finally: + shutil.rmtree(repo, ignore_errors=True) + + for b_ in bad: print('FAIL', b_) + print(f"{checks - len(bad)} of {checks} check(s) passed") + return 1 if bad or checks == 0 else 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tests/front_door.py b/tests/front_door.py index efb5310b7..ac0f6bc5b 100644 --- a/tests/front_door.py +++ b/tests/front_door.py @@ -12,7 +12,7 @@ path answer with numbered places and a fenced code block; after an edit, impact with no name starts with `your edits:`, and tests lists the test with its code and ends with a `run:` line. A verb off the surface is refused with the supported list. - b. the MCP server lists exactly context, impact, path, tests and link, each with at most two parameters, and a call to one + b. the MCP server lists exactly context, impact, path, tests, link and unresolved, each with at most two parameters, and a call to one answers in the same shape. c. CONTROLS: the dispatcher run directly, bin/axiomcode with --json, and AXIOMCODE_RAW=1 give the old answer — no fenced block — for the same question. @@ -130,7 +130,7 @@ def main(): # ── b. the MCP server ────────────────────────────────────────────────────────────────────────────────────── got = mcp(repo, [('path', {'start': 'total', 'end': 'vat_rate'}), ('impact', {'name': 'vat_rate'})]) tools = {t['name']: list((t.get('inputSchema') or {}).get('properties', {})) for t in got.get(2, {}).get('tools', [])} - check('MCP tools/list is exactly context, impact, path, tests and link (search is grep\'s)', set(tools) == {'context', 'impact', 'path', 'tests', 'link'}, tools) + check('MCP tools/list is exactly context, impact, path, tests, link and unresolved (search is grep\'s)', set(tools) == {'context', 'impact', 'path', 'tests', 'link', 'unresolved'}, tools) check('MCP: every tool takes at most two parameters', bool(tools) and all(len(p) <= 2 for p in tools.values()), tools) text = lambda i: ''.join(c.get('text', '') for c in got.get(i, {}).get('content', [])) check('MCP path answers as numbered places with their code', places(text(3)), text(3)[:600]) diff --git a/tests/hosts.py b/tests/hosts.py index 2be577ae7..afba8f678 100644 --- a/tests/hosts.py +++ b/tests/hosts.py @@ -127,14 +127,14 @@ def said_cursor(out, event): sys.exit(1) lib = os.path.join(repo, 'lib.py') - # UserPromptSubmit with a graph: changes.py and orient.py answer in Cursor's shape or not at all. - for hook in ('changes.py', 'orient.py'): + # UserPromptSubmit with a graph: changes.py, orient.py and fill.py answer in Cursor's shape or not at all. + for hook in ('changes.py', 'orient.py', 'fill.py'): rc2, out2 = fire(hook, cursor('beforeSubmitPrompt', None, {}, repo, 'p1', prompt='what calls greet'), cursor=True) said = said_cursor(out2, 'beforeSubmitPrompt') check(f'{hook} on beforeSubmitPrompt: exit 0 and Cursor-shaped', rc2 == 0 and said is not None, out2[:160]) - for hook in ('changes.py', 'orient.py'): + for hook in ('changes.py', 'orient.py', 'fill.py'): rc3, out3 = fire(hook, gemini('BeforeAgent', None, {}, repo, 'p3', prompt='what calls greet')) said = said_gemini(out3, 'BeforeAgent') check(f'{hook} on BeforeAgent: exit 0 and JSON only', rc3 == 0 and said is not None, out3[:160]) diff --git a/tests/mcp.py b/tests/mcp.py index 1b4311dd6..e5246d85f 100644 --- a/tests/mcp.py +++ b/tests/mcp.py @@ -32,7 +32,8 @@ # THE SMALL SURFACE: four questions, each with at most two parameters and no options. The front-door answer is capped # at ten places with the rest counted, so no tool is paged. context is the one narrative verb: a task in words, # answered as the verb's own flow rather than as places. -TOOLS = {'context': ['task', 'source'], 'impact': ['name'], 'path': ['start', 'end'], 'tests': [], 'link': ['site', 'target']} +TOOLS = {'context': ['task', 'source'], 'impact': ['name'], 'path': ['start', 'end'], 'tests': [], 'link': ['site', 'target'], + 'unresolved': ['limit', 'decisions']} def exchange(cmd, cwd, env=None, workdir=None): diff --git a/tests/mcp_docs.py b/tests/mcp_docs.py index 42a40d23d..6884dab3b 100644 --- a/tests/mcp_docs.py +++ b/tests/mcp_docs.py @@ -26,7 +26,7 @@ [os.path.join(ROOT, 'plugins', 'axiomcode', 'AGENTS.md')] + \ sorted(glob.glob(os.path.join(ROOT, 'plugins', 'axiomcode', 'rules', '*.mdc'))) -VERB = r'(context|impact|link|path|tests)' +VERB = r'(context|impact|link|path|tests|unresolved)' # a tool named: a call `impact(`, the Claude Code name mcp__plugin_axiomcode_axiomcode__impact, MCP `impact`, or a command # in backticks (`axiomcode impact x`); `path:line: …` is an answer's shape, not the tool MENTION = re.compile(r'`(?:axiomcode )?' + VERB + r'(?:[ \t][^`\n]*)?`|\bmcp__plugin_axiomcode_axiomcode__' + VERB + r'\b' @@ -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'}: + if set(tools) != {'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 09899d2b3..76f9ece01 100644 --- a/tests/surfaces.py +++ b/tests/surfaces.py @@ -29,7 +29,7 @@ MCP = os.path.join(PLUG, 'mcp', 'server.py') CLI = os.path.join(ROOT, 'bin', 'axiomcode') # the command an install puts on $PATH -PUBLIC = ['index', 'impact', 'path', 'tests', 'context', 'link', 'report', 'graph'] +PUBLIC = ['index', 'impact', 'path', 'tests', 'context', 'link', 'unresolved', 'report', 'graph'] 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'}