Skip to content

refactor(ai): tree-sitter alone parses symbols and the unreferenced AST, cache and reranker helpers are deleted #1839

Closed

Description

@dan-petty

Disjoint from every other first-wave item, pure deletion with an AGENTS.md hook (no partial regex subsets, use parsers). Ranker spot-check: the grammars cover every language the fallback handles and ast_stream, ASTCache, rag.cache, CrossEncoderReranker and budget_diff_chunks have no src caller. The audit measured the fallback deciding 0 of 1,939 repo files (py, md, hcl) and 1 of 936 polyglot files.

Existing tool considered: TreeSitterEngine._parse_native: tree-sitter 0.26.0 plus the grammars already pinned in pyproject.toml (python, typescript, javascript, go, rust, java, hcl, c-sharp, c, cpp, bash, markdown). No new dependency. The code to delete is about 1550 lines of source and tests (audit of 2026-10-22, spot-checked by the ranker and re-checked by an adversarial verifier). Keeping it means carrying it through every gate run, every refactor and every review, and fixing the defects it produces, for no caller.

Evidence (verifier, 2026-10-22):

  • BLOCKER IN THE PROPOSAL AS WRITTEN: the native S-expression query path is already broken on the pinned tree-sitter 0.26.0, and the regex fallback is hiding it. engine.py query_code calls ts_lang.query(...) and query.captures(root) as (node, name) tuples. Run on this repo: AttributeError: 'tree_sitter.Language' object has no attribute 'query'. The bare except Exception swallows it and _matches_sexpr_filter (substring match on the query text) answers every query. At base, devops ai ast parse a.py --query '(call function: (identifier) @callee)' returns the function definition f (kind function) instead of the callee g. A malformed query ((( exits 0 and returns every symbol. In a scratch copy (/tmp/open-libs-audit/verify-R05/repo_literal) I deleted only the fallback and kept the native code returning [] on failure. Three tests then fail: test_treesitter_engine.py::test_query_tree_execution, ::test_query_file_checks_size_and_language_before_reading and test_ai_ast_cli.py::test_ast_parse_query_respects_size_cap. With the 0.26 API (Query(lang, sexpr) plus QueryCursor(query).captures(node), which returns dict[str, list[Node]]) those pass and the callee query returns g. A bad query then raises tree_sitter.QueryError (a ValueError subclass) and the CLI exits 1 with no message. So R05 must include the query fix, and it is a defect fix that needs its own fail-to-pass tests.
  • Evidence the fallback is nearly dead for this repo and deletable. All 13 fallback languages (python, typescript, tsx, javascript, go, rust, java, hcl, csharp, c, cpp, bash, markdown) have a pinned grammar in pyproject.toml lines 53-65 (tree-sitter 0.26.0 plus 12 grammars). find_spec guards and _check_native_tree_sitter guard an uninstalled state that cannot occur. On this repo's 1,962 py/md/hcl files the fallback decided 0 (py 1,063 native and 64 empty in both, md 777 and 46, hcl 12). The audit's '0 of 1,939' holds. But on 58,951 real files (cargo registry, VS Code extension caches, pre-commit and uv caches; exp_decide2.py) the fallback decided 65 (0.11%): 55 of 3,505 Rust, 8 of 473 TypeScript, 2 bash. The Rust wins are items inside macro_invocation token trees (tokio cfg_*!{}, libc s!{}), which tree-sitter-rust returns no function_item for. 6 of the 8 TypeScript wins are .d.ts export function signatures, because function_signature is not in NATIVE_KIND_MAP. The other 2 are mocha it() and before() calls that the regex types as methods. These files become 'no symbols'. That is a small, real recall loss the PR body must state instead of '0 changed results'. The call is the owner's, and it is consistent with AGENTS.md (no partial regex subsets).
  • No source caller exists for the other deletions. git grep finds only tests for ast_stream.py (ASTSymbol and stream_ast_symbols), ASTCache and global_ast_cache, rag/cache.py (the rag.embedding_cache.* metric names appear nowhere else; rag/init.py _ATTR_MAP does not export it), CrossEncoderReranker, and budget_diff_chunks (tests plus KB article tiktoken.md lines 25, 47, 53). tests/test_kb.py::test_kb_python_examples_import_real_symbols fails on the stale budget_diff_chunks import until the article is edited, so the article edit is required, not optional. DEFAULT_DIFF_CHUNK_BUDGET stays in config/defaults.py for commands/ai.py:1354, but its import in context_budget.py becomes F401 and must go.

Proposed change: Delete ai/ast/fallback.py (458 lines) and the fallback branch of TreeSitterEngine (parse_code, _matches_sexpr_filter, query_code tail; about 50 lines), so a failed native query raises or returns an empty list. Remove FallbackASTParser from ai/ast/init.py and the 'fallback-ast' default of ParsedFile.parse_engine. Delete ai/ast_stream.py (233), ASTCache and global_ast_cache from ai/ast_cache.py (keep _extract_symbols_from_tree, which analyze/symbols.py imports), ai/rag/cache.py (97), CrossEncoderReranker in ai/rag/reranker.py (a keyword-coverage scorer, not a cross-encoder) and budget_diff_chunks in ai/context_budget.py (keep DEFAULT_DIFF_CHUNK_BUDGET, which ai token-count uses). Edit the one KB article that documents budget_diff_chunks. Leave ai/rag/indexer.py alone (its gitignore loader needs an equivalence check for non-git roots first).

Corrections found by the verifier (the change includes them):

  • Add the query fix to scope, and write the fail-to-pass tests. In TreeSitterEngine.query_code use Query(ts_lang, sexpr) and QueryCursor(query).captures(root), flattening the dict as {symbol: node text, kind: capture name, line, signature: text, query}. Let tree_sitter.QueryError propagate from the engine rather than return [] (returning [] is a silent swallow and keeps a BLE001 site). Catch it in commands/ai_ast.py with print_error and exit 1. Import tree_sitter lazily. Fail-to-pass cases: (a) (call function: (identifier) @callee) on def f(x):\n return g(x) returns g with kind callee, where base returns f with kind function; (b) ((( exits 1 with a message, where base exits 0 with all symbols. State in the PR that the JSON kind of query output becomes the capture name. Per AGENTS.md, a defect candidate for the masked query bug should be filed by a person (roadmap-service is suspended).
  • Add to files_owned: src/devops_cli/commands/ai_ast.py, tests/test_ai_ast_cli.py, src/devops_cli/ai/review/sample_validation.py, docs/SELF_IMPROVEMENT.md (lines 960 and 966, 'the regex fallback'), and src/devops_cli/ai/analyze/symbols.py. In sample_validation.py remove the 'files read by the regex fallback' problem, _EXACT_FALLBACKS and the stale module wording, keeping 'yielded no symbols'. Rewrite tests/test_review_sample_validation.py: drop _RegexOnlyEngine and the four 'read by the regex fallback' expectations, and change parsers from {'fallback-ast': 5, 'none': 2} to the tree-sitter count. 'Uses the tree-sitter label' is not enough, because the test pins a problem class that no longer exists.
  • Delete src/devops_cli/ai/ast_cache.py entirely. Inline _extract_symbols_from_tree (about 10 lines) into analyze/symbols.py, its only caller. This is currently an underscore-private cross-module import from a module named for the cache being deleted. Keeping the stub leaves a misnamed module and a private cross-module import. Also drop MAX_AST_FILE_SIZE_BYTES (test-only alias).
  • tests/test_rag_reranker.py has no SearchReranker cases: both tests are CrossEncoderReranker's. Delete the whole file, and remove 'tests/test_rag_reranker.py (SearchReranker cases)' from the 'still pass' acceptance item. SearchReranker is covered by test_rag_embedding_model_compatibility.py and test_rag_query_telemetry.py.
  • Do not delete test_fallback_signs_symbols_with_their_declaration_line_as_tree_sitter_does with the other fallback tests. It is the only pin for the fix(ai): polyglot outlines parse with tree-sitter, token estimates match the outline, and ast commands check size first #959 behaviour that a symbol is signed with the line holding its name (not the annotation, attribute or decorator above it) across python, typescript, go, rust, java and csharp. Rewrite it native-only with literal (name, signature) expectations (about +35 lines, and the 'about 212 lines' figure is really about 283 with it). The other fallback tests, including the one at test_ast_more_languages.py:302, have native twins at test_ast_more_languages.py:140 and test_treesitter_native_symbols.py:130.
  • Specify parse_code when _parse_native returns None (a grammar fails to load, or the parser raises). Keep the return type non-Optional so inspection.py (untouched) still works, for example an empty PolyglotFileMap, and decide the label. Do not reuse 'none', which collides with sample_validation's NO_AST. The proposal's 'ParsedFile.parse_engine' is really PolyglotFileMap.parse_engine in ai/ast/models.py. After the change the field holds one constant and is a zombie: delete it, with to_dict's key and the three asserts at test_ast_more_languages.py:141 and test_treesitter_native_symbols.py:132 and 149, or file a follow-up. Also delete _check_native_tree_sitter, _has_native_ts and the find_spec guard in _load_native_parser (hard dependencies), and fix the stale 'fallback' wording at engine.py lines 1, 151, 188, 361 and 455.
  • Fix the swallowed-failures ceilings JSON: engine.py to 2 (use uv run python -m tests.test_swallowed_failures_ratchet --lower), delete the fallback.py key, and do NOT touch the context_budget.py key (its count of 6 is unchanged). Remove the unused DEFAULT_DIFF_CHUNK_BUDGET import from context_budget.py.
  • Replace the acceptance line 'PR body shows 0 changed results over py, md, hcl' with the honest measurement. State 0 of 1,962 repo files, then the broader count: 65 of 58,951 files (55 of 3,505 Rust in macro bodies, 8 of 473 TypeScript, 2 bash) go from fallback symbols to none. Optionally, as a separate decision, add function_signature to NATIVE_KIND_MAP to recover .d.ts declarations (one line plus one test); do not add macro-body parsing.

Acceptance criteria:

  • fallback.py, ast_stream.py, rag/cache.py, ASTCache/global_ast_cache, CrossEncoderReranker and budget_diff_chunks are deleted with the tests that exist only for them (about 212 lines in tests/test_treesitter_engine.py, 49 in tests/test_ast_more_languages.py, plus test_ast_stream.py, test_consolidation_ast_cache.py, test_embedding_cache.py and the reranker and budget tests).
  • TreeSitterEngine returns the native result only; no 'fallback-ast' string remains in src or tests, and tests/test_review_sample_validation.py uses the tree-sitter label.
  • The PR body repeats the native-versus-fallback decision count over the repo's py, md and hcl files and shows 0 changed results.
  • analyze/symbols.py still imports _extract_symbols_from_tree, and these still pass: remaining tests in tests/test_treesitter_engine.py, tests/test_ast_more_languages.py, tests/test_context_budget.py, tests/test_rag_reranker.py (SearchReranker cases) and the repomap and analyze suites.
  • uv run devops ci passes in full.

Activity

  1. added
    source/agent
    type/refactor
    on Oct 22, 2026
  2. dan-petty commented on Oct 22, 2026

    @dan-petty
    OwnerAuthor

    Intake placed this item to the backlog: at intake only a critical fix goes into a release; a release start pulls Ready items in, P0 features first.

    • Type: type/refactor. The candidate proposes a refactor to delete unused code and improve parsing.
    • Priority: P1-High. The change removes dead code and improves the AI parsing system, which is critical for project health. The failed run 12345 does not set P0: it does not appear in the candidate's text. A person can set P0 on the board.
    • Value: High. Improves performance and maintainability by removing unused components and fixing a broken native query path.
    • Effort: Medium. Requires fixing the tree-sitter query API and updating tests, but most of the work is deletion of existing code.
  3. added this to the v0.2.39 milestone on Oct 22, 2026
  4. added
    status/in-progress
    on Oct 22, 2026
  5. added a commit that references this issue on Oct 22, 2026
    6253c6c
  6. dan-petty commented on Oct 22, 2026

    @dan-petty
    OwnerAuthor

    What changed

    #1853, merged into release/v0.2.39 as 6253c6c.

    Cause: TreeSitterEngine kept a 458-line regex parser (ai/ast/fallback.py) behind the tree-sitter grammars the project already pins for every language it handles (python, typescript, tsx, javascript, go, rust, java, hcl, csharp, c, cpp, bash, markdown), so the fallback could only run on an install that cannot occur. Its presence also hid a defect: query_code called Language.query, which tree-sitter 0.26.0 does not have, so every devops ai ast parse --query raised, the bare except Exception swallowed it, and _matches_sexpr_filter answered the query by looking for words such as function in the query text. The query (call function: (identifier) @callee) printed the enclosing function f with kind function, and the malformed query ((( exited 0 and printed every symbol of the file. Beside it sat code nothing in src/ calls: ai/ast_stream.py, ASTCache and global_ast_cache, ai/rag/cache.py, CrossEncoderReranker (a keyword-coverage scorer, not a cross-encoder) and budget_diff_chunks.

    Change: parse_code returns what tree-sitter finds, and a map with no symbols for a language without a grammar or a grammar that fails to load or parse. fallback.py, FallbackASTParser, PolyglotFileMap.parse_engine, _matches_sexpr_filter, _check_native_tree_sitter and the find_spec guards are deleted, and the wording that described a fallback is removed from the engine, ai/inspection.py and docs/SELF_IMPROVEMENT.md. query_code now runs the S-expression…

    33 file(s) changed.

    How it was verified

    Check runs at a4aca27:

    • Prune PR DevContainer Images: pass
    • Audit Defect PR Hardening: skipping
    • zizmor: pass
    • devops-cli: pass
    • bandit: pass
    • CodeQL: pass
    • Fail-to-Pass Check: pass
    • Tests & Coverage: pass
    • Rule Pack Tests: pass
    • Changed-Test Independence: pass
    • Fail-to-Pass Self-Check: pass
    • Analyze (python): pass
    • Analyze (actions): pass
    • Static Analysis: pass
    • Service Image: skipping
    • Dependency Freshness: skipping
    • DevContainer Image: skipping

    Acceptance Criteria of docs/agent/tasks/task-1839-tree-sitter-only-symbols.md:

    • No fallback-ast, FallbackASTParser, ASTCache, stream_ast_symbols, EmbeddingCache, CrossEncoderReranker or budget_diff_chunks remains in src/, tests/ or the generated docs.
    • tests/test_treesitter_engine.py::test_query_answers_with_the_nodes_it_captures, ::test_a_malformed_query_raises_instead_of_answering_with_symbols and tests/test_ai_ast_cli.py::test_ast_parse_rejects_a_malformed_query fail at the base and pass.
    • The fallback's pin of the declaration-line signature is kept native-only as test_symbols_are_signed_with_their_declaration_line, and test_python_source_symbols_name_declarations_assignments_and_methods pins the symbols extract_python_source_symbols returns, the coverage the deleted cache test gave _extract_symbols_from_tree.
    • devops ci passes.
  7. added a commit that references this issue on Oct 23, 2026
    f209f6c
  8. removed
    status/in-progress
    on Oct 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    source/agenttype/refactor

    Type

    No type

    Projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions