Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(agentic-ide): read a bounded outline of a file so prompts can name real symbols

Ruben Lütkeb6850ee148dc
diff --git a/jarvis/agentic_ide/code_skeleton.py b/jarvis/agentic_ide/code_skeleton.py
new file mode 100644
index 0000000000..8154b1bfa9
--- /dev/null
+++ b/jarvis/agentic_ide/code_skeleton.py
@@ -0,0 +1,213 @@
+"""A dense outline of a source file, for the prompt composer to read.
+
+The composer used to receive candidate file *paths* and nothing else, which is
+why its prompts said "the ranking logic" where they could have said
+``_fuse_ranked()``. Giving it the files themselves is the fix, but not
+verbatim: a leading excerpt spends most of its tokens on imports and the first
+function's body, and the interesting part of a module — what it offers and
+what it is for — is spread across the whole file.
+
+So what it gets is a skeleton: the module docstring, then every class and
+function signature with the first line of its own docstring. That is roughly
+the table of contents a developer reads first, at a fraction of the tokens.
+
+Safety and bounds, because the user can open ANY folder:
+
+* ``ast.parse`` never executes the file it parses. Nothing here imports,
+ compiles, or runs workspace code.
+* Paths that try to leave the workspace are refused outright, symlinks
+ included.
+* Every read is bounded (per file and in total) and every failure — missing,
+ unreadable, undecodable, syntactically broken — degrades to a smaller
+ result or an empty string, never to an exception. A missing skeleton costs
+ prompt quality; a raised exception would cost the user their instruction.
+"""
+from __future__ import annotations
+
+import ast
+import re
+from collections.abc import Sequence
+from pathlib import Path
+
+# Bounds. Three files is what a spoken instruction realistically points at,
+# and the character budgets keep the composer's own context well clear of the
+# point where a provider would start truncating.
+MAX_SKELETON_FILES = 3
+MAX_CHARS_PER_FILE = 6_000
+MAX_CHARS_TOTAL = 20_000
+
+# Never read more than this off disk before outlining — a "source file" in an
+# arbitrary folder can be a 200 MB generated blob.
+_MAX_SOURCE_BYTES = 400_000
+
+# Lines that look like a declaration in a curly-brace or indentation language.
+# Deliberately shallow: this is the fallback for everything Python's parser
+# cannot read, and a wrong line costs one glance, not a failure.
+_SIGNATURE_RE = re.compile(
+ r"^\s{0,8}(?:export\s+)?(?:default\s+)?"
+ r"(?:public\s+|private\s+|protected\s+|static\s+|abstract\s+|final\s+)*"
+ r"(?:async\s+)?(?:"
+ r"function\b|class\b|interface\b|type\b|enum\b|struct\b|trait\b|impl\b"
+ r"|const\s+\w+\s*[:=]\s*(?:async\s*)?\(|fn\b|func\b|def\b|module\b"
+ r"|(?:public|private|protected)\s+\w+\s+\w+\s*\("
+ r")",
+)
+
+
+def _safe_path(root: str, rel: str) -> Path | None:
+ """``rel`` resolved under ``root``, or None if it escapes the workspace."""
+ if not rel or rel.startswith(("/", "\\")) or ":" in rel[:3]:
+ return None
+ if ".." in rel.replace("\\", "/").split("/"):
+ return None
+ try:
+ base = Path(root).resolve()
+ target = (base / rel).resolve()
+ except (OSError, ValueError):
+ return None
+ # A symlink pointing outside the workspace is the remaining escape route.
+ if base != target and base not in target.parents:
+ return None
+ return target
+
+
+def _read(path: Path) -> str:
+ """File text, or "" when it cannot be read. Never raises."""
+ try:
+ if not path.is_file() or path.stat().st_size > _MAX_SOURCE_BYTES:
+ return ""
+ return path.read_text(encoding="utf-8", errors="replace")
+ except (OSError, ValueError):
+ return ""
+
+
+def _first_docstring_line(node: ast.AST) -> str:
+ try:
+ raw = ast.get_docstring(node) # type: ignore[arg-type]
+ except TypeError:
+ return ""
+ if not raw:
+ return ""
+ return raw.strip().splitlines()[0].strip()
+
+
+def _signature(node: ast.FunctionDef | ast.AsyncFunctionDef) -> str:
+ """The ``def ...`` header as written, collapsed onto one line."""
+ prefix = "async def" if isinstance(node, ast.AsyncFunctionDef) else "def"
+ try:
+ args = ast.unparse(node.args)
+ returns = f" -> {ast.unparse(node.returns)}" if node.returns else ""
+ except Exception: # noqa: BLE001 - unparse is best-effort decoration
+ return f"{prefix} {node.name}(...)"
+ return f"{prefix} {node.name}({args}){returns}"
+
+
+def _python_skeleton(source: str) -> str:
+ """Module docstring plus every top-level and class-level declaration."""
+ try:
+ tree = ast.parse(source)
+ except (SyntaxError, ValueError, RecursionError):
+ return ""
+
+ lines: list[str] = []
+ module_doc = _first_docstring_line(tree)
+ if module_doc:
+ lines.append(f'"""{module_doc}"""')
+
+ def emit(node: ast.AST, indent: str) -> None:
+ if isinstance(node, ast.ClassDef):
+ lines.append(f"{indent}class {node.name}:")
+ doc = _first_docstring_line(node)
+ if doc:
+ lines.append(f'{indent} """{doc}"""')
+ for child in node.body:
+ if isinstance(
+ child, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)
+ ):
+ emit(child, indent + " ")
+ elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
+ lines.append(f"{indent}{_signature(node)}")
+ doc = _first_docstring_line(node)
+ if doc:
+ lines.append(f'{indent} """{doc}"""')
+
+ for node in tree.body:
+ if isinstance(node, (ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)):
+ emit(node, "")
+ elif isinstance(node, ast.Assign):
+ # Module-level constants carry real meaning in this codebase
+ # (bounds, tier tables); their values do not.
+ for target in node.targets:
+ if isinstance(target, ast.Name) and target.id.isupper():
+ lines.append(f"{target.id} = ...")
+
+ return "\n".join(lines)
+
+
+def _lexical_skeleton(source: str) -> str:
+ """Declaration-shaped lines, for everything Python's parser cannot read."""
+ out: list[str] = []
+ for line in source.splitlines():
+ if _SIGNATURE_RE.match(line):
+ out.append(line.rstrip().rstrip("{").rstrip())
+ return "\n".join(out)
+
+
+def skeleton_for(root: str, rel: str, *, max_chars: int = MAX_CHARS_PER_FILE) -> str:
+ """A bounded outline of ``rel`` under ``root``. "" when unavailable."""
+ if max_chars <= 0:
+ return ""
+ path = _safe_path(root, rel)
+ if path is None:
+ return ""
+ source = _read(path)
+ if not source:
+ return ""
+
+ out = ""
+ if path.suffix in {".py", ".pyi"}:
+ out = _python_skeleton(source)
+ if not out:
+ out = _lexical_skeleton(source)
+ if not out:
+ # Neither parser found structure — a config file, a plain document.
+ # Its opening is then the most informative thing about it.
+ out = "\n".join(source.splitlines()[:40])
+
+ return out[:max_chars]
+
+
+def skeletons(
+ root: str,
+ rels: Sequence[str],
+ *,
+ max_files: int = MAX_SKELETON_FILES,
+ max_total: int = MAX_CHARS_TOTAL,
+) -> dict[str, str]:
+ """Outlines for the first ``max_files`` readable paths, within ``max_total``.
+
+ Ordered as given — the file index already ranks by relevance, and the
+ budget should go to the best candidates.
+ """
+ out: dict[str, str] = {}
+ spent = 0
+ for rel in rels:
+ if len(out) >= max_files or spent >= max_total:
+ break
+ text = skeleton_for(
+ root, rel, max_chars=min(MAX_CHARS_PER_FILE, max_total - spent)
+ )
+ if not text:
+ continue
+ out[rel] = text
+ spent += len(text)
+ return out
+
+
+__all__ = [
+ "MAX_CHARS_PER_FILE",
+ "MAX_CHARS_TOTAL",
+ "MAX_SKELETON_FILES",
+ "skeleton_for",
+ "skeletons",
+]
diff --git a/tests/unit/agentic_ide/test_code_skeleton.py b/tests/unit/agentic_ide/test_code_skeleton.py
new file mode 100644
index 0000000000..0eec920c2d
--- /dev/null
+++ b/tests/unit/agentic_ide/test_code_skeleton.py
@@ -0,0 +1,135 @@
+"""Bounded outlines of workspace files, for the prompt composer."""
+from __future__ import annotations
+
+from pathlib import Path
+
+from jarvis.agentic_ide.code_skeleton import (
+ MAX_CHARS_PER_FILE,
+ skeleton_for,
+ skeletons,
+)
+
+_PY = '''\
+"""Ranking pipeline for the wiki."""
+from __future__ import annotations
+
+import math
+
+CONSTANT = 3
+
+
+class Ranker:
+ """Fuses several ranked lists."""
+
+ def fuse(self, lists: list[list[str]], k: int = 60) -> list[str]:
+ """Reciprocal-rank fusion over ``lists``."""
+ return []
+
+ def _private_helper(self) -> None:
+ pass
+
+
+def rank_documents(query: str, limit: int = 10) -> list[str]:
+ """Rank documents for ``query``."""
+ body = query.strip()
+ return [body][:limit]
+'''
+
+
+def test_python_skeleton_names_the_real_symbols(tmp_path: Path):
+ (tmp_path / "pipeline.py").write_text(_PY, encoding="utf-8")
+
+ out = skeleton_for(str(tmp_path), "pipeline.py")
+
+ assert "Ranking pipeline for the wiki." in out
+ assert "class Ranker" in out
+ assert "Reciprocal-rank fusion" in out
+ # The signature carries the name, every parameter with its annotation, and
+ # the return type. Exact spacing is `ast.unparse`'s business, not ours.
+ assert "def fuse(self, lists: list[list[str]], k: int" in out
+ assert "60) -> list[str]" in out
+ assert "def rank_documents(query: str, limit: int" in out
+ assert "10) -> list[str]" in out
+ # Bodies are what we are NOT paying tokens for.
+ assert "return [body][:limit]" not in out
+
+
+def test_broken_python_still_yields_something_useful(tmp_path: Path):
+ (tmp_path / "broken.py").write_text(
+ "def half_written(\n # never closed\n", encoding="utf-8"
+ )
+
+ out = skeleton_for(str(tmp_path), "broken.py")
+
+ assert "half_written" in out
+
+
+def test_non_python_falls_back_to_signature_shaped_lines(tmp_path: Path):
+ (tmp_path / "api.ts").write_text(
+ "import { z } from 'zod'\n"
+ "\n"
+ "export interface Prompt { text: string }\n"
+ "\n"
+ "export async function sendPrompt(name: string): Promise<void> {\n"
+ " const body = JSON.stringify({ name })\n"
+ " await fetch('/api', { body })\n"
+ "}\n",
+ encoding="utf-8",
+ )
+
+ out = skeleton_for(str(tmp_path), "api.ts")
+
+ assert "export interface Prompt" in out
+ assert "export async function sendPrompt" in out
+ assert "JSON.stringify" not in out
+
+
+def test_a_missing_file_is_empty_not_an_error(tmp_path: Path):
+ assert skeleton_for(str(tmp_path), "nope.py") == ""
+
+
+def test_a_path_escaping_the_workspace_is_refused(tmp_path: Path):
+ assert skeleton_for(str(tmp_path), "../outside.py") == ""
+ assert skeleton_for(str(tmp_path), "/etc/passwd") == ""
+
+
+def test_per_file_bound_is_enforced(tmp_path: Path):
+ body = "\n".join(f"def function_{i}(argument: int) -> int: ..." for i in range(4000))
+ (tmp_path / "huge.py").write_text(body, encoding="utf-8")
+
+ out = skeleton_for(str(tmp_path), "huge.py")
+
+ assert len(out) <= MAX_CHARS_PER_FILE
+
+
+def test_skeletons_respects_the_file_count_and_total_bounds(tmp_path: Path):
+ for i in range(6):
+ (tmp_path / f"mod_{i}.py").write_text(
+ f'"""Module {i}."""\n\n\ndef entry_{i}() -> None: ...\n', encoding="utf-8"
+ )
+
+ out = skeletons(
+ str(tmp_path), [f"mod_{i}.py" for i in range(6)], max_files=3, max_total=10_000
+ )
+
+ assert len(out) == 3
+ assert list(out) == ["mod_0.py", "mod_1.py", "mod_2.py"]
+ assert sum(len(v) for v in out.values()) <= 10_000
+
+
+def test_total_bound_stops_before_exceeding(tmp_path: Path):
+ for i in range(3):
+ (tmp_path / f"m{i}.py").write_text(
+ '"""D."""\n\n\ndef f() -> None: ...\n' + ("# pad\n" * 200),
+ encoding="utf-8",
+ )
+
+ out = skeletons(str(tmp_path), ["m0.py", "m1.py", "m2.py"], max_total=120)
+
+ assert sum(len(v) for v in out.values()) <= 120
+
+
+def test_undecodable_bytes_do_not_raise(tmp_path: Path):
+ (tmp_path / "weird.py").write_bytes(b"def f():\n x = '\xff\xfe'\n")
+
+ assert isinstance(skeleton_for(str(tmp_path), "weird.py"), str)