Skip to content

fix(ai): polyglot outlines parse with tree-sitter, token estimates match the outline, and ast commands check size first #959

Closed

Description

@dan-petty

Problem

The devsecops review session 20261001-224227 (2026-10-02, a path review of the whole repository with local models) raised 563 findings. A triage of every finding against release/v0.2.25 (c279c18) judged 489 false. Each of the 4 defects below was confirmed with code evidence and then upheld by a second agent that tried to refute it. The severities are re-rated; the review's own ratings were inflated.

Incomplete TypeScript Function Signature Parsing (src/devops_cli/ai/ast/fallback.py:147, LOW, correctness)

  • Defect: The claim that parameter types are dropped is wrong: (.*?) captures x: string, y: number. The resulting signature is still materially incomplete, though, and it reaches output. The fallback stores signature=f"({m_fn.group(2)})" (fallback.py:147, and the same pattern at 160/186/196/238/299), which has no name and no return type. The native engine stores the whole declaration line (sig = lines[start_pt[0]].strip(), engine.py:417), so PolyglotSymbol.signature means different things depending on which engine produced it. inspection.py uses FallbackASTParser directly for every non-Python file (lines 543/592/668), and _build_polyglot_structural emits sig = sym.signature or ... as the skeleton line (inspection.py:611). Reproduced: generate_semantic_outline(m.ts, STRUCTURAL) for export function a(x: string, y: number): Promise<void> renders the skeleton `' (x: string, y: …
  • Skeptic's ruling: The literal claim is wrong: (.*?) keeps the parameter types. The return-type omission it describes is real, though, and the output is worse than it says. The fallback stores signature=f"({m_fn.group(2)})" (fallback.py; same pattern for TS methods, Go, Rust and Java), and inspection.py builds every non-Python outline with FallbackASTParser directly, not TreeSitterEngine. _build_polyglot_structural emits sym.signature as the skeleton line, and _render_structural_markdown prints only …
  • Fix: In inspection.py, route _build_polyglot_topology, _build_polyglot_structural and _find_symbol_or_lines_range through one TreeSitterEngine().parse_code(content, lang, str(path)); it already falls back to the regex parser. Also make FallbackASTParser store signature=line.strip(), the declaration line, as _extract_native_symbols does, so the two engines agree on what a signature is.
  • Regression test: tests/test_ai_inspection.py::test_polyglot_structural_skeleton_keeps_names_and_return_types: write service.ts containing export function a(x: string, y: number): Promise<void> {}. Call generate_semantic_outline(..., level=FocalLevel.STRUCTURAL, repo_root=tmp_path) and assert 'a(' in raw_skeleton and 'Promise' in raw_skeleton. Today the skeleton is ' (x: string, y: number)'.

Rust Method Pattern Matching May Miss Some Valid Declarations (src/devops_cli/ai/ast/fallback.py:225, LOW, correctness)

  • Defect: RE_RS_FN = re.compile(r"^\s*(?:pub(?:\(.*?\))?\s+)?(?:async\s+)?fn\s+([A-Za-z0-9_]+)\s*\((.*?)\)") requires ( immediately after the name. Verified that it does not match pub fn process<T: Clone>(x: T) -> T {, pub async fn f<'a>(...), const fn c(), unsafe fn u() or pub unsafe extern "C" fn g(). (Likewise, RE_TS_FUNC misses function f<T>(...) and export default function.) This matters because inspection.py parses all non-Python files with FallbackASTParser directly (lines 543, 592, 668), not with TreeSitterEngine. Reproduced on lib.rs: the Level-1 outline lists only plain, and --symbol process falls back to the default line range (symbol_name='process', lines 1-5, breadcrumbs just lib.rs). Agents using devops ai read or MCP ai_read therefore never see generic or qualified Rust functions.
  • Skeptic's ruling: Reproduced. RE_RS_FN requires ( straight after the name and allows only pub/async qualifiers, so it misses pub fn process<T: Clone>(x: T) -> T, pub const fn c() and unsafe fn u(). Because inspection.py uses FallbackASTParser directly for non-Python files, a lib.rs with plain/process/c/u gives Level-0 functions ['plain'] and a Level-1 skeleton of just ' (x: i32)'. --symbol process (DEEP_FOCAL) silently falls back to lines 1-6 with breadcrumbs 'lib.rs'. …
  • Fix: Same change as idx 156: inspection's polyglot builders and the symbol-range finder use TreeSitterEngine.parse_code, whose native Rust and TS grammars handle generics and qualifiers. Also harden the fallback: ^\s*(?:pub(?:\([^)]*\))?\s+)?(?:(?:const|async|unsafe|extern\s+"[^"]*")\s+)*fn\s+([A-Za-z0-9_]+)\s*(?:<[^>]*>)?\s*\((.*?)\), and allow (?:<[^>]*>)? before ( in RE_TS_FUNC as well as an export default prefix.
  • Regression test: tests/test_ai_inspection.py::test_rust_outline_finds_generic_const_unsafe_fns: write lib.rs with pub fn plain(x: i32) -> i32 { x }, pub fn process<T: Clone>(x: T) -> T { x }, pub const fn c() -> u8 { 1 } and unsafe fn u() {}. Assert the TOPOLOGY function names are {'plain','process','c','u'}, and that DEEP_FOCAL with symbol='process' gives focal_window.line_start == 2 with 'process' in scope_breadcrumbs. Today only 'plain' is found and the focal window is lines 1-6. Add a fallback-only …

Token Estimation in Topology Outline May Underestimate Actual Tokens (src/devops_cli/ai/inspection.py:348-350, LOW, correctness)

  • Defect: text_repr = f"classes: {len(classes)}, functions: {len(functions)}, exports: {len(exports)}"; est_tokens = estimate_tokens(text_repr) + (total_syms * 6). The polyglot path does the same: est_tokens = max(1, total_syms * 6) at :578. The structural and focal levels count the text they actually emit (estimate_tokens(raw_skel), estimate_tokens(focal_text)). Topology instead guesses, ignoring the docstrings, bases, method lists, exports and hotspots that _render_topology_markdown outputs. Measured at c279c18: inspection.py reported 279 tokens against 1317 for the rendered markdown (96.48% reduction claimed); workflow.py 81 against 555 (99.05%); settings.py 423 against 1593 (96.05%). outline_tokens and token_reduction_pct are shown by devops ai read --inspect and returned to MCP clients, so the reported savings are inflated. The finding's proposed fix (multiplier 10) is still …
  • Skeptic's ruling: Confirmed at c279c18. _build_python_topology sets est_tokens = estimate_tokens("classes: N, functions: M, exports: K") + total_syms * 6, and _build_polyglot_topology uses max(1, total_syms * 6). generate_semantic_outline reports this guess as outline_tokens, and token_reduction_pct is computed from it. Neither looks at what _render_topology_markdown actually emits: docstrings, bases, the method lists, exports and hotspots. The structural and focal levels, by contrast, measure …
  • Fix: In generate_semantic_outline, after building the topology, render it once with the same functions _render_topology_markdown uses (the classes, functions and hotspots sections plus the exports line). Set topology.estimated_tokens = outline_tokens = estimate_tokens(rendered). For consistency, the structural level could also count the fenced block it renders. Delete the text_repr/total_syms * 6 heuristic in both _build_python_topology and _build_polyglot_topology, or have those builders return 0 and let the caller measure. Then update the hard-coded < 200 bound in test_level_0_topology_outline against the measured value.
  • Regression test: Add tests/test_ai_inspection.py::test_topology_outline_tokens_match_rendered_markdown. Write the SAMPLE_HOTSPOT_PYTHON fixture (whose docstrings and methods make the rendered text much longer than the heuristic), call generate_semantic_outline(..., level=FocalLevel.TOPOLOGY), and assert abs(outline.outline_tokens - estimate_tokens(_render_topology_markdown(outline))) <= max(5, 0.1 * estimate_tokens(...)). Add the same assertion for a small .ts or .go file through the polyglot path. Both …

Potential Tree-Sitter Parser Denial of Service via Large Input (src/devops_cli/commands/ai_ast.py:56, LOW, reliability)

  • Defect: The finding's literal location is mostly mitigated, but the DoS cap it asks for really is skipped on one path. TreeSitterEngine.parse_file enforces stat.st_size > self.max_file_size_bytes (engine.py:482; DEFAULT_MAX_AST_FILE_SIZE_BYTES = 50MB # 50MB DoS protection limit). Every other caller goes through parse_file: graph.py:101, repomap.py:222, sample_validation.py:111. ast_parse_cmd with --query instead runs code = file_path.read_text(...) then engine.query_code(code, ...) (ai_ast.py:55-57). That path reads the whole file and passes it to parser.parse(bytes(code, "utf-8")) (engine.py:518) and then to parse_code → _parse_native, with no size check. It is reachable from an untrusted MCP client: ai_ast_parse(file_path, query) (mcp/server.py:1001) only rejects a leading hyphen. In-process dispatch (InProcessDispatcher._dispatch_typer, dispatcher.py:232-251) also …
  • Skeptic's ruling: Could not refute it; I reproduced it. ast_parse_cmd checks the size cap only on the parse_file branch (engine.py, stat.st_size > self.max_file_size_bytes). The --query branch runs file_path.read_text() and then engine.query_code(), which runs parser.parse(bytes(code,'utf-8')) with no size check. With the engine capped at 100 bytes, ai ast parse big.py exits 1 ('file size exceeded'), but ai ast parse big.py --query '(function_definition name: (identifier) @n)' exits 0 and returns …
  • Fix: Add TreeSitterEngine.query_file(path, sexpr). It stats the path, returns None or raises above self.max_file_size_bytes (sharing parse_file's guard and the .h language detection), and only then reads the file and calls query_code. Have ast_parse_cmd call it, and on a None or too-large result print the same 'Unsupported language or file size exceeded' error with exit 1. Optionally run both branches through inspection's _validate_inspect_path so traversal and forbidden-path checks also apply.
  • Regression test: tests/test_ai_ast_cli.py::test_ast_parse_query_respects_size_cap: write a ~1 KB .py file containing def f(x): .... Monkeypatch devops_cli.commands.ai_ast.TreeSitterEngine to lambda: TreeSitterEngine(max_file_size_bytes=100). Invoke ai ast parse <file> --query '(function_definition name: (identifier) @n)'. Assert exit_code == 1 and no JSON matches in the output. Today it exits 0 and prints the match for f.

Acceptance criteria

  • Each defect above is fixed as its Fix line describes, or the PR says why another fix is better.
  • Each has its Regression test: offline, failing on the base revision and passing after the fix.
  • Removed code goes without shims (pre-1.0), and docs that described it are corrected.
  • uv run devops ci passes.

Key questions

  • One PR for all of these? Yes (proposed). They share a module area and none needs a design decision; each fix is small.

Activity

  1. added this to the v0.2.25 milestone on Oct 2, 2026
  2. added
    type/bug
    scope/ai
    priority/p3-low
    on Oct 2, 2026
  3. dan-petty commented on Oct 3, 2026

    @dan-petty
    OwnerAuthor

    Closed by #1076, merged into release/v0.2.25.

    GitHub only acts on closing keywords when a pull request merges into the default branch, so this was closed by devops gh issues close-merged.

  4. added a commit that references this issue on Oct 3, 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

    priority/p3-lowscope/aitype/bug

    Type

    No type

    Projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions