From 9c82af5b64ab7843687ebfa47c633dff353601b3 Mon Sep 17 00:00:00 2001 From: Swapnil <78632212+swapnilpaliwal-sd@users.noreply.github.com> Date: Wed, 18 Nov 2026 15:05:18 -0800 Subject: [PATCH 1/9] python: a closure cell rebound through nonlocal from a nested scope is not single-write (#381) symtable counts a name's binding sites per scope, so `fn = first` in the enclosing function and `nonlocal fn; fn = second` in a nested one are two rows, the cell's own saying 1. Every single-write guard read that row, so `swap(); fn()` came out known_edge -> first, a function that cannot run there, and `second` was the target of no edge. binding_rebinding now adds to a cell's count each ASSIGNED NONLOCAL binding whose LEGB walk lands on it (binding_nonlocal_write). The raw per-row count is kept as binding_rebinding_raw for the walk itself, which binding_rebinding is derived from. The site is now a declared unknown instead of a wrong committed target. A `nonlocal` that only reads the cell, and a nested local of the same name, keep their single-write answers (both are controls in the new case). Case 44-nonlocal-rebind. No other golden moved. --- graph/python/engine/projections/bindings.dl | 17 +++++- .../engine/resolution/name-resolution.dl | 27 ++++++++- graph/python/souffle/decls_all.dl | 3 + .../cases/44-nonlocal-rebind/src/main.py | 56 +++++++++++++++++++ .../python/expected/44-nonlocal-rebind.edges | 16 ++++++ .../expected/44-nonlocal-rebind.entries | 1 + .../expected/44-nonlocal-rebind.framework | 5 ++ .../python/expected/44-nonlocal-rebind.tiers | 24 ++++++++ 8 files changed, 144 insertions(+), 5 deletions(-) create mode 100644 graph/test/python/cases/44-nonlocal-rebind/src/main.py create mode 100644 graph/test/python/expected/44-nonlocal-rebind.edges create mode 100644 graph/test/python/expected/44-nonlocal-rebind.entries create mode 100644 graph/test/python/expected/44-nonlocal-rebind.framework create mode 100644 graph/test/python/expected/44-nonlocal-rebind.tiers diff --git a/graph/python/engine/projections/bindings.dl b/graph/python/engine/projections/bindings.dl index baa19e72c..1d64485bb 100644 --- a/graph/python/engine/projections/bindings.dl +++ b/graph/python/engine/projections/bindings.dl @@ -50,9 +50,20 @@ binding_is_namespace("lib", h) :- lib_py_binding(_, _, _, _, _, _, _, _, _, _, _ // bindingCount is the number of DISTINCT binding sites for this name in this scope. // == 1 is the precondition for treating a name as single-valued (the alias case // `_Aliased = Base`); > 1 means the name is rebound and a single-value inference is -// unsound. Consumed by resolution/name-resolution.dl. -binding_rebinding("client", n, first, last, h) :- py_binding(_, _, _, _, _, _, _, _, _, _, _, _, _, _, _, n, first, last, _, _, _, _, _, _, _, _, _, _, h). -binding_rebinding("lib", n, first, last, h) :- lib_py_binding(_, _, _, _, _, _, _, _, _, _, _, _, _, _, _, n, first, last, _, _, _, _, _, _, _, _, _, _, h). +// unsound. +// This is the RAW per-row count. It cannot see a write made from a NESTED scope through +// `nonlocal`: that write is a separate NONLOCAL row with its own count, so the enclosing +// cell's row still says 1. resolution/name-resolution.dl derives binding_rebinding from +// this and adds those writes; every single-write guard reads binding_rebinding. Only the +// LEGB walk reads the raw count, because it is what binding_rebinding is derived from. +binding_rebinding_raw("client", n, first, last, h) :- py_binding(_, _, _, _, _, _, _, _, _, _, _, _, _, _, _, n, first, last, _, _, _, _, _, _, _, _, _, _, h). +binding_rebinding_raw("lib", n, first, last, h) :- lib_py_binding(_, _, _, _, _, _, _, _, _, _, _, _, _, _, _, n, first, last, _, _, _, _, _, _, _, _, _, _, h). + +// ── binding_is_assigned(Prov, BindingHash) ─────────────────────────────────── +// Symbol.is_assigned(): the name is a store target in this scope. Separates a +// `nonlocal fn` that rebinds the enclosing cell from one that only reads it. +binding_is_assigned("client", h) :- py_binding(_, _, _, _, _, _, _, _, _, _, "true", _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, h). +binding_is_assigned("lib", h) :- lib_py_binding(_, _, _, _, _, _, _, _, _, _, "true", _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, h). // ── binding_annotation(Prov, DeclaredTypeName, DeclaredBaseType, PotentialQName, BindingHash) ── // "" on 68.2% of parameters, which is exactly why declared-type receiver typing — diff --git a/graph/python/engine/resolution/name-resolution.dl b/graph/python/engine/resolution/name-resolution.dl index b9345eb12..7efac4e75 100644 --- a/graph/python/engine/resolution/name-resolution.dl +++ b/graph/python/engine/resolution/name-resolution.dl @@ -438,7 +438,7 @@ binding_lookup(p, b, b2) :- binding_owner(p, mod, _, b), module_init(p, _, modScope, mod), binding_decl(p, n, modScope, _, _, b2), b2 != b, - binding_rebinding(p, cnt, _, _, b2), cnt != "0". + binding_rebinding_raw(p, cnt, _, _, b2), cnt != "0". // (c) FREE / NONLOCAL — nearest enclosing scope that binds the name. Candidate set // first, then the max-depth filter in the next stratum. binding_free_candidate(p, b, b2, d) :- @@ -446,7 +446,7 @@ binding_free_candidate(p, b, b2, d) :- binding_decl(p, n, s, _, _, b), scope_ancestor(p, s, anc), binding_decl(p, n, anc, _, _, b2), - binding_rebinding(p, cnt, _, _, b2), cnt != "0", + binding_rebinding_raw(p, cnt, _, _, b2), cnt != "0", scope_depth(p, dstr, _, anc), d = to_number(dstr). binding_free_nearest_depth(p, b, dmax) :- @@ -456,6 +456,29 @@ binding_lookup(p, b, b2) :- binding_free_nearest_depth(p, b, dmax), binding_free_candidate(p, b, b2, dmax). +// ── binding_nonlocal_write / binding_rebinding: writes from a nested scope ── +// symtable counts a name's binding sites per scope, so a cell rebound from a nested +// function through `nonlocal` has two rows, each with its own count: the cell's own +// (1, `fn = first`) and the nested NONLOCAL row (`fn = second`). Read alone, the cell's +// row says the name is written once, and every single-write guard then commits to the +// first write. #381: `fn = first; def swap(): nonlocal fn; fn = second; swap(); fn()` +// came out known_edge -> first, a function that cannot run there, and `second` was the +// target of no edge. +// A NONLOCAL row that is ASSIGNED is a write to the cell its LEGB walk lands on. One that +// only reads (`nonlocal fn` and no store) is not, and leaves the count alone. +binding_nonlocal_write(p, cell, nb) :- + binding_decl(p, _, _, "NONLOCAL", _, nb), + binding_is_assigned(p, nb), + binding_lookup(p, nb, cell), cell != nb. +binding_rebinding(p, n, first, last, b) :- + binding_rebinding_raw(p, n, first, last, b), + !binding_nonlocal_write(p, b, _). +binding_rebinding(p, total, first, last, b) :- + binding_rebinding_raw(p, n, first, last, b), + binding_nonlocal_write(p, b, _), + k = count : { binding_nonlocal_write(p, b, _) }, + total = to_string(to_number(n) + k). + // ── binding_lookup_unresolved(Prov, ReferenceBinding, Name, BindingKind) ───── // A reference-side binding whose LEGB walk found no declaration. THE HONEST FRONTIER: // a builtin (`super`, `len`, `object`), a name from `from x import *`, or a genuine diff --git a/graph/python/souffle/decls_all.dl b/graph/python/souffle/decls_all.dl index db011f111..b216cc982 100644 --- a/graph/python/souffle/decls_all.dl +++ b/graph/python/souffle/decls_all.dl @@ -6,7 +6,10 @@ .decl binding_decl(c0:symbol,c1:symbol,c2:symbol,c3:symbol,c4:symbol,c5:symbol) .decl binding_predicates(c0:symbol,c1:symbol,c2:symbol,c3:symbol,c4:symbol,c5:symbol,c6:symbol) .decl binding_is_namespace(c0:symbol,c1:symbol) +.decl binding_rebinding_raw(c0:symbol,c1:symbol,c2:symbol,c3:symbol,c4:symbol) .decl binding_rebinding(c0:symbol,c1:symbol,c2:symbol,c3:symbol,c4:symbol) +.decl binding_is_assigned(c0:symbol,c1:symbol) +.decl binding_nonlocal_write(c0:symbol,c1:symbol,c2:symbol) .decl binding_annotation(c0:symbol,c1:symbol,c2:symbol,c3:symbol,c4:symbol) .decl binding_declared_ref(c0:symbol,c1:symbol,c2:symbol) .decl binding_declared_nominal(c0:symbol,c1:symbol,c2:symbol) diff --git a/graph/test/python/cases/44-nonlocal-rebind/src/main.py b/graph/test/python/cases/44-nonlocal-rebind/src/main.py new file mode 100644 index 000000000..69cd26958 --- /dev/null +++ b/graph/test/python/cases/44-nonlocal-rebind/src/main.py @@ -0,0 +1,56 @@ +# A closure cell rebound from a nested scope through `nonlocal` is written twice, so the +# call through it must not commit to the first write alone (#381). + + +def first() -> str: + return "first" + + +def second() -> str: + return "second" + + +def nonlocal_rebind() -> str: + fn = first + + def swap() -> None: + nonlocal fn + fn = second + + swap() + return fn() + + +def nonlocal_read_only() -> str: + # A nested scope that only READS the cell through `nonlocal` is not a write; the call + # still has exactly one value and stays a committed edge. + fn = first + + def peek() -> str: + nonlocal fn + return fn.__name__ + + peek() + return fn() + + +def unrelated_nested_name() -> str: + # A nested scope that assigns its OWN local of the same name does not touch the cell. + fn = first + + def shadow() -> None: + fn = second + fn() + + shadow() + return fn() + + +def main() -> None: + nonlocal_rebind() + nonlocal_read_only() + unrelated_nested_name() + + +if __name__ == "__main__": + main() diff --git a/graph/test/python/expected/44-nonlocal-rebind.edges b/graph/test/python/expected/44-nonlocal-rebind.edges new file mode 100644 index 000000000..f817f75fa --- /dev/null +++ b/graph/test/python/expected/44-nonlocal-rebind.edges @@ -0,0 +1,16 @@ +ambiguous_unknown SIMPLE_CALL main.nonlocal_rebind -> - +callback_registered METHOD_REFERENCE main.nonlocal_read_only -> main.first +callback_registered METHOD_REFERENCE main.nonlocal_rebind -> main.first +callback_registered METHOD_REFERENCE main.nonlocal_rebind..swap -> main.second +callback_registered METHOD_REFERENCE main.unrelated_nested_name -> main.first +callback_registered METHOD_REFERENCE main.unrelated_nested_name..shadow -> main.second +known_edge SIMPLE_CALL main. -> main.main +known_edge SIMPLE_CALL main.main -> main.nonlocal_read_only +known_edge SIMPLE_CALL main.main -> main.nonlocal_rebind +known_edge SIMPLE_CALL main.main -> main.unrelated_nested_name +known_edge SIMPLE_CALL main.nonlocal_read_only -> main.first +known_edge SIMPLE_CALL main.nonlocal_read_only -> main.nonlocal_read_only..peek +known_edge SIMPLE_CALL main.nonlocal_rebind -> main.nonlocal_rebind..swap +known_edge SIMPLE_CALL main.unrelated_nested_name -> main.first +known_edge SIMPLE_CALL main.unrelated_nested_name -> main.unrelated_nested_name..shadow +known_edge SIMPLE_CALL main.unrelated_nested_name..shadow -> main.second diff --git a/graph/test/python/expected/44-nonlocal-rebind.entries b/graph/test/python/expected/44-nonlocal-rebind.entries new file mode 100644 index 000000000..276e39fa5 --- /dev/null +++ b/graph/test/python/expected/44-nonlocal-rebind.entries @@ -0,0 +1 @@ +── entry_point (0) ── diff --git a/graph/test/python/expected/44-nonlocal-rebind.framework b/graph/test/python/expected/44-nonlocal-rebind.framework new file mode 100644 index 000000000..b9cbca067 --- /dev/null +++ b/graph/test/python/expected/44-nonlocal-rebind.framework @@ -0,0 +1,5 @@ +── framework_edge (0) ── +── framework_unjoined (0) ── +── remote_edge (0) ── +── remote_unserved (0) ── +── remote_unsent (0) ── diff --git a/graph/test/python/expected/44-nonlocal-rebind.tiers b/graph/test/python/expected/44-nonlocal-rebind.tiers new file mode 100644 index 000000000..8356c96cc --- /dev/null +++ b/graph/test/python/expected/44-nonlocal-rebind.tiers @@ -0,0 +1,24 @@ +distinct call sites emitted: 16 + +--- by tier: edge ROWS, and the distinct SITES they cover --- + 1 rows 1 sites ambiguous_unknown + 5 rows 5 sites callback_registered + 10 rows 10 sites known_edge + +--- edge rows by call kind --- + 5 METHOD_REFERENCE + 11 SIMPLE_CALL + +--- unresolved reasons --- + 1 no_rule + +--- the engine's own conservation ledger --- + 11 _total_sites + 1 ambiguous_unknown + 10 known_edge + +--- reconciling rows against the conserved site count --- + edge rows 16 + minus extra rows from multi-target sites 0 + = tier/site pairs 16 + engine's conserved site total 11 From 991080f654249ce0ad137b2632a651c979dafe68 Mon Sep 17 00:00:00 2001 From: Swapnil <78632212+swapnilpaliwal-sd@users.noreply.github.com> Date: Wed, 18 Nov 2026 15:05:18 -0800 Subject: [PATCH 2/9] plugin: test-impact --files names the files that follow it, and is not itself a file (#2022) `test-impact --files a.py b.py` handed `--files` on to `changed`, which took it as one more named path; it is not source, so it was listed as a changed file outside every indexed language and searched for by name in the tests. `--files` is now dropped with the other test-impact flags, so the named files are read as they are for `test-impact a.py b.py`. tests/test_command.py checks what reaches `changed`. --- .../axiomcode/scripts/axiomcode-test-impact | 6 ++++-- tests/test_command.py | 15 +++++++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/plugins/axiomcode/skills/axiomcode/scripts/axiomcode-test-impact b/plugins/axiomcode/skills/axiomcode/scripts/axiomcode-test-impact index 6f9de3ff0..085db63ad 100755 --- a/plugins/axiomcode/skills/axiomcode/scripts/axiomcode-test-impact +++ b/plugins/axiomcode/skills/axiomcode/scripts/axiomcode-test-impact @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""axiomcode test-impact [] […] [--range .. | --staged] [--in ] [--limit N] [--json] [--why] [--no-refresh] +"""axiomcode test-impact [] [[--files] …] [--range .. | --staged] [--in ] [--limit N] [--json] [--why] [--no-refresh] --no-refresh (MCP refresh=false; AXIOMCODE_NO_REFRESH=1 for a whole shell) is a read-only query: it answers from the graph as it is and never starts a rebuild; rows in files edited since are still marked. Without it, a query on a graph @@ -1873,7 +1873,9 @@ def main(argv): limit = 40 if '--limit' in argv: i = argv.index('--limit'); limit = int(argv[i + 1]) - passthru = [a for a in argv if a not in ('--json', '--why')] + # --files is a spelling of the named-file list, not a file: `test-impact --files a b` passed it on to `changed`, + # which read it as one more named file (#1832) + passthru = [a for a in argv if a not in ('--json', '--why', '--files')] if '--limit' in passthru: i = passthru.index('--limit'); del passthru[i:i + 2] if '-h' in argv or '--help' in argv: diff --git a/tests/test_command.py b/tests/test_command.py index 7d90a3151..0bd9eb266 100644 --- a/tests/test_command.py +++ b/tests/test_command.py @@ -446,5 +446,20 @@ def tree(files): ax_pages.next_test_impact("\n (cd p && npx tsx a.ts)\n (cd p && npx tsx b.ts)\n").startswith('next: run the 2 commands above'), True) +# #1832: `test-impact --files a b` names a and b; `--files` is not a file, and never reaches `changed` as one +seen = [] +_run = ti.run +ti.run = lambda *a: (seen.append(a[1]), (0, json.dumps({'refused': 'stop'}), ''))[1] +try: + with open(os.devnull, 'w') as null: + _out, sys.stdout = sys.stdout, null + try: ti.main(['--files', 'a.py', 'b.py']) + finally: sys.stdout = _out +finally: + ti.run = _run +check("--files: the named files reach changed, the flag does not", + [x for x in (seen[0] if seen else []) if x not in ('--whole', '--json', '--suggest')], ['a.py', 'b.py']) +check("--files: the named files count whole", '--whole' in (seen[0] if seen else []), True) + print('\n' + ('all passed' if not fails else f"{fails} FAILED")) sys.exit(1 if fails else 0) From 47fb4299b939d7a79ae5240b246b0fe4e2899ab8 Mon Sep 17 00:00:00 2001 From: Swapnil <78632212+swapnilpaliwal-sd@users.noreply.github.com> Date: Wed, 18 Nov 2026 15:09:43 -0800 Subject: [PATCH 3/9] csharp: new T() on a staged library type is not an external constructor (#1339) With a C# library staged, `new Store()` on a library type was still reported as a construction of an unstaged dependency. Declared constructor: the site had two rows, the resolved one and `external:Store.` (provenance external). The cause is call_ctor_target_accepts in external-types.dl, which re-checked that the target accepts the argument count under the SITE's provenance. A client site that reaches a library constructor has the constructor under "lib", so the check found nothing and the "staged type, no carried constructor" clause labelled a resolved site as unstaged. call_ctor_target already checks the arity under the constructor's own provenance, so the relation now reads it as is. No constructor carried: the site was `external:Store.`, which says the dependency was not supplied. It now has one row to `generated:#/0` with callee_provenance lib and tier boundary_lib; the bundle gives that id a methods row with provenance generated, as it does for a delegate member's Invoke. `new T()` compiles only if T has a parameterless constructor, so the target exists, but a library IR is a signature subset and cannot say whether T declares it, so the site is still kept out of known_implicit_ctor. A site whose argument count no carried constructor accepts, where the IR carries some, keeps its external label, like an uncarried method. Tests: staging-test.sh gains both shapes; it fails on the base (2 rows / external) and passes here. --- graph/bundle/SCHEMA.md | 4 +- graph/bundle/schema.ts | 4 +- .../engine/call-edge-generation/call_chain.dl | 11 +++++ .../engine/resolution/external-types.dl | 34 +++++++++++++- graph/csharp/souffle/decls_all.dl | 1 + graph/test/csharp/staging-test.sh | 45 +++++++++++++++++++ 6 files changed, 94 insertions(+), 5 deletions(-) diff --git a/graph/bundle/SCHEMA.md b/graph/bundle/SCHEMA.md index 3b54dcc71..3c7bddeb7 100644 --- a/graph/bundle/SCHEMA.md +++ b/graph/bundle/SCHEMA.md @@ -347,7 +347,7 @@ Every callable the graph refers to: all client methods/functions from the IR, pl | `client` | all | Declared in the analysed project. | | `lib` | all | Declared in a staged library IR; listed because an edge reaches it. | | `generated` | java | Declared by a compile-time annotation processor: present in the compiled artefact and in every caller's source, and in no IR, so the bundle synthesises it to give the edge a target. id `generated:#/`, no file and no line numbers. | -| `generated` | csharp | The Invoke of the delegate held in one field or property: id `generated:#.Invoke`, no file and no line numbers. Every call through that member is an edge to it (tier boundary_lib, which is also where the compiler binds the call), and what the member holds is in dispatch_candidates with basis `value`. | +| `generated` | csharp | The Invoke of the delegate held in one field or property: id `generated:#.Invoke`, no file and no line numbers. Every call through that member is an edge to it (tier boundary_lib, which is also where the compiler binds the call), and what the member holds is in dispatch_candidates with basis `value`. And the parameterless constructor of a staged library type whose IR carries no constructor: id `generated:#/0`. `new T()` compiles only if T has one, so the target exists, but a library IR is a signature subset and cannot say whether T declares it or the compiler supplies it. The `new` site is an edge to it with callee_provenance `lib` and tier boundary_lib, not an `external:` label, because the library WAS staged. | **Notes** @@ -578,7 +578,7 @@ THE GRAPH. One row per (site, resolved target). A site with N possible targets h |---|---|---| | `external` | all | The target is outside every staged IR. callee_method_id is NULL and callee_label names it, as `external:.`. A client-only run of a C# project reaches the BCL this way for most of its calls. | | `client` | all | Target is a client method (callee_method_id set). | -| `lib` | all | Target is a method of a staged library IR (callee_method_id set, methods.provenance = lib). | +| `lib` | all | Target is a method of a staged library IR (callee_method_id set, methods.provenance = lib). C# only: or the parameterless constructor of a staged type its IR does not carry, a methods row with provenance `generated`. | | `generated` | csharp | The target is a member the compiler generated and no source declares (a `boundary_generated` row); callee_label names it. | | `builtin` | python | Target is a CPython builtin with no Python source (callee_label = `builtin:NAME`). | | `external` | python, java | Target is outside every staged IR and has no methods row. Python: an import path (callee_label = the written path). Java: a method of an unstaged ancestor type (callee_label = `external:.`), reached through a receiver declared as that type or inherited by a client subclass; see types.provenance external. | diff --git a/graph/bundle/schema.ts b/graph/bundle/schema.ts index 906ca4eda..94fe91ad6 100644 --- a/graph/bundle/schema.ts +++ b/graph/bundle/schema.ts @@ -415,7 +415,7 @@ export const VOCAB: readonly VocabSpec[] = [ { table: 'methods', column: 'provenance', value: 'client', languages: 'all', meaning: 'Declared in the analysed project.' }, { table: 'methods', column: 'provenance', value: 'lib', languages: 'all', meaning: 'Declared in a staged library IR; listed because an edge reaches it.' }, { table: 'methods', column: 'provenance', value: 'generated', languages: J, meaning: 'Declared by a compile-time annotation processor: present in the compiled artefact and in every caller\'s source, and in no IR, so the bundle synthesises it to give the edge a target. id `generated:#/`, no file and no line numbers.' }, - { table: 'methods', column: 'provenance', value: 'generated', languages: C, meaning: 'The Invoke of the delegate held in one field or property: id `generated:#.Invoke`, no file and no line numbers. Every call through that member is an edge to it (tier boundary_lib, which is also where the compiler binds the call), and what the member holds is in dispatch_candidates with basis `value`.' }, + { table: 'methods', column: 'provenance', value: 'generated', languages: C, meaning: 'The Invoke of the delegate held in one field or property: id `generated:#.Invoke`, no file and no line numbers. Every call through that member is an edge to it (tier boundary_lib, which is also where the compiler binds the call), and what the member holds is in dispatch_candidates with basis `value`. And the parameterless constructor of a staged library type whose IR carries no constructor: id `generated:#/0`. `new T()` compiles only if T has one, so the target exists, but a library IR is a signature subset and cannot say whether T declares it or the compiler supplies it. The `new` site is an edge to it with callee_provenance `lib` and tier boundary_lib, not an `external:` label, because the library WAS staged.' }, { table: 'types', column: 'provenance', value: 'client', languages: 'all', meaning: 'Declared in the analysed project.' }, { table: 'types', column: 'provenance', value: 'lib', languages: 'all', meaning: 'Declared in a staged library IR.' }, { table: 'types', column: 'provenance', value: 'external', languages: J, meaning: 'Named by the client as an ancestor (`extends`/`implements`) but declared in no staged IR: id `external:`, category EXTERNAL_TYPE, no file, no members. Kept so the subtype edge survives; stage the library to replace it with the real declaration.' }, @@ -617,7 +617,7 @@ export const VOCAB: readonly VocabSpec[] = [ // call_edges.callee_provenance { table: 'call_edges', column: 'callee_provenance', value: 'client', languages: 'all', meaning: 'Target is a client method (callee_method_id set).' }, - { table: 'call_edges', column: 'callee_provenance', value: 'lib', languages: 'all', meaning: 'Target is a method of a staged library IR (callee_method_id set, methods.provenance = lib).' }, + { table: 'call_edges', column: 'callee_provenance', value: 'lib', languages: 'all', meaning: 'Target is a method of a staged library IR (callee_method_id set, methods.provenance = lib). C# only: or the parameterless constructor of a staged type its IR does not carry, a methods row with provenance `generated`.' }, { table: 'call_edges', column: 'callee_provenance', value: 'generated', languages: C, meaning: 'The target is a member the compiler generated and no source declares (a `boundary_generated` row); callee_label names it.' }, { table: 'call_edges', column: 'callee_provenance', value: 'builtin', languages: P, meaning: 'Target is a CPython builtin with no Python source (callee_label = `builtin:NAME`).' }, { table: 'call_edges', column: 'callee_provenance', value: 'external', languages: ['python', 'java'], meaning: 'Target is outside every staged IR and has no methods row. Python: an import path (callee_label = the written path). Java: a method of an unstaged ancestor type (callee_label = `external:.`), reached through a receiver declared as that type or inherited by a client subclass; see types.provenance external.' }, diff --git a/graph/csharp/engine/call-edge-generation/call_chain.dl b/graph/csharp/engine/call-edge-generation/call_chain.dl index 61db248e2..64e94f417 100644 --- a/graph/csharp/engine/call-edge-generation/call_chain.dl +++ b/graph/csharp/engine/call-edge-generation/call_chain.dl @@ -111,6 +111,8 @@ site_leaves_client(prov, e) :- client_calls_lib(prov, e, _, _). // a real project that is most of the unresolved sites -- which makes the number that // matters unreadable. site_leaves_client(prov, e) :- external_target(prov, e, _). +// And one into a staged type whose parameterless constructor its IR does not carry. +site_leaves_client(prov, e) :- staged_parameterless_ctor(prov, e, _). // A call through a field or property holding a delegate lands on the delegate's // Invoke, which the runtime supplies (resolution/delegates.dl). The site gets an edge // to that member's Invoke node and the stored functions are in the envelope. @@ -235,6 +237,14 @@ call_chain_edge(e, caller, "-", label, "external", "boundary_lib", kind) :- call_from("client", e, caller), invocation_site("client", e, kind). +// client -> A STAGED TYPE'S PARAMETERLESS CONSTRUCTOR, NOT CARRIED BY ITS IR. The +// target belongs to a staged type, so the provenance is `lib`; it is the `generated:` +// node resolution/external-types.dl names, which the bundle gives a methods row. +call_chain_edge(e, caller, "-", node, "lib", "boundary_lib", kind) :- + staged_parameterless_ctor("client", e, node), + call_from("client", e, caller), + invocation_site("client", e, kind). + // client -> A DELEGATE MEMBER'S INVOKE (#1206). `getPath(url)` on a field holding a // delegate calls Invoke -- Roslyn's answer too -- and which stored function then runs // is value flow, recorded in method_dispatch_candidate with basis `value` rather than @@ -400,6 +410,7 @@ call_has_edge(prov, e) :- client_calls_lib(prov, e, _, _). call_has_edge("client", e) :- client_calls_external(e, _). call_has_edge("client", e) :- delegate_member_call("client", e, _). call_has_edge("client", e) :- delegate_param_call(e, _). +call_has_edge("client", e) :- staged_parameterless_ctor("client", e, _). call_chain_edge(e, caller, "-", "-", "-", cls, kind) :- invocation_site("client", e, kind), diff --git a/graph/csharp/engine/resolution/external-types.dl b/graph/csharp/engine/resolution/external-types.dl index 966db7a15..6ff6722e0 100644 --- a/graph/csharp/engine/resolution/external-types.dl +++ b/graph/csharp/engine/resolution/external-types.dl @@ -435,20 +435,52 @@ external_target(prov, e, label) :- // constructor clause above needs the type to be UNSTAGED, so once a library // declares the type the site had neither a constructor to resolve nor a name to // carry. Refusing the implicit-constructor claim alone leaves it a blind spot. +// +// NOT FOR `new T()` ON A STAGED TYPE THAT CARRIES NO CONSTRUCTOR AT ALL. That site +// runs T's parameterless constructor, which exists whether the library declares it +// or the compiler supplies it, and T is staged: `external` would say the +// dependency was not supplied, and it was (#1339). staged_parameterless_ctor names +// it inside the library instead. What is left here is a site whose argument count +// no carried constructor accepts although the IR carries some: a member the subset +// IR was not told about, named like an uncarried method. external_target(prov, e, label) :- call_needs_ctor_lookup(prov, e), expr_new_type(prov, e, gk), type_group("lib", _, gk), call_argc(prov, e, ac), !call_ctor_target_accepts(prov, e, ac), + !staged_parameterless_ctor(prov, e, _), type_decl("lib", n, _, _, _, t), type_group("lib", t, gk), label = cat("external:", cat(n, ".")). // Whether any constructor of the created type accepts this site's argument // count. Named rather than inlined because the rule above needs its NEGATION, // and a negated conjunction over three relations is where a cross-product hides. +// +// call_ctor_target already admits a constructor only where it accepts the site's +// argument count, under the provenance the constructor is DECLARED in. Re-checking +// it here under the SITE's provenance missed every staged constructor -- a client +// `new` reaching a library constructor -- so a resolved site was also labelled an +// unstaged one and had two rows (#1339). call_ctor_target_accepts(prov, e, ac) :- - call_ctor_target(prov, e, ctor), ctor_accepts_argc(prov, ctor, ac). + call_ctor_target(prov, e, _), call_argc(prov, e, ac). + +// staged_parameterless_ctor(Prov, Site, Node) -- `new T()` with no argument, on a +// staged type whose IR carries no constructor. Not known_implicit_ctor: a library IR +// is a signature subset, so it cannot show that T declares none. But `new T()` +// compiles only if T has a parameterless constructor, declared or supplied, so the +// target is known to exist and to be T's. The node is the `generated:` member id the +// bundle gives a methods row (provenance generated, owner T), so the edge points at +// T inside the library rather than at a label for an unsupplied dependency. +staged_parameterless_ctor(prov, e, node) :- + call_needs_ctor_lookup(prov, e), + expr_new_type(prov, e, gk), + type_group("lib", _, gk), + !type_ctor("lib", gk, _), + !type_ctor(prov, gk, _), + call_argc(prov, e, "0"), + type_decl("lib", _, qn, _, _, t), type_group("lib", t, gk), + node = cat("generated:", cat(qn, "#/0")). // ── A PROPERTY READ ON AN EXTERNAL RECEIVER ───────────────────────────────── // `someString.Length`, `dict.Count`, `ex.Message`. Reading a property IS a call, and diff --git a/graph/csharp/souffle/decls_all.dl b/graph/csharp/souffle/decls_all.dl index 182506dd0..d5c4ceda7 100644 --- a/graph/csharp/souffle/decls_all.dl +++ b/graph/csharp/souffle/decls_all.dl @@ -916,6 +916,7 @@ .decl site_unresolved_named(c0:symbol,c1:symbol,c2:symbol) .decl site_unresolved_real(c0:symbol) .decl sseg(c0:symbol,c1:number,c2:symbol) +.decl staged_parameterless_ctor(c0:symbol,c1:symbol,c2:symbol) .decl starts_slash(c0:symbol) .decl static_edge_exists(c0:symbol,c1:symbol) .decl static_fan_member(c0:symbol,c1:symbol,c2:symbol) diff --git a/graph/test/csharp/staging-test.sh b/graph/test/csharp/staging-test.sh index 7274c0edd..8dc3467f2 100755 --- a/graph/test/csharp/staging-test.sh +++ b/graph/test/csharp/staging-test.sh @@ -288,6 +288,51 @@ aln=$(awk -F' ' '$6=="boundary_lib"' "$AL" 2>/dev/null | wc -l | tr -d ' ') [ "${aln:-0}" -eq 2 ] || fail "a keyword-typed receiver did not reach the staged framework type: got ${aln:-0} of 2" grep -q "external:" "$AL" 2>/dev/null && fail "a keyword-typed receiver was still labelled external although its type is staged" +# ── `new T()` ON A STAGED TYPE IS NOT AN UNSTAGED DEPENDENCY (#1339) ─────── +# Two shapes of one site, each in its own run because the library is the variable: +# ctor/ Store declares a constructor. The site has exactly ONE row, the +# resolved one. It used to have a second, `external:Store.`, +# because the "no carried constructor accepts this arity" check joined +# the library's constructor under the client's provenance and found +# nothing, so a resolved site was also labelled unstaged. +# noctor/ Store declares none. The parameterless constructor the site runs is +# not carried, but the TYPE is staged, so the row must not say +# `external` -- that provenance means "this dependency was not +# supplied", and it was. Nor is it known_implicit_ctor: a library IR is +# a signature subset, so it cannot prove the type declares none. +for shape in ctor noctor; do + mkdir -p "$WORK/new-$shape-lib" "$WORK/new-$shape-cli" + if [ "$shape" = ctor ]; then decl='public Store() { }'; else decl=''; fi + cat > "$WORK/new-$shape-lib/Store.cs" < "$WORK/new-$shape-cli/Program.cs" <<'EOF2' +using Acme; +namespace App; +public static class Program { public static int Main() { var s = new Store(); return s.Open("x").Size(); } } +EOF2 + node "$REPO/parser/dist/index.js" "$WORK/new-$shape-lib" "new-$shape-lib" false "$WORK/new-$shape-libir" --per-language > "$WORK/new-$shape-parse.log" 2>&1 + bash "$REPO/bin/axiomcode" all --language csharp --src "$WORK/new-$shape-cli" --out "$WORK/new-$shape-out" \ + --library "$WORK/new-$shape-libir" --version pinned --debug > "$WORK/new-$shape.log" 2>&1 + NEW="$WORK/new-$shape-out/csharp/raw/call-chain-edges.csv" + rows=$(awk -F'\t' '$7=="new"' "$NEW" 2>/dev/null | wc -l | tr -d ' ') + ext=$(awk -F'\t' '$7=="new" && $5=="external"' "$NEW" 2>/dev/null | wc -l | tr -d ' ') + libm=$(awk -F'\t' '$7=="new" && $5=="lib" && $4 ~ /^CS_METHOD_/' "$NEW" 2>/dev/null | wc -l | tr -d ' ') + implicit=$(awk -F'\t' '$7=="new" && $6=="known_implicit_ctor"' "$NEW" 2>/dev/null | wc -l | tr -d ' ') + if [ "$shape" = ctor ]; then + [ "${rows:-0}" -eq 1 ] && [ "${libm:-0}" -eq 1 ] || \ + fail "\`new Store()\` on a staged type that DECLARES its constructor has ${rows:-0} row(s), ${libm:-0} to the library constructor and ${ext:-0} external; expected exactly the one resolved row" + else + [ "${rows:-0}" -eq 1 ] || fail "\`new Store()\` on a staged type with no carried constructor has ${rows:-0} row(s), expected 1" + [ "${ext:-0}" -eq 0 ] || fail "\`new Store()\` on a STAGED type with no carried constructor is labelled external, as if the library had not been supplied" + [ "${implicit:-0}" -eq 0 ] || fail "\`new Store()\` on a staged type claimed known_implicit_ctor, which a signature-subset IR cannot prove" + fi + [ "${rows:-0}" -ge 1 ] || awk -F'\t' '{print " got: "$4" "$5" "$6" "$7}' "$NEW" 2>/dev/null | head -5 + [ "${rows:-0}" -le 1 ] || awk -F'\t' '$7=="new"{print " got: "$4" "$5" "$6" "$7}' "$NEW" 2>/dev/null | head -5 +done + # ── STAGING NOTHING CHANGES NOTHING ───────────────────────────────────────── # The cross-provenance clauses must be inert on a client-only run. Compared # relation by relation, and then the SAME comparison is run against the staged From 57e30c1eae9a25ac396b2d4b44034274b6fb0c41 Mon Sep 17 00:00:00 2001 From: Swapnil <78632212+swapnilpaliwal-sd@users.noreply.github.com> Date: Wed, 18 Nov 2026 15:23:01 -0800 Subject: [PATCH 4/9] release 0.2.4: every package and plugin manifest at 0.2.4 (the parser keeps its own version) 0.2.3 is released, so what merges into this branch ships in 0.2.4. package.json (version and the five @axiomcode/engine-* pins) and the four editor plugin and extension manifests move from 0.2.3 to 0.2.4. The parser keeps its own version. --- gemini-extension.json | 2 +- package.json | 12 ++++++------ plugins/axiomcode/.claude-plugin/plugin.json | 2 +- plugins/axiomcode/.codex-plugin/plugin.json | 2 +- plugins/axiomcode/.cursor-plugin/plugin.json | 2 +- 5 files changed, 10 insertions(+), 10 deletions(-) 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/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", From 272f1af57e0812fc98634b84444976e1fdfdb524 Mon Sep 17 00:00:00 2001 From: Swapnil <78632212+swapnilpaliwal-sd@users.noreply.github.com> Date: Wed, 18 Nov 2026 15:36:23 -0800 Subject: [PATCH 5/9] typescript: a call to a function-literal const no longer also names its annotation's signature (#2005) A call to a const annotated with a callable type and holding a function literal resolved two ways: the literal's body and the annotation's bodiless call signature. Rule (3) in callee-resolution.dl added the signature of the callee's expr_type or expr_shape with no check that the callee already holds a literal, which the method lookup answers with its body. The namespace var_shape clause in expr-type.dl carried that guard; rule (3) did not. Rule (3) now skips a callee that holds a function literal (callee_holds_function): a local, a named import, or a namespace member read. The relation is built from relations below the expression fixpoint, so the negation stays stratifiable. A const holding a factory's result, and a parameter, keep the signature as the target. Case 101 pins the interface and function-type-alias forms through a local, a named import and a namespace read, with factory and parameter controls. On the base each literal site is multi_inferred to body and signature; here each is one known_edge to the body. Goldens: the same two-way hedge collapses to the body in 08 (lib), 63, 65, 74 and 77. The compiler names the annotation's signature, so 08, 63 and 65 record it in known-missing, the shape 92 and 98 already accept; 77 loses an extra. The comment in case 65 describes what a revert now looks like. --- .../src/formats.ts | 10 ++++++++ .../src/globals.d.ts | 11 +++++++++ .../src/tsconfig.json | 1 + .../101-annotated-function-const/src/x.ts | 17 ++++++++++++++ .../src/fewer.ts | 6 ++--- ...08-function-values-and-callbacks.lib.edges | 1 - ...ion-values-and-callbacks.lib.known-missing | 7 ++++++ ...8-function-values-and-callbacks.lib.oracle | 3 ++- .../101-annotated-function-const.edges | 10 ++++++++ .../101-annotated-function-const.entries | 12 ++++++++++ .../101-annotated-function-const.envelope | 4 ++++ .../101-annotated-function-const.fields | 1 + ...101-annotated-function-const.fields-oracle | 7 ++++++ ...101-annotated-function-const.known-missing | 13 +++++++++++ ...annotated-function-const.lib.known-missing | 13 +++++++++++ .../101-annotated-function-const.oracle | 13 +++++++++++ .../101-annotated-function-const.type-use | 8 +++++++ .../101-annotated-function-const.types-oracle | 7 ++++++ .../63-annotated-callable-member.edges | 6 ++--- ...63-annotated-callable-member.known-missing | 7 ++++++ .../63-annotated-callable-member.oracle | 4 ++-- ...-annotated-callable-fewer-parameters.edges | 6 ++--- ...ed-callable-fewer-parameters.known-missing | 8 +++++++ ...annotated-callable-fewer-parameters.oracle | 4 +++- .../expected/74-jsx-component-forms.edges | 3 +-- .../77-package-published-entries.edges | 3 +-- .../77-package-published-entries.oracle | 3 +-- .../callee-resolution.dl | 23 +++++++++++++++++++ graph/typescript/souffle/decls_all.dl | 1 + 29 files changed, 190 insertions(+), 22 deletions(-) create mode 100644 graph/test/typescript/cases/101-annotated-function-const/src/formats.ts create mode 100644 graph/test/typescript/cases/101-annotated-function-const/src/globals.d.ts create mode 100644 graph/test/typescript/cases/101-annotated-function-const/src/tsconfig.json create mode 100644 graph/test/typescript/cases/101-annotated-function-const/src/x.ts create mode 100644 graph/test/typescript/expected/08-function-values-and-callbacks.lib.known-missing create mode 100644 graph/test/typescript/expected/101-annotated-function-const.edges create mode 100644 graph/test/typescript/expected/101-annotated-function-const.entries create mode 100644 graph/test/typescript/expected/101-annotated-function-const.envelope create mode 100644 graph/test/typescript/expected/101-annotated-function-const.fields create mode 100644 graph/test/typescript/expected/101-annotated-function-const.fields-oracle create mode 100644 graph/test/typescript/expected/101-annotated-function-const.known-missing create mode 100644 graph/test/typescript/expected/101-annotated-function-const.lib.known-missing create mode 100644 graph/test/typescript/expected/101-annotated-function-const.oracle create mode 100644 graph/test/typescript/expected/101-annotated-function-const.type-use create mode 100644 graph/test/typescript/expected/101-annotated-function-const.types-oracle create mode 100644 graph/test/typescript/expected/63-annotated-callable-member.known-missing create mode 100644 graph/test/typescript/expected/65-annotated-callable-fewer-parameters.known-missing diff --git a/graph/test/typescript/cases/101-annotated-function-const/src/formats.ts b/graph/test/typescript/cases/101-annotated-function-const/src/formats.ts new file mode 100644 index 000000000..475913447 --- /dev/null +++ b/graph/test/typescript/cases/101-annotated-function-const/src/formats.ts @@ -0,0 +1,10 @@ +// A const annotated with a callable type and holding a function literal: the call's +// target is the literal's body, not the annotation's bodiless signature beside it. +export interface Format { (input: string): string } +export type Fn = (input: string) => string; +export const fromArrow: Format = (input) => input; +export const fromAlias: Fn = (input) => input; + +// controls: the value is a factory's result, so the signature is the only answer. +declare function makeFormat(): Format; +export const made: Format = makeFormat(); diff --git a/graph/test/typescript/cases/101-annotated-function-const/src/globals.d.ts b/graph/test/typescript/cases/101-annotated-function-const/src/globals.d.ts new file mode 100644 index 000000000..dd5843cc1 --- /dev/null +++ b/graph/test/typescript/cases/101-annotated-function-const/src/globals.d.ts @@ -0,0 +1,11 @@ +// The case's own standard library under `noLib`. +interface Object {} +interface Boolean {} +interface Number {} +interface String {} +interface Array { length: number; } +interface Function {} +interface CallableFunction extends Function {} +interface NewableFunction extends Function {} +interface IArguments {} +interface RegExp {} diff --git a/graph/test/typescript/cases/101-annotated-function-const/src/tsconfig.json b/graph/test/typescript/cases/101-annotated-function-const/src/tsconfig.json new file mode 100644 index 000000000..dcbfb4f8d --- /dev/null +++ b/graph/test/typescript/cases/101-annotated-function-const/src/tsconfig.json @@ -0,0 +1 @@ +{ "compilerOptions": { "strict": true, "noLib": true, "target": "es2022" } } diff --git a/graph/test/typescript/cases/101-annotated-function-const/src/x.ts b/graph/test/typescript/cases/101-annotated-function-const/src/x.ts new file mode 100644 index 000000000..2db50cf04 --- /dev/null +++ b/graph/test/typescript/cases/101-annotated-function-const/src/x.ts @@ -0,0 +1,17 @@ +import * as formats from "./formats"; +import { fromArrow, fromAlias, made, Format, Fn } from "./formats"; + +export function viaNamespace(s: string): string { return formats.fromArrow(s); } +export function viaNamed(s: string): string { return fromArrow(s); } +const local: Format = (i) => i; +export function viaLocal(s: string): string { return local(s); } + +export function aliasNamespace(s: string): string { return formats.fromAlias(s); } +export function aliasNamed(s: string): string { return fromAlias(s); } +const localAlias: Fn = (i) => i; +export function aliasLocal(s: string): string { return localAlias(s); } + +// controls: no literal to find, so the annotation's signature stays the target. +export function factoryNamed(s: string): string { return made(s); } +export function factoryNamespace(s: string): string { return formats.made(s); } +export function viaParam(f: Format, s: string): string { return f(s); } diff --git a/graph/test/typescript/cases/65-annotated-callable-fewer-parameters/src/fewer.ts b/graph/test/typescript/cases/65-annotated-callable-fewer-parameters/src/fewer.ts index dd2d59d8e..93cd4660e 100644 --- a/graph/test/typescript/cases/65-annotated-callable-fewer-parameters/src/fewer.ts +++ b/graph/test/typescript/cases/65-annotated-callable-fewer-parameters/src/fewer.ts @@ -19,9 +19,9 @@ // WHAT THE DISCRIMINATOR IS. Read the `.edges` golden, not the `.oracle` one. `tsc` // answers with the DECLARED TYPE -- the two-parameter call signature -- and is right to; // the implementation surviving beside it is a claim about what RUNS, which the compiler -// oracle does not make and cannot score. Reverting the relaxation removes the arrow edge -// from every mismatch cell below and drops the tier back to `known_edge`, so the `.edges` -// golden is where it shows up. +// oracle does not make and cannot score. Reverting the relaxation removes the arrow edge, +// each cell's only one since the signature is no longer added beside a literal (#2005), +// so a revert leaves the call with no edge, and the `.edges` golden is where it shows up. // // THE ANNOTATION IS A NAMED INTERFACE, not an inline function type, so that the target // both sides name is the interface's call signature and the comparison is about which diff --git a/graph/test/typescript/expected/08-function-values-and-callbacks.lib.edges b/graph/test/typescript/expected/08-function-values-and-callbacks.lib.edges index 7a2b1a274..8b3fc29e1 100644 --- a/graph/test/typescript/expected/08-function-values-and-callbacks.lib.edges +++ b/graph/test/typescript/expected/08-function-values-and-callbacks.lib.edges @@ -1,5 +1,4 @@ ambiguous_unknown METHOD_CALL values#drive() @L29 -> - -boundary_lib FUNCTION_CALL values#useLibrary() @L40 -> hooks#(string) boundary_lib FUNCTION_CALL values#useLibrary() @L40 -> hooks#identity(?) boundary_lib FUNCTION_CALL values#useLibrary() @L40 -> hooks#withHook(Hook,string) callback_handed FUNCTION_CALL values#drive() @L30 -> values#lower(?) diff --git a/graph/test/typescript/expected/08-function-values-and-callbacks.lib.known-missing b/graph/test/typescript/expected/08-function-values-and-callbacks.lib.known-missing new file mode 100644 index 000000000..973949176 --- /dev/null +++ b/graph/test/typescript/expected/08-function-values-and-callbacks.lib.known-missing @@ -0,0 +1,7 @@ +# Accepted client->library gaps for 08-function-values-and-callbacks: +# each line is an edge the TypeScript compiler resolves and this engine does not. A NEW missing +# edge fails the suite; a line here that STARTS working also fails, so the debt cannot rot. +# A const that HOLDS a function literal and is annotated with a callable type: the compiler names +# the annotation's signature, the engine names the literal's body, the accepted shape of +# 92-namespace-typed-const and 101-annotated-function-const (#2005). +values#useLibrary() -> hooks#(string) diff --git a/graph/test/typescript/expected/08-function-values-and-callbacks.lib.oracle b/graph/test/typescript/expected/08-function-values-and-callbacks.lib.oracle index 068febee7..037ec4349 100644 --- a/graph/test/typescript/expected/08-function-values-and-callbacks.lib.oracle +++ b/graph/test/typescript/expected/08-function-values-and-callbacks.lib.oracle @@ -1,3 +1,4 @@ -oracle=8 engine=10 agree=8 missing=0 (known 0, NEW 0) extra=2 +oracle=8 engine=9 agree=7 missing=1 (known 1, NEW 0) extra=2 + known values#useLibrary() -> hooks#(string) extra values#drive() -> Pipeline#tag(string) extra values#useLibrary() -> hooks#identity(?) diff --git a/graph/test/typescript/expected/101-annotated-function-const.edges b/graph/test/typescript/expected/101-annotated-function-const.edges new file mode 100644 index 000000000..08ba85427 --- /dev/null +++ b/graph/test/typescript/expected/101-annotated-function-const.edges @@ -0,0 +1,10 @@ +ambient_terminal FUNCTION_CALL formats#() @L10 -> formats#makeFormat() +known_edge FUNCTION_CALL x#aliasLocal(string) @L12 -> x#localAlias(?) +known_edge FUNCTION_CALL x#aliasNamed(string) @L10 -> formats#fromAlias(?) +known_edge FUNCTION_CALL x#factoryNamed(string) @L15 -> Format#(string) +known_edge FUNCTION_CALL x#viaLocal(string) @L7 -> x#local(?) +known_edge FUNCTION_CALL x#viaNamed(string) @L5 -> formats#fromArrow(?) +known_edge FUNCTION_CALL x#viaParam(Format,string) @L17 -> Format#(string) +known_edge METHOD_CALL x#aliasNamespace(string) @L9 -> formats#fromAlias(?) +known_edge METHOD_CALL x#factoryNamespace(string) @L16 -> Format#(string) +known_edge METHOD_CALL x#viaNamespace(string) @L4 -> formats#fromArrow(?) diff --git a/graph/test/typescript/expected/101-annotated-function-const.entries b/graph/test/typescript/expected/101-annotated-function-const.entries new file mode 100644 index 000000000..bc7967437 --- /dev/null +++ b/graph/test/typescript/expected/101-annotated-function-const.entries @@ -0,0 +1,12 @@ +── entry_point (11) ── + exported_from_entry_module x#aliasLocal x.ts:12 + exported_from_entry_module x#aliasNamed x.ts:10 + exported_from_entry_module x#aliasNamespace x.ts:9 + exported_from_entry_module x#factoryNamed x.ts:15 + exported_from_entry_module x#factoryNamespace x.ts:16 + exported_from_entry_module x#viaLocal x.ts:7 + exported_from_entry_module x#viaNamed x.ts:5 + exported_from_entry_module x#viaNamespace x.ts:4 + exported_from_entry_module x#viaParam x.ts:17 + unimported_module globals# globals.d.ts:1 + unimported_module x# x.ts:1 diff --git a/graph/test/typescript/expected/101-annotated-function-const.envelope b/graph/test/typescript/expected/101-annotated-function-const.envelope new file mode 100644 index 000000000..9cd02f860 --- /dev/null +++ b/graph/test/typescript/expected/101-annotated-function-const.envelope @@ -0,0 +1,4 @@ +value formats#@4:18 -> formats#@6 +value formats#@4:18 -> x#@11 +value formats#Format. -> formats#@5 +value formats#Format. -> x#@6 diff --git a/graph/test/typescript/expected/101-annotated-function-const.fields b/graph/test/typescript/expected/101-annotated-function-const.fields new file mode 100644 index 000000000..4d23b91a4 --- /dev/null +++ b/graph/test/typescript/expected/101-annotated-function-const.fields @@ -0,0 +1 @@ +known_edge read x#factoryNamed(string) -> formats#made diff --git a/graph/test/typescript/expected/101-annotated-function-const.fields-oracle b/graph/test/typescript/expected/101-annotated-function-const.fields-oracle new file mode 100644 index 000000000..a2ffbadd5 --- /dev/null +++ b/graph/test/typescript/expected/101-annotated-function-const.fields-oracle @@ -0,0 +1,7 @@ +101-annotated-function-const [fields] + precision 0.0000 (0 correct, 0 wrong) + recall 0.0000 (0 of 0 the compiler resolved) + sites 1 resolved 1 (100.0%) + tiers known_edge=1 + access read=1 + not scored: 1 rows whose target is not a client declaration diff --git a/graph/test/typescript/expected/101-annotated-function-const.known-missing b/graph/test/typescript/expected/101-annotated-function-const.known-missing new file mode 100644 index 000000000..cf05307c4 --- /dev/null +++ b/graph/test/typescript/expected/101-annotated-function-const.known-missing @@ -0,0 +1,13 @@ +# Accepted gaps for 101-annotated-function-const: each line is an edge the TypeScript compiler +# resolves and this engine does not. A NEW missing edge fails the suite; +# a line here that STARTS working also fails, so the debt cannot rot. +# A const that HOLDS a function literal and is annotated with a callable type: the compiler names +# the annotation's signature, the engine names the literal's body, the same accepted shape as +# 92-namespace-typed-const and 98-namespace-const-callable (#2005). Kept on purpose: the signature +# must not be added beside the body as a second target. +x#aliasLocal(string) -> formats#(string) +x#aliasNamed(string) -> formats#(string) +x#aliasNamespace(string) -> formats#(string) +x#viaLocal(string) -> Format#(string) +x#viaNamed(string) -> Format#(string) +x#viaNamespace(string) -> Format#(string) diff --git a/graph/test/typescript/expected/101-annotated-function-const.lib.known-missing b/graph/test/typescript/expected/101-annotated-function-const.lib.known-missing new file mode 100644 index 000000000..cf05307c4 --- /dev/null +++ b/graph/test/typescript/expected/101-annotated-function-const.lib.known-missing @@ -0,0 +1,13 @@ +# Accepted gaps for 101-annotated-function-const: each line is an edge the TypeScript compiler +# resolves and this engine does not. A NEW missing edge fails the suite; +# a line here that STARTS working also fails, so the debt cannot rot. +# A const that HOLDS a function literal and is annotated with a callable type: the compiler names +# the annotation's signature, the engine names the literal's body, the same accepted shape as +# 92-namespace-typed-const and 98-namespace-const-callable (#2005). Kept on purpose: the signature +# must not be added beside the body as a second target. +x#aliasLocal(string) -> formats#(string) +x#aliasNamed(string) -> formats#(string) +x#aliasNamespace(string) -> formats#(string) +x#viaLocal(string) -> Format#(string) +x#viaNamed(string) -> Format#(string) +x#viaNamespace(string) -> Format#(string) diff --git a/graph/test/typescript/expected/101-annotated-function-const.oracle b/graph/test/typescript/expected/101-annotated-function-const.oracle new file mode 100644 index 000000000..ce7d7cd1c --- /dev/null +++ b/graph/test/typescript/expected/101-annotated-function-const.oracle @@ -0,0 +1,13 @@ +oracle=10 engine=10 agree=4 missing=6 (known 6, NEW 0) extra=6 + known x#aliasLocal(string) -> formats#(string) + known x#aliasNamed(string) -> formats#(string) + known x#aliasNamespace(string) -> formats#(string) + known x#viaLocal(string) -> Format#(string) + known x#viaNamed(string) -> Format#(string) + known x#viaNamespace(string) -> Format#(string) + extra x#aliasLocal(string) -> x#localAlias(?) + extra x#aliasNamed(string) -> formats#fromAlias(?) + extra x#aliasNamespace(string) -> formats#fromAlias(?) + extra x#viaLocal(string) -> x#local(?) + extra x#viaNamed(string) -> formats#fromArrow(?) + extra x#viaNamespace(string) -> formats#fromArrow(?) diff --git a/graph/test/typescript/expected/101-annotated-function-const.type-use b/graph/test/typescript/expected/101-annotated-function-const.type-use new file mode 100644 index 000000000..5856712ac --- /dev/null +++ b/graph/test/typescript/expected/101-annotated-function-const.type-use @@ -0,0 +1,8 @@ +known_edge METHOD_PARAM 0 x [METHOD_PARAM] -> Format +known_edge METHOD_RETURN 0 formats [METHOD] -> Format +known_edge SUPER_TYPE 0 CallableFunction [HERITAGE] -> Function +known_edge SUPER_TYPE 0 NewableFunction [HERITAGE] -> Function +known_edge VARIABLE_TYPE 0 formats [VARIABLE] -> Fn +known_edge VARIABLE_TYPE 0 formats [VARIABLE] -> Format +known_edge VARIABLE_TYPE 0 x [VARIABLE] -> Fn +known_edge VARIABLE_TYPE 0 x [VARIABLE] -> Format diff --git a/graph/test/typescript/expected/101-annotated-function-const.types-oracle b/graph/test/typescript/expected/101-annotated-function-const.types-oracle new file mode 100644 index 000000000..54aa3f4ba --- /dev/null +++ b/graph/test/typescript/expected/101-annotated-function-const.types-oracle @@ -0,0 +1,7 @@ +101-annotated-function-const [types] + precision 1.0000 (6 correct, 0 wrong) + recall 1.0000 (6 of 6 the compiler resolved) + sites 9 resolved 9 (100.0%) + tiers known_edge=9 + contexts METHOD_PARAM=1 METHOD_RETURN=1 SUPER_TYPE=2 VARIABLE_TYPE=5 + not scored: 0 rows whose target is not a client declaration diff --git a/graph/test/typescript/expected/63-annotated-callable-member.edges b/graph/test/typescript/expected/63-annotated-callable-member.edges index bf5a18be9..e34aeed8a 100644 --- a/graph/test/typescript/expected/63-annotated-callable-member.edges +++ b/graph/test/typescript/expected/63-annotated-callable-member.edges @@ -1,8 +1,6 @@ known_edge FUNCTION_CALL members#callVarAmbient() @L66 -> NamedCallable#(number) +known_edge FUNCTION_CALL members#callVarInline() @L51 -> members#varInline(number) +known_edge FUNCTION_CALL members#callVarNamed() @L52 -> members#varNamed(number) known_edge METHOD_CALL members#callPlainMethod(PlainMethod) @L61 -> PlainMethod#run(number) known_edge METHOD_CALL members#callPropInline(PropInline) @L53 -> PropInline#(number) known_edge METHOD_CALL members#callPropNamed(PropNamed) @L54 -> NamedCallable#(number) -multi_inferred FUNCTION_CALL members#callVarInline() @L51 -> members#(number) -multi_inferred FUNCTION_CALL members#callVarInline() @L51 -> members#varInline(number) -multi_inferred FUNCTION_CALL members#callVarNamed() @L52 -> NamedCallable#(number) -multi_inferred FUNCTION_CALL members#callVarNamed() @L52 -> members#varNamed(number) diff --git a/graph/test/typescript/expected/63-annotated-callable-member.known-missing b/graph/test/typescript/expected/63-annotated-callable-member.known-missing new file mode 100644 index 000000000..75c39aab5 --- /dev/null +++ b/graph/test/typescript/expected/63-annotated-callable-member.known-missing @@ -0,0 +1,7 @@ +# Accepted gaps for 63-annotated-callable-member: +# each line is an edge the TypeScript compiler resolves and this engine does not. A NEW missing +# edge fails the suite; a line here that STARTS working also fails, so the debt cannot rot. +# A const that HOLDS a function literal and is annotated with a callable type: the compiler names +# the annotation's signature, the engine names the literal's body, the accepted shape of +# 92-namespace-typed-const and 101-annotated-function-const (#2005). +members#callVarNamed() -> NamedCallable#(number) diff --git a/graph/test/typescript/expected/63-annotated-callable-member.oracle b/graph/test/typescript/expected/63-annotated-callable-member.oracle index baee96d98..35b22bda3 100644 --- a/graph/test/typescript/expected/63-annotated-callable-member.oracle +++ b/graph/test/typescript/expected/63-annotated-callable-member.oracle @@ -1,3 +1,3 @@ -oracle=6 engine=8 agree=6 missing=0 (known 0, NEW 0) extra=2 - extra members#callVarInline() -> members#(number) +oracle=6 engine=6 agree=5 missing=1 (known 1, NEW 0) extra=1 + known members#callVarNamed() -> NamedCallable#(number) extra members#callVarNamed() -> members#varNamed(number) diff --git a/graph/test/typescript/expected/65-annotated-callable-fewer-parameters.edges b/graph/test/typescript/expected/65-annotated-callable-fewer-parameters.edges index 808bb1ab2..aeb0afea4 100644 --- a/graph/test/typescript/expected/65-annotated-callable-fewer-parameters.edges +++ b/graph/test/typescript/expected/65-annotated-callable-fewer-parameters.edges @@ -1,8 +1,6 @@ known_edge FUNCTION_CALL fewer#callAmbient() @L73 -> TwoArgs#(number,number) +known_edge FUNCTION_CALL fewer#callDeclaresFewer() @L47 -> fewer#declaresFewer(number) +known_edge FUNCTION_CALL fewer#callDeclaresSame() @L54 -> fewer#declaresSame(number,number) known_edge FUNCTION_CALL fewer#callSiblingsOne() @L90 -> Siblings#(number) known_edge FUNCTION_CALL fewer#callSiblingsTwo() @L91 -> Siblings#(number,number) known_edge METHOD_CALL fewer#callHolderRun(Holder) @L68 -> TwoArgs#(number,number) -multi_inferred FUNCTION_CALL fewer#callDeclaresFewer() @L47 -> TwoArgs#(number,number) -multi_inferred FUNCTION_CALL fewer#callDeclaresFewer() @L47 -> fewer#declaresFewer(number) -multi_inferred FUNCTION_CALL fewer#callDeclaresSame() @L54 -> TwoArgs#(number,number) -multi_inferred FUNCTION_CALL fewer#callDeclaresSame() @L54 -> fewer#declaresSame(number,number) diff --git a/graph/test/typescript/expected/65-annotated-callable-fewer-parameters.known-missing b/graph/test/typescript/expected/65-annotated-callable-fewer-parameters.known-missing new file mode 100644 index 000000000..fffdb6b96 --- /dev/null +++ b/graph/test/typescript/expected/65-annotated-callable-fewer-parameters.known-missing @@ -0,0 +1,8 @@ +# Accepted gaps for 65-annotated-callable-fewer-parameters: +# each line is an edge the TypeScript compiler resolves and this engine does not. A NEW missing +# edge fails the suite; a line here that STARTS working also fails, so the debt cannot rot. +# A const that HOLDS a function literal and is annotated with a callable type: the compiler names +# the annotation's signature, the engine names the literal's body, the accepted shape of +# 92-namespace-typed-const and 101-annotated-function-const (#2005). +fewer#callDeclaresFewer() -> TwoArgs#(number,number) +fewer#callDeclaresSame() -> TwoArgs#(number,number) diff --git a/graph/test/typescript/expected/65-annotated-callable-fewer-parameters.oracle b/graph/test/typescript/expected/65-annotated-callable-fewer-parameters.oracle index 2cbe7995d..e8bc0ff03 100644 --- a/graph/test/typescript/expected/65-annotated-callable-fewer-parameters.oracle +++ b/graph/test/typescript/expected/65-annotated-callable-fewer-parameters.oracle @@ -1,3 +1,5 @@ -oracle=6 engine=8 agree=6 missing=0 (known 0, NEW 0) extra=2 +oracle=6 engine=6 agree=4 missing=2 (known 2, NEW 0) extra=2 + known fewer#callDeclaresFewer() -> TwoArgs#(number,number) + known fewer#callDeclaresSame() -> TwoArgs#(number,number) extra fewer#callDeclaresFewer() -> fewer#declaresFewer(number) extra fewer#callDeclaresSame() -> fewer#declaresSame(number,number) diff --git a/graph/test/typescript/expected/74-jsx-component-forms.edges b/graph/test/typescript/expected/74-jsx-component-forms.edges index 1215ed2b5..f82b66d6f 100644 --- a/graph/test/typescript/expected/74-jsx-component-forms.edges +++ b/graph/test/typescript/expected/74-jsx-component-forms.edges @@ -16,13 +16,12 @@ known_edge FUNCTION_CALL app#useFactory() @L23 -> parts#()@L22 known_edge FUNCTION_CALL parts#FieldImpl({ label: string },unknown) @L39 -> parts#trackClick(string) known_edge FUNCTION_CALL parts#UserCard({ id: string }) @L34 -> parts#formatName(string) known_edge FUNCTION_CALL settings#Settings() @L6 -> settings#saveSettings() +known_edge JSX_COMPONENT_CALL app#App() @L11 -> parts#Badge(?) known_edge JSX_COMPONENT_CALL app#App() @L12 -> parts#Avatar({ src: string }) known_edge JSX_COMPONENT_CALL app#App() @L13 -> Panel#({ title: string }) known_edge JSX_COMPONENT_CALL app#App() @L14 -> settings#Settings() known_edge METHOD_CALL app#App() @L15 -> parts#Chip({ text: string }) multi_inferred JSX_COMPONENT_CALL app#App() @L10 -> parts#(T) multi_inferred JSX_COMPONENT_CALL app#App() @L10 -> parts#FieldImpl({ label: string },unknown) -multi_inferred JSX_COMPONENT_CALL app#App() @L11 -> parts#(T) -multi_inferred JSX_COMPONENT_CALL app#App() @L11 -> parts#Badge(?) multi_inferred JSX_COMPONENT_CALL app#App() @L9 -> parts#(T) multi_inferred JSX_COMPONENT_CALL app#App() @L9 -> parts#UserCard({ id: string }) diff --git a/graph/test/typescript/expected/77-package-published-entries.edges b/graph/test/typescript/expected/77-package-published-entries.edges index 313a7e054..3a5496beb 100644 --- a/graph/test/typescript/expected/77-package-published-entries.edges +++ b/graph/test/typescript/expected/77-package-published-entries.edges @@ -1,8 +1,7 @@ +known_edge FUNCTION_CALL index#useStore(number) @L10 -> vanilla#createCastStore(number) known_edge FUNCTION_CALL index#useStore(number) @L11 -> internal#describeState(number) known_edge FUNCTION_CALL index#useStore(number) @L9 -> vanilla#createStore(number) known_edge FUNCTION_CALL plugins/logger#logger(string) @L9 -> plugins/logger#format(string) known_edge FUNCTION_CALL vanilla#createBoundStore(number) @L12 -> vanilla#seal(number) known_edge FUNCTION_CALL vanilla#createCastStore(number) @L18 -> vanilla#seal(number) known_edge FUNCTION_CALL vanilla#createStore(number) @L4 -> vanilla#seal(number) -multi_inferred FUNCTION_CALL index#useStore(number) @L10 -> vanilla#(number) -multi_inferred FUNCTION_CALL index#useStore(number) @L10 -> vanilla#createCastStore(number) diff --git a/graph/test/typescript/expected/77-package-published-entries.oracle b/graph/test/typescript/expected/77-package-published-entries.oracle index 68001a69c..fa4000b6a 100644 --- a/graph/test/typescript/expected/77-package-published-entries.oracle +++ b/graph/test/typescript/expected/77-package-published-entries.oracle @@ -1,2 +1 @@ -oracle=7 engine=8 agree=7 missing=0 (known 0, NEW 0) extra=1 - extra index#useStore(number) -> vanilla#(number) +oracle=7 engine=7 agree=7 missing=0 (known 0, NEW 0) extra=0 diff --git a/graph/typescript/engine/expression-resolution/callee-resolution.dl b/graph/typescript/engine/expression-resolution/callee-resolution.dl index d05fc58a1..d692f096b 100644 --- a/graph/typescript/engine/expression-resolution/callee-resolution.dl +++ b/graph/typescript/engine/expression-resolution/callee-resolution.dl @@ -152,13 +152,36 @@ call_kind_is_plain_call("DECORATOR_CALL"). // value's type carries a call signature, which IS the target. Java's nearest // analogue is a functional interface, and there the single abstract method has to be // found by counting; here the call signature is a member with its own row. +// +// Not where the callee already holds a function LITERAL — `const f: Format = (i) => i; +// f(s)`. The literal's body is the target (rule (2), rule (8), expr_callable), and the +// annotation's bodiless signature beside it turned a right answer into a two-way hedge +// (#2005). The same guard the namespace var_shape clause in expr-type.dl carries. Where +// the value is a factory's result, or the callee is a parameter, there is no literal and +// the signature stays the answer. expr_call_candidate(ce, m) :- call_callee_expr(_, ce, ne), expr_type(ne, _, t), + !callee_holds_function(ne), call_signature_in_scope(t, m). expr_call_candidate(ce, m) :- call_callee_expr(_, ce, ne), expr_shape(ne, s), + !callee_holds_function(ne), call_signature_in_scope(s, m). +// A local, a named import, or a namespace member read whose value is a function literal. +// Built only from relations below the expression fixpoint (expr_callable is negated by +// callee_expr_bound already; expr_namespace and var_is_function feed expr_callable), so +// the negation above stays stratifiable. +callee_holds_function(e) :- expr_referenced("client", "VARIABLE", v, e), + var_is_function(v, _). +callee_holds_function(e) :- expr_referenced("client", "IMPORT_BINDING", ih, e), + import_binds(ih, _, "VARIABLE", v), + var_is_function(v, _). +callee_holds_function(e) :- property_access_recv(e, n, q), + expr_namespace(q, _, mod), + module_export(_, mod, n, "VARIABLE", v), + var_is_function(v, _). + // ============================================================================ // METHOD CALLS — `recv.name(...)` // ============================================================================ diff --git a/graph/typescript/souffle/decls_all.dl b/graph/typescript/souffle/decls_all.dl index 68e0681d8..cc2967dec 100644 --- a/graph/typescript/souffle/decls_all.dl +++ b/graph/typescript/souffle/decls_all.dl @@ -83,6 +83,7 @@ .decl call_target_is_signature(c0:symbol) .decl call_type_only_target(c0:symbol,c1:symbol) .decl callee_expr_bound(c0:symbol) +.decl callee_holds_function(c0:symbol) .decl callee_names_local(c0:symbol) .decl category_is_class(c0:symbol) .decl category_is_instantiable(c0:symbol) From ffda9d667db09d278807ae80d98866ca3f741f7b Mon Sep 17 00:00:00 2001 From: Swapnil <78632212+swapnilpaliwal-sd@users.noreply.github.com> Date: Wed, 18 Nov 2026 14:56:23 -0800 Subject: [PATCH 6/9] fill: list every unresolved call site the project may own, settle them in batches, and say so once per build The engine has done what it can by the end of a build; the sites it leaves are calls through a value (a handler table, a callback parameter, getattr, reflection) or a member called on a receiver it could not type. An answer listed the ones it stopped at; nothing listed them all, and nothing told the agent to look. - `axiomcode unresolved` / MCP `unresolved(limit, decisions)`: a summary line, then the open sites inside the most called callers first, each with its code, the engine's reason and its candidates. Only sites that may land in the project are listed: a member call needs a project method of that name, a bare call through a value counts unless the file imports the name. A library's method on an untyped value is counted, not listed. - `link --batch -`: links, rejected leads (`not:`) and `?` (read, nothing certain) in one apply, each validated as a single link is. A `?` or a rejection is kept in .axiomcode/fill-skipped.tsv keyed by the line's text, so the site is asked again only when its line changes. - the build ends with the summary line; the first prompt (hook) and the first query answer (MCP, for hosts without hooks) after a build say how many sites are open and how to fill them, once per build. - skill `fill` (`/axiomcode:fill`), forked into a subagent where the host supports it: read each site, link only what the code makes certain, return one line. --- hooks/hooks.json | 3 +- plugins/axiomcode/hooks/fill.py | 34 ++ plugins/axiomcode/hooks/hooks.json | 9 + plugins/axiomcode/mcp/server.py | 52 ++- plugins/axiomcode/skills/axiomcode/SKILL.md | 11 + .../skills/axiomcode/scripts/ax_fill.py | 376 ++++++++++++++++++ .../skills/axiomcode/scripts/ax_links.py | 110 +++-- .../skills/axiomcode/scripts/axiomcode | 6 +- .../skills/axiomcode/scripts/axiomcode-build | 4 + .../axiomcode/scripts/axiomcode-unresolved | 14 + plugins/axiomcode/skills/fill/SKILL.md | 47 +++ tests/README.md | 4 + tests/fill.py | 142 +++++++ tests/front_door.py | 4 +- tests/hosts.py | 6 +- tests/mcp.py | 3 +- tests/mcp_docs.py | 4 +- tests/surfaces.py | 2 +- 18 files changed, 779 insertions(+), 52 deletions(-) create mode 100644 plugins/axiomcode/hooks/fill.py create mode 100755 plugins/axiomcode/skills/axiomcode/scripts/ax_fill.py create mode 100755 plugins/axiomcode/skills/axiomcode/scripts/axiomcode-unresolved create mode 100644 plugins/axiomcode/skills/fill/SKILL.md create mode 100644 tests/fill.py 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/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/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..a3caadf97 --- /dev/null +++ b/plugins/axiomcode/skills/axiomcode/scripts/ax_fill.py @@ -0,0 +1,376 @@ +#!/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): + """(every callable name the project declares, the names of its METHODS): a call on a receiver reaches a method, + never a free or nested function""" + 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}, {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 +BARE_VALUE_KINDS = {'SIMPLE_CALL', 'DYNAMIC_CALL', 'COMPUTED_CALL', 'FUNCTION_CALL_APPLY', 'FUNCTION_CALL_CALL', + 'FUNCTION_CALL_BIND', 'IIFE_CALL', 'DYNAMIC_CODE_CALL'} + + +PROCESS_RUNNERS = re.compile(r'\b(subprocess|_?sp|asyncio|os|shutil|child_process|execa|ProcessBuilder|Process)\b[.:]|\bexec(Sync|File)?\b') +_PY_IMPORT = re.compile(r'^\s*(?:from\s+[\w.]+\s+)?import\s+\(?([^#]+?)\)?\s*(?:#.*)?$') +_JS_IMPORT = re.compile(r'^\s*import\s+(?:type\s+)?([^;]*?)\s+from\s+[\'"]([^\'"]+)[\'"]') + + +def imported_names(lines): + """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 []: + m = _PY_IMPORT.match(t) + if m and (t.lstrip().startswith(('from ', 'import '))): + for part in m.group(1).split(','): + part = part.strip().strip('()') + if part: out.add(part.split(' as ')[-1].strip().split('.')[0]) + continue + m = _JS_IMPORT.match(t) + if m and not m.group(2).startswith('.'): + for part in re.split(r'[{},]', m.group(1)): + part = part.strip() + 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 = {} + def imported(f): + if f not in seen: seen[f] = imported_names(reader.lines(site_file(f)) if reader else None) + 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 '') + 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 '): + # a library that runs a value it is handed (Method.invoke, Function.apply) — not one that runs a PROCESS + return not PROCESS_RUNNERS.search(reason) + 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 '') and nm not in imported(_f) + 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..8fd1362e1 100644 --- a/plugins/axiomcode/skills/axiomcode/scripts/ax_links.py +++ b/plugins/axiomcode/skills/axiomcode/scripts/ax_links.py @@ -1006,9 +1006,10 @@ def add(mid, why): return out -def unknown_sites(q, callers, site_file, limit=30, order=None, repo=None): +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')")} @@ -1037,6 +1038,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 +1086,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 +1231,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 +1318,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..e879ac97e 100755 --- a/plugins/axiomcode/skills/axiomcode/scripts/axiomcode-build +++ b/plugins/axiomcode/skills/axiomcode/scripts/axiomcode-build @@ -614,3 +614,7 @@ if [ ${#READY[@]} -gt 0 ]; then else echo "graph at $OUT/graph.sqlite" fi +# 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. +python3 "$H/ax_fill.py" "$REPO" --summary 2>/dev/null || true 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/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..0fb85b02c --- /dev/null +++ b/tests/fill.py @@ -0,0 +1,142 @@ +#!/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 ends with the summary line: 1 site may land in the project, 3 are a library's + 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) + + 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') + last = [l for l in b.stdout.split('\n') if l.strip()][-1:] or [''] + check(last[0].startswith('graph: ') and '1 may land in the project' in last[0] and "3 a library's method" in last[0], + f'build: the index ends with the summary line (got {last[0][: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'} From 414d36433caabe46d839e6f8f8b012980baf6e08 Mon Sep 17 00:00:00 2001 From: Swapnil <78632212+swapnilpaliwal-sd@users.noreply.github.com> Date: Wed, 18 Nov 2026 14:59:00 -0800 Subject: [PATCH 7/9] links: a process launcher is not a call that runs a value; fill: a JS import is a package's name - `subprocess.run(cmd)`, `asyncio.run(..)`, `child_process.exec(..)` matched the reflective names (`run`, `exec`) and every answer listed them under "to resolve" as running a value. A call written on a process or event-loop module, read through an import alias (`import a as b, subprocess as sp`, `import * as cp from 'child_process'`), is no longer one. Method.invoke, Function.apply and Thread.run still are. - a JS/TS `import { z } from 'zod'` line was read by the Python import rule, so its names were never taken as a package's and a bare call of one was listed as a call through a value; a relative import is still the project's own. --- .../skills/axiomcode/scripts/ax_fill.py | 18 ++++---- .../skills/axiomcode/scripts/ax_links.py | 44 ++++++++++++++++++- tests/fill.py | 13 ++++++ 3 files changed, 66 insertions(+), 9 deletions(-) diff --git a/plugins/axiomcode/skills/axiomcode/scripts/ax_fill.py b/plugins/axiomcode/skills/axiomcode/scripts/ax_fill.py index a3caadf97..6d0eb9c0c 100755 --- a/plugins/axiomcode/skills/axiomcode/scripts/ax_fill.py +++ b/plugins/axiomcode/skills/axiomcode/scripts/ax_fill.py @@ -99,8 +99,6 @@ def _project_names(con): 'FUNCTION_CALL_BIND', 'IIFE_CALL', 'DYNAMIC_CODE_CALL'} -PROCESS_RUNNERS = re.compile(r'\b(subprocess|_?sp|asyncio|os|shutil|child_process|execa|ProcessBuilder|Process)\b[.:]|\bexec(Sync|File)?\b') -_PY_IMPORT = re.compile(r'^\s*(?:from\s+[\w.]+\s+)?import\s+\(?([^#]+?)\)?\s*(?:#.*)?$') _JS_IMPORT = re.compile(r'^\s*import\s+(?:type\s+)?([^;]*?)\s+from\s+[\'"]([^\'"]+)[\'"]') @@ -109,10 +107,16 @@ def imported_names(lines): 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 []: - m = _PY_IMPORT.match(t) - if m and (t.lstrip().startswith(('from ', 'import '))): - for part in m.group(1).split(','): + 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 st.startswith('import ') and not any(q in st for q in ('"', "'")): # Python import + for part in st[len('import '):].split(','): + part = part.strip() if part: out.add(part.split(' as ')[-1].strip().split('.')[0]) continue m = _JS_IMPORT.match(t) @@ -143,9 +147,7 @@ def keep(row, reason): # 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 '): - # a library that runs a value it is handed (Method.invoke, Function.apply) — not one that runs a PROCESS - return not PROCESS_RUNNERS.search(reason) + 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`) diff --git a/plugins/axiomcode/skills/axiomcode/scripts/ax_links.py b/plugins/axiomcode/skills/axiomcode/scripts/ax_links.py index 8fd1362e1..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,6 +1035,17 @@ def add(mid, why): return out +_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). `keep(row, reason)` narrows the rows @@ -1023,7 +1063,9 @@ def unknown_sites(q, callers, site_file, limit=30, order=None, repo=None, keep=N # 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 " diff --git a/tests/fill.py b/tests/fill.py index 0fb85b02c..1e9877725 100644 --- a/tests/fill.py +++ b/tests/fill.py @@ -70,6 +70,19 @@ def check(ok, what): 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)})') + repo = tempfile.mkdtemp(prefix='ax-fill-') try: os.makedirs(os.path.join(repo, 'app')) From fe3c6df6e6495395885e264dd40de093078bc7e1 Mon Sep 17 00:00:00 2001 From: Swapnil <78632212+swapnilpaliwal-sd@users.noreply.github.com> Date: Wed, 18 Nov 2026 15:35:00 -0800 Subject: [PATCH 8/9] fill: TypeScript and C# value calls, multi-line imports, runtime globals and workspace packages Measured on a TypeScript monorepo, the fill list dropped every call through a local value there: the bare-call kinds were Python's only. And it kept what is not the project's: - a bare call is FUNCTION_CALL / JSX_COMPONENT_CALL in TypeScript and JavaScript and INVOCATION / DELEGATE_INVOKE in C#, not only SIMPLE_CALL (`const { useWidget } = ctx; useWidget()` was filed as a library's) - an import whose braces span lines (`import {\n expectTypeOf,\n} from 'vitest'`) is read; the reader is bounded, so a Python file's `import` lines cannot make it scan the whole file (a 120 s worklist on a 70k-line project before) - a runtime or test-runner global (`fetch`, `expect`, `expectTypeOf`, `assert`) is the platform's, unless the file imports the project's own declaration of that name from a relative path or a workspace package - an import from one of the repository's own workspace packages (a monorepo's `@scope/core`) is the project's - a bare call reaches functions, classes, consts and variables, never a method; a call on a receiver reaches methods --- .../skills/axiomcode/scripts/ax_fill.py | 85 +++++++++++++++---- tests/fill.py | 5 ++ 2 files changed, 74 insertions(+), 16 deletions(-) diff --git a/plugins/axiomcode/skills/axiomcode/scripts/ax_fill.py b/plugins/axiomcode/skills/axiomcode/scripts/ax_fill.py index 6d0eb9c0c..23b2da58e 100755 --- a/plugins/axiomcode/skills/axiomcode/scripts/ax_fill.py +++ b/plugins/axiomcode/skills/axiomcode/scripts/ax_fill.py @@ -85,24 +85,67 @@ def graph_counts(con): def _project_names(con): - """(every callable name the project declares, the names of its METHODS): a call on a receiver reaches a method, - never a free or nested function""" + """(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}, {n for n, k in rows if k in ('method', 'constructor', 'field')} + 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 -BARE_VALUE_KINDS = {'SIMPLE_CALL', 'DYNAMIC_CALL', 'COMPUTED_CALL', 'FUNCTION_CALL_APPLY', 'FUNCTION_CALL_CALL', +# (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 -_JS_IMPORT = re.compile(r'^\s*import\s+(?:type\s+)?([^;]*?)\s+from\s+[\'"]([^\'"]+)[\'"]') - - -def imported_names(lines): +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() @@ -114,16 +157,19 @@ def imported_names(lines): part = part.strip().strip('()') if part and part != '*': out.add(part.split(' as ')[-1].strip()) continue - if st.startswith('import ') and not any(q in st for q in ('"', "'")): # Python import + 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 - m = _JS_IMPORT.match(t) - if m and not m.group(2).startswith('.'): - for part in re.split(r'[{},]', m.group(1)): - part = part.strip() - if part and part != '*': out.add(part.split(' as ')[-1].strip()) + # 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 @@ -135,13 +181,20 @@ def fillable(names, reader=None, site_file=lambda f: f): 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: seen[f] = imported_names(reader.lines(site_file(f)) if reader else None) + 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 @@ -151,7 +204,7 @@ def keep(row, reason): 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 '') and nm not in imported(_f) + return kind in BARE_VALUE_KINDS and '.' not in (callee or '') return keep diff --git a/tests/fill.py b/tests/fill.py index 1e9877725..81cf8aa49 100644 --- a/tests/fill.py +++ b/tests/fill.py @@ -82,6 +82,11 @@ def check(ok, what): 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: From fdcdbe2ab76724eee413f72fd9f9ef1d00b874cc Mon Sep 17 00:00:00 2001 From: Swapnil <78632212+swapnilpaliwal-sd@users.noreply.github.com> Date: Wed, 18 Nov 2026 17:21:21 -0800 Subject: [PATCH 9/9] fill: the build still ends with `graph at`, and AGENTS.md names unresolved The summary line was printed after `graph at `, which callers read as the build's last line (tests/publish_order.py's one-language control). It now prints just above the warnings and that line. AGENTS.md lists the unresolved tool, and the Gemini skill copy and the Cursor rule are regenerated with packaging/copies.py (tests/manifests.py). --- plugins/axiomcode/AGENTS.md | 2 ++ plugins/axiomcode/rules/axiomcode.mdc | 2 ++ .../skills/axiomcode/scripts/axiomcode-build | 9 +++++---- skills/axiomcode/SKILL.md | 11 +++++++++++ tests/fill.py | 12 ++++++++---- 5 files changed, 28 insertions(+), 8 deletions(-) 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/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/scripts/axiomcode-build b/plugins/axiomcode/skills/axiomcode/scripts/axiomcode-build index e879ac97e..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" @@ -614,7 +619,3 @@ if [ ${#READY[@]} -gt 0 ]; then else echo "graph at $OUT/graph.sqlite" fi -# 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. -python3 "$H/ax_fill.py" "$REPO" --summary 2>/dev/null || true 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/fill.py b/tests/fill.py index 81cf8aa49..44cf0230c 100644 --- a/tests/fill.py +++ b/tests/fill.py @@ -4,7 +4,8 @@ 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 ends with the summary line: 1 site may land in the project, 3 are a library's + 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, @@ -97,9 +98,12 @@ def check(ok, what): 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') - last = [l for l in b.stdout.split('\n') if l.strip()][-1:] or [''] - check(last[0].startswith('graph: ') and '1 may land in the project' in last[0] and "3 a library's method" in last[0], - f'build: the index ends with the summary line (got {last[0][:160]!r})') + 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})")