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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(agentic-ide): look inside the key files before writing a terminal brief
rubenluetke10-beep52c6512231c3
diff --git a/jarvis/agentic_ide/code_skeleton.py b/jarvis/agentic_ide/code_skeleton.pyindex 3faa4b7e9b..d79cce9f7b 100644--- a/jarvis/agentic_ide/code_skeleton.py+++ b/jarvis/agentic_ide/code_skeleton.py@@ -156,6 +156,12 @@ def _lexical_skeleton(source: str) -> str:return "\n".join(out)+def read_source(root: str, rel: str) -> str:+ """The text of ``rel`` under ``root`` within the same bounds, or ""."""+ path = _safe_path(root, rel)+ return _read(path) if path is not None else ""++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:@@ -163,12 +169,16 @@ def skeleton_for(root: str, rel: str, *, max_chars: int = MAX_CHARS_PER_FILE) ->path = _safe_path(root, rel)if path is None:return ""- source = _read(path)- if not source:+ return outline_source(rel, _read(path), max_chars=max_chars)+++def outline_source(rel: str, source: str, *, max_chars: int = MAX_CHARS_PER_FILE) -> str:+ """The outline of already-read ``source``; ``rel`` only decides the parser."""+ if max_chars <= 0 or not source:return ""out = ""- if path.suffix in {".py", ".pyi"}:+ if Path(rel).suffix in {".py", ".pyi"}:out = _python_skeleton(source)if not out:out = _lexical_skeleton(source)@@ -211,6 +221,8 @@ __all__ = ["MAX_CHARS_PER_FILE","MAX_CHARS_TOTAL","MAX_SKELETON_FILES",+ "outline_source",+ "read_source","skeleton_for","skeletons",]diff --git a/jarvis/agentic_ide/file_index.py b/jarvis/agentic_ide/file_index.pyindex 1b7564d4c4..e77073c5c0 100644--- a/jarvis/agentic_ide/file_index.py+++ b/jarvis/agentic_ide/file_index.py@@ -17,6 +17,9 @@ Design constraints that shaped it:* **Bounded, always.** A user can open ANY folder, including a home directory ora network share. The walk carries a hard file budget, a depth limit, and theshared skip list, so the worst case is a truncated index, never a hang.+* **Git first.** In a checkout the file list comes from ``git ls-files``, so+ gitignored data, caches and build output never crowd the code out. Without+ git, or outside a checkout, the bounded walk stands in.* **Lexical, not semantic.** Matching is token overlap against path segments andfile stems. No embedding, no model call — it must work on a machine with noAPI key at all, and a wrong suggestion costs the agent one glance.@@ -31,10 +34,14 @@ from __future__ import annotationsimport osimport re+import shutil+import subprocessimport threadingfrom dataclasses import dataclass, fieldfrom pathlib import Path+from loguru import logger+from .folders import _SKIP_DIRS# Hard bounds. 30k files covers a large monorepo; past that the tail is noise@@ -575,8 +582,94 @@ def _entry_size(item: os.DirEntry[str]) -> int:return 0+def _make_entry(rel: str, name: str, size: int) -> _Entry:+ stem = os.path.splitext(name)[0]+ parent = rel.rsplit("/", 1)[0] if "/" in rel else ""+ return _Entry(+ rel=rel,+ stem_tokens=frozenset(tokenize(stem)),+ path_tokens=frozenset(tokenize(parent)) | frozenset(tokenize(stem)),+ is_test=(+ "test" in rel.lower().split("/")[0]+ or stem.lower().startswith("test_")+ or stem.lower().endswith(("_test", ".test", ".spec"))+ ),+ is_doc=_is_doc(rel, name),+ dir_names=frozenset(part.lower() for part in parent.split("/") if part),+ size=size,+ )+++_GIT_TIMEOUT_S = 15.0+++def _git_paths(base: Path) -> list[str] | None:+ """Tracked plus untracked-but-not-ignored files, or None without git.++ A checkout's runtime data, caches and build output are gitignored, and in+ a walk they crowd the code out: measured on this repository 2026-10-01,+ 21 000 of the 30 000 indexed files came from two ignored data folders and+ the walk stopped at its cap. Git already knows which files are the+ project. The walk below stays the fallback for folders that are no+ checkout or machines without git.+ """+ try:+ if not (base / ".git").exists():+ return None+ except OSError: # an unreadable folder is no checkout; the walk decides+ return None+ git = shutil.which("git")+ if not git:+ return None+ from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS++ try:+ proc = subprocess.run(+ [git, "-C", str(base), "ls-files", "-z", "--cached", "--others", "--exclude-standard"],+ capture_output=True,+ timeout=_GIT_TIMEOUT_S,+ creationflags=NO_WINDOW_CREATIONFLAGS,+ check=False,+ )+ except (OSError, subprocess.SubprocessError) as exc:+ logger.debug("Agentic IDE file index: git ls-files failed in {}: {}", base, exc)+ return None+ if proc.returncode != 0:+ return None+ return [p for p in proc.stdout.decode("utf-8", errors="replace").split("\0") if p]+++def _index_from_git(base: Path, paths: list[str]) -> FileIndex:+ """The index built from git's file list, under the walk's own rules."""+ index = FileIndex(root=str(base))+ for raw in paths:+ if len(index.entries) >= _MAX_FILES:+ index.truncated = True+ break+ rel = raw.replace("\\", "/")+ if rel.endswith("/"):+ continue # an untracked nested checkout; never one file to point at+ parts = rel.split("/")+ dirs, name = parts[:-1], parts[-1]+ if len(dirs) > _MAX_DEPTH or not _is_interesting(name):+ continue+ if any(+ part in _SKIP_DIRS+ or part in _COPY_DIRS+ or (part.startswith(".") and part not in _KEEP_HIDDEN)+ for part in dirs+ ):+ continue+ try:+ size = (base / rel).stat().st_size+ except OSError:+ continue # deleted since git listed it+ index.entries.append(_make_entry(rel, name, size))+ return index++def build_index(root: str | Path) -> FileIndex:- """Walk ``root`` once and return its bounded file index.+ """List ``root`` once and return its bounded file index.Blocking by design — callers run it in a worker thread (see ``index_for``)."""@@ -588,6 +681,10 @@ def build_index(root: str | Path) -> FileIndex:except OSError:return index+ listed = _git_paths(base)+ if listed is not None:+ return _index_from_git(base, listed)+stack: list[tuple[Path, int]] = [(base, 0)]while stack:current, depth = stack.pop()@@ -618,23 +715,7 @@ def build_index(root: str | Path) -> FileIndex:except OSError:continuerel = os.path.relpath(item.path, base).replace(os.sep, "/")- stem = os.path.splitext(name)[0]- parent = rel.rsplit("/", 1)[0] if "/" in rel else ""- index.entries.append(- _Entry(- rel=rel,- stem_tokens=frozenset(tokenize(stem)),- path_tokens=frozenset(tokenize(parent)) | frozenset(tokenize(stem)),- is_test=(- "test" in rel.lower().split("/")[0]- or stem.lower().startswith("test_")- or stem.lower().endswith(("_test", ".test", ".spec"))- ),- is_doc=_is_doc(rel, name),- dir_names=frozenset(part.lower() for part in parent.split("/") if part),- size=_entry_size(item),- )- )+ index.entries.append(_make_entry(rel, name, _entry_size(item)))except (PermissionError, OSError):continuereturn indexdiff --git a/jarvis/agentic_ide/file_peek.py b/jarvis/agentic_ide/file_peek.pynew file mode 100644index 0000000000..cfec3541b8--- /dev/null+++ b/jarvis/agentic_ide/file_peek.py@@ -0,0 +1,287 @@+"""A short look inside the files a brief is about to point at.++The tree index matches spoken words against file NAMES. That finds the right+neighbourhood, but a writer that has only seen names can do no better than+"the ranking logic" and cannot tell which of five similarly named files+actually holds the behaviour. A developer handing work to a colleague glances+into the two or three files that matter first; this module is that glance.++What it does, per composition, all in one worker thread and all bounded:++* **Reads the name candidates** (a small pool, never the repository) and+ re-ranks them by how many of the task's own words occur in their CONTENT, so+ the file that really implements "the wake timeout" beats the one that merely+ has "wake" in its name.+* **Excerpts the top few**: the outline (module docstring, signatures, first+ docstring lines, constants) plus the lines that mention the task's words,+ with line numbers. That is enough for the writer to name a real symbol and+ state where a value lives, without pasting the module.++How deep it looks depends on the task (``task_kind``). An investigation, a+review or a question is ABOUT the code, so the writer gets more files and more+lines; an implementation gets the entry points; an undetermined request gets a+light glance. Nothing here executes workspace code (``ast.parse`` only), every+read is size-bounded, and the whole pass carries a wall-clock deadline so a+slow network share costs excerpts, never the turn.+"""++from __future__ import annotations++import math+import time+from collections.abc import Sequence+from dataclasses import dataclass, field+from pathlib import PurePosixPath++from .code_skeleton import outline_source, read_source+from .file_index import tokenize+from .task_kind import (+ KIND_IMPLEMENT,+ KIND_INVESTIGATE,+ KIND_NEUTRAL,+ KIND_QUESTION,+ KIND_REVIEW,+)+++@dataclass(frozen=True, slots=True)+class PeekPlan:+ """How far to look for one kind of task."""++ pool: int+ """Name candidates read and re-ranked by content."""+ files: int+ """How many of the re-ranked files get an excerpt."""+ chars_per_file: int+ total_chars: int+ hit_lines: int+ """Task-relevant lines quoted per file."""+++# Sized against the writer's budget: every excerpt character is input the fast+# writer reads before it answers, and the spoken path waits for that answer.+#+# The pool is wide on purpose. Names alone put the right file outside a narrow+# pool: measured 2026-10-01, "why does prompting a terminal take so long in+# the agentic ide composer" ranked ``prompt_composer.py`` 24th by name, behind+# every frontend file in a folder called ``agentic``. Reading 30 bounded files+# costs about a tenth of a second; the content then decides.+_DEEP = PeekPlan(pool=30, files=4, chars_per_file=2_400, total_chars=8_000, hit_lines=8)+_PLANS: dict[str, PeekPlan] = {+ KIND_INVESTIGATE: _DEEP,+ KIND_REVIEW: _DEEP,+ KIND_QUESTION: _DEEP,+ KIND_IMPLEMENT: PeekPlan(+ pool=24, files=3, chars_per_file=2_000, total_chars=5_500, hit_lines=5+ ),+ KIND_NEUTRAL: PeekPlan(+ pool=12, files=2, chars_per_file=1_500, total_chars=3_000, hit_lines=4+ ),+}++# The whole pass, reads included. Disk on a local SSD answers in milliseconds;+# this bound exists for a network share or a cold spinning disk.+PEEK_DEADLINE_S = 0.4+# Outlining the top files after reading: measured 9-40 ms per file warm.+EXCERPT_WINDOW_S = 0.25++_MAX_LINE_CHARS = 160++# The whole outline is built before it is focused, so the task's function is+# found even at the end of a 7 000-line module. Text only, never sent as is.+_FULL_OUTLINE_CHARS = 120_000++# Files that style, configure or store data rather than behave. They mention+# every word under the sun ("index", "terminal") and are rarely where a coding+# task starts, so they rank below code unless the task names their kind.+_LOW_VALUE_SUFFIXES = frozenset(+ {".css", ".scss", ".json", ".html", ".txt", ".csv", ".svg", ".lock", ".yaml", ".yml"}+)+_LOW_VALUE_FACTOR = 0.4++# Lines that name a dependency or print a message, not behaviour — they match+# the task's words constantly ("from .wake import ...", a log line naming the+# subsystem) and tell the writer nothing.+_IMPORT_PREFIXES = (+ "import ",+ "from ",+ "#include",+ "using ",+ "require(",+ "logger.",+ "log.",+ "logging.",+ "console.",+ "print(",+)+++def plan_for(kind: str) -> PeekPlan:+ """The depth for ``kind``; unknown kinds get the light glance."""+ return _PLANS.get(kind, _PLANS[KIND_NEUTRAL])+++@dataclass(slots=True)+class Peek:+ """What the glance found."""++ ranked: list[str] = field(default_factory=list)+ """The candidates, best first, after looking inside them."""+ excerpts: dict[str, str] = field(default_factory=dict)+ """Path → outline plus task-relevant lines, for the top files only."""+++def _hit_lines(source: str, wanted: set[str], limit: int) -> list[str]:+ """Up to ``limit`` numbered lines that mention the most task words."""+ if limit <= 0 or not wanted:+ return []+ scored: list[tuple[int, int, str]] = []+ for number, line in enumerate(source.splitlines(), start=1):+ stripped = line.strip()+ if not stripped or stripped.startswith(_IMPORT_PREFIXES):+ continue+ lowered = stripped.lower()+ hits = sum(1 for token in wanted if token in lowered)+ if hits:+ scored.append((hits, number, stripped[:_MAX_LINE_CHARS]))+ best = sorted(scored, key=lambda item: (-item[0], item[1]))[:limit]+ return [f"L{number}: {text}" for _hits, number, text in sorted(best, key=lambda i: i[1])]+++def _focused_outline(outline: str, wanted: set[str], room: int) -> str:+ """``outline`` cut to ``room``, keeping the declarations the task names.++ A plain cut keeps the head of a big module — its constants — and drops+ the function the task is about, which sits a thousand lines further down.+ So the outline is split into entries (a declaration plus its docstring+ line), the module docstring and every entry naming a task word are kept+ first, and the rest fill whatever room is left, all in file order.+ """+ if len(outline) <= room:+ return outline+ if room <= 0:+ return ""+ entries: list[str] = []+ for line in outline.splitlines():+ if entries and line.lstrip().startswith('"""') and not entries[-1].startswith('"""'):+ entries[-1] += "\n" + line+ else:+ entries.append(line)++ def _hits(entry: str) -> int:+ lowered = entry.lower()+ return sum(1 for token in wanted if token in lowered)++ # Bare constants (``NAME = ...``) say little unless the task names them.+ order = sorted(+ range(len(entries)),+ key=lambda i: (+ i != 0,+ -_hits(entries[i]),+ entries[i].rstrip().endswith("= ..."),+ i,+ ),+ )+ kept: set[int] = set()+ used = 0+ for i in order:+ cost = len(entries[i]) + 1+ if used + cost > room:+ continue+ kept.add(i)+ used += cost+ return "\n".join(entries[i] for i in sorted(kept))+++def _excerpt(rel: str, source: str, wanted: set[str], plan: PeekPlan, budget: int) -> str:+ """Outline first, then the lines that mention the task, within ``budget``."""+ cap = min(plan.chars_per_file, budget)+ if cap <= 0:+ return ""+ lines = _hit_lines(source, wanted, plan.hit_lines)+ hits_block = ("\nLines mentioning the task:\n" + "\n".join(lines)) if lines else ""+ # The relevant lines are the part only a look inside can give, so they keep+ # their room and the outline takes what is left.+ room = max(cap - len(hits_block), 0)+ full = outline_source(rel, source, max_chars=_FULL_OUTLINE_CHARS)+ outline = _focused_outline(full, wanted, room)+ return (outline + hits_block).strip()[:cap]+++def peek(+ root: str,+ instruction: str,+ candidates: Sequence[str],+ kind: str,+ *,+ deadline_s: float = PEEK_DEADLINE_S,+) -> Peek:+ """Look inside ``candidates`` for ``instruction``. Blocking; never raises.++ Run it in a worker thread. ``candidates`` arrive name-ranked from the file+ index; the result keeps that order as a prior and lets content decide+ between files the names could not separate.+ """+ plan = plan_for(kind)+ pool = list(dict.fromkeys(candidates))[: plan.pool]+ if not pool:+ return Peek()+ wanted = tokenize(instruction)+ stop_at = time.monotonic() + max(deadline_s, 0.0)++ sources: dict[str, str] = {}+ present: dict[str, set[str]] = {}+ for rel in pool:+ if time.monotonic() >= stop_at:+ break+ try:+ source = read_source(root, rel)+ except Exception: # noqa: BLE001 - a broken file costs its excerpt only+ source = ""+ if not source:+ continue+ sources[rel] = source+ lowered = source.lower()+ present[rel] = {token for token in wanted if token in lowered}++ # A word every file in the pool contains separates nothing; a word only+ # two files contain is what the task is actually about.+ seen_in = {token: sum(1 for hits in present.values() if token in hits) for token in wanted}+ named_kinds = {token.lstrip(".") for token in wanted}+ scores: dict[str, float] = {}+ for position, rel in enumerate(pool):+ if rel not in sources:+ continue+ content = sum(math.log(1 + len(sources) / seen_in[token]) for token in present[rel])+ # Name order is a real signal (the user often names the file), so it+ # stays as a prior worth about one rare content word.+ prior = 1.5 * (len(pool) - position) / len(pool)+ score = content + prior+ suffix = PurePosixPath(rel).suffix.lower()+ if suffix in _LOW_VALUE_SUFFIXES and suffix.lstrip(".") not in named_kinds:+ score *= _LOW_VALUE_FACTOR+ scores[rel] = score++ read = sorted(sources, key=lambda rel: -scores[rel])+ unread = [rel for rel in pool if rel not in sources]+ result = Peek(ranked=read + unread)++ # Excerpting is CPU on text already in memory. A cold disk that ate the+ # read deadline must not also cost every excerpt — that left a brief with+ # the right files and nothing seen inside them — so it gets its own window.+ excerpt_stop = max(stop_at, time.monotonic() + EXCERPT_WINDOW_S)+ remaining = plan.total_chars+ for rel in read[: plan.files]:+ if remaining <= 0 or time.monotonic() >= excerpt_stop:+ break+ try:+ text = _excerpt(rel, sources[rel], wanted, plan, remaining)+ except Exception: # noqa: BLE001 - a parser edge case costs one excerpt+ text = ""+ if text:+ result.excerpts[rel] = text+ remaining -= len(text)+ return result+++__all__ = ["EXCERPT_WINDOW_S", "PEEK_DEADLINE_S", "Peek", "PeekPlan", "peek", "plan_for"]diff --git a/jarvis/agentic_ide/prompt_blueprint.py b/jarvis/agentic_ide/prompt_blueprint.pyindex 245d4eca02..f4f42191cf 100644--- a/jarvis/agentic_ide/prompt_blueprint.py+++ b/jarvis/agentic_ide/prompt_blueprint.py@@ -37,6 +37,9 @@ made the receiving agent behave *worse*:files work. The agent opens them. A 1400-2400 character specification(2026-07-27) cost 10-30 s of thinking and then made the agent re-read thesame files; the 2026-08-18 mandate is 1-5 s, cleaned speech plus key files.+ Since 2026-10-01 the writer also sees short excerpts of the top files, and+ may pass on up to three facts from them in ``## Context`` - the symbol or+ value the agent would otherwise spend its first searches finding.* **Scope lives in the task, not in a prohibition list.** The first versionlisted what the agent must not do (no surrounding cleanup, no unrequestedrefactors, no speculative abstractions). Anthropic's own measured@@ -82,7 +85,7 @@ from .task_kind import (# Set above what a lean brief plus a dropped-file description measures, not# at the target: a limit the writer breaches on every ordinary composition# teaches it that the limits in this prompt are approximate.-MAX_BODY_CHARS = 1800+MAX_BODY_CHARS = 2200# What a GOOD prompt weighs. The 1400-2400 target (2026-07-27) bought a# specification the agent then re-read from the same @files, and the writer@@ -90,9 +93,10 @@ MAX_BODY_CHARS = 1800# that cleaned the spoken sentence and attached the neighbouring files landed# a comparable brief in about a second (maintainer, 2026-08-18). The target# is therefore the cleaned task plus a short Key files list — not a map of-# the code the agent is about to open.+# the code the agent is about to open. Raised 900 -> 1200 (2026-10-01) for+# the optional ``## Context`` bullets the file excerpts make possible.TARGET_MIN_CHARS = 280-TARGET_MAX_CHARS = 900+TARGET_MAX_CHARS = 1200_SKELETON = """\## Task@@ -102,6 +106,9 @@ _SKELETON = """\- `@path/to/file` - why this file is the starting point- `@path/to/other` - same, specifically+## Context+- <a fact the file excerpts show that the agent needs to start>+## Done when- <an observable outcome the user actually stated>\"""@@ -174,6 +181,13 @@ determines (its test command, its lint gate). Omit it otherwise. Do not add a \`## Scope` or `## How it works today` section - the agent will open the @files \and discover the current code itself.+`## Context` exists only when you were given FILE OUTLINES AND TASK-RELEVANT \+LINES: at most three bullets, each a fact those excerpts actually show and \+the agent needs to start - which function owns the behaviour, where a value \+is set and what it is now, where something is wired. Name the symbol and its \+file. Never a proposed change, never a walkthrough of the code. Omit it when \+the excerpts show nothing the task needs.+- Aim for {TARGET_MIN_CHARS}-{TARGET_MAX_CHARS} characters, never over \{MAX_BODY_CHARS}. Length comes from a clean task and a concrete Key files \list, never from restating the files' internals, hedging or dictated steps.@@ -199,7 +213,8 @@ coming back with questions: the behaviour that must exist afterwards, how it \should behave when things go wrong, and any constraint it has to respect. \Complete means the agent lacks no context - not that you dictated the steps.- Point at the starting files. Do not narrate how those files work today - \-the agent will open them. A symbol name from the outline is enough.+the agent will open them. A symbol name or one fact from the excerpts is \+enough.- A bound the user actually drew belongs in `## Task`, not in a separate \section. Do not fill the brief with generic don'ts - "no unrequested \refactors", "no speculative abstractions", "no surrounding cleanup" are \@@ -366,8 +381,11 @@ def user_block(f'<file path="{path}">\n{text}\n</file>' for path, text in skeletons.items())parts.append(- "FILE OUTLINES (signatures only - bodies omitted; use these to name "- "real symbols instead of describing code vaguely)\n" + outlines+ "FILE OUTLINES AND TASK-RELEVANT LINES (Jarvis looked into these "+ "files; partial - signatures plus the numbered lines that mention "+ "the task. Use them to choose the right Key files, to name real "+ "symbols instead of describing code vaguely, and for ## Context)\n"+ + outlines)if tree:diff --git a/jarvis/agentic_ide/prompt_composer.py b/jarvis/agentic_ide/prompt_composer.pyindex b8b35bc930..3273d9a7df 100644--- a/jarvis/agentic_ide/prompt_composer.py+++ b/jarvis/agentic_ide/prompt_composer.py@@ -25,10 +25,11 @@ What the composed prompt contains, and why each part earns its place:file into context", which removes the agent's entire opening round of blindsearching. Paths come from the workspace file index — never invented, andevery one is verified to exist before it ships.-* **A slim outline of the top files**, so the writer can name a real symbol- in the Key files list (``_fuse_ranked()`` instead of "the ranking logic")- without pasting the module. House rules stay out: the receiving agent- already has them.+* **A look inside the top files** (``file_peek``): their outline plus the+ lines that mention the task, so the writer picks the file that really holds+ the behaviour and names a real symbol (``_fuse_ranked()`` instead of "the+ ranking logic") without pasting the module. How deep it looks follows the+ task kind. House rules stay out: the receiving agent already has them.Two-layer construction, because the product must work for a downloader with noAPI key at all (§3):@@ -62,11 +63,16 @@ the same CLI. File *bodies* were never the wait, but sending AST outlinesplus a CLI rescue made the wait look like "reading the repo".The spoken budget is therefore ``FAST_BUDGET_S`` (about a second). Thinking-is off. The writer sees candidate *paths* from the tree, not file contents —-the receiving agent opens those files. A coding CLI is not a rescue on this-path: if Flash is not done when the budget expires, the deterministic brief-ships. What must still never happen is a silent demotion to a weaker-*quality tier* while the user waits.+is off. A coding CLI is not a rescue on this path: if Flash is not done when+the budget expires, the deterministic brief ships. What must still never+happen is a silent demotion to a weaker *quality tier* while the user waits.++**On context (maintainer decision 2026-10-01).** Paths alone made briefs that+pointed at the right folder but not at the right file or symbol. The writer+now also gets short excerpts of the most relevant files — read from disk in+well under a second, sized by task kind — and the budget grows by+``PEEK_EXTRA_S`` for that kind only when excerpts were actually read. A+brief with nothing to look into keeps the one-second path.**On the silence.** The beats below (``start`` → ``thinking``/``drafting`` →``ready``, and ``sent`` once the pane took it) are printed as they happen,@@ -127,6 +133,21 @@ COMPOSE_TIMEOUT_S = 90.0# 90 s ceiling plus an 8 s API hedge plus a CLI rescue was 22 s of silence.FAST_BUDGET_S = 1.2+# Extra seconds the writer gets when Jarvis looked inside the files first+# (``file_peek``). The excerpts are input the writer must read, and a budget+# sized for a bare rewrite would send every looked-at brief to the fallback.+# Deeper looks buy more time: an investigation, review or question is ABOUT+# the code, an implementation needs its entry points, an unclear request gets+# a glance. Maintainer decision 2026-10-01: briefs carry context from the+# important files, sized to the task.+PEEK_EXTRA_S: dict[str, float] = {+ KIND_INVESTIGATE: 2.8,+ KIND_REVIEW: 2.8,+ KIND_QUESTION: 2.8,+ KIND_IMPLEMENT: 1.8,+ KIND_NEUTRAL: 0.8,+}+# How many files may be attached. Enough to point the agent at a feature's# surface; few enough that the agent's context is not flooded with guesses.MAX_FILE_REFERENCES = 5@@ -434,7 +455,7 @@ def _start_message(kind: str, instruction: str, terminal_name: str) -> str:def _thinking_message(- instruction: str, terminal_name: str, *, files: int, writer_label: str+ instruction: str, terminal_name: str, *, files: int, writer_label: str, read: int = 0) -> str:"""The line that stands while the model works — with what it was handed."""if files == 1:@@ -443,6 +464,8 @@ def _thinking_message(context = f"{files} starting files from the tree"else:context = "your words alone"+ if read:+ context = f"{context}, {read} looked into"if writer_label:context = f"{context}, via {writer_label}"return _variant(_THINKING_PHRASES, instruction).format(name=terminal_name, context=context)@@ -594,6 +617,26 @@ def _file_candidates(session, instruction: str, limit: int) -> list[str]: # noqreturn _existing(session.folder, index.suggest(instruction, limit=limit))+def _gather_files(+ session, # noqa: ANN001 - Session, avoid an import cycle+ instruction: str,+ kind: str,+ limit: int,+) -> tuple[list[str], dict[str, str]]:+ """Name candidates, re-ranked by a look inside, plus excerpts of the top ones.++ Blocking; runs in a worker thread. Without an index there is nothing to+ look into and the brief ships without references, exactly as before.+ """+ from .file_peek import peek, plan_for++ pool = _file_candidates(session, instruction, max(limit, plan_for(kind).pool))+ if not pool:+ return [], {}+ looked = peek(session.folder, instruction, pool, kind)+ return (looked.ranked or pool)[:limit], looked.excerpts++def _extract_referenced(text: str) -> list[str]:"""``@path`` tokens in a composed prompt, in order of appearance."""seen: list[str] = []@@ -638,13 +681,6 @@ def _rescue_writer(tried: Sequence[str]): # noqa: ANN202 - (Brain | None, str))-# No file bodies. The tree index already named the candidates; the receiving-# agent opens those @files. Sending AST outlines made the writer prompt-# thousands of characters and looked like "reading the repo" while the wait-# was the model. Paths stay in the candidate list.-_OUTLINE_FILES = 0-_OUTLINE_CHARS = 0-# Spoken compositions currently in ``compose()``. Recap jobs read this so# they do not spawn a coding CLI on the same machine the user is waiting on._live_composes = 0@@ -702,11 +738,12 @@ async def _read_context(session, # noqa: ANN001 - Session, avoid an import cycleinstruction: str,) -> tuple[str, dict[str, str]]:- """The workspace tree, from the cached walk. No file bodies.+ """The workspace tree, from the cached walk.Kept as an awaitable so cancellation still reaps a sibling task, and sotests can patch this hook. The index was built when the folder opened;- rendering the map is in-memory.+ rendering the map is in-memory. File excerpts come from ``_gather_files``,+ which already ran before the writer's budget was fixed."""from .file_index import cached_index@@ -730,6 +767,7 @@ async def _compose_once(notify: Callable[[str, str], None],attachments: list,conversation: Sequence[tuple[str, str]],+ excerpts: dict[str, str] | None = None,) -> str:"""Wait for the file material, then make the one writing call.@@ -744,6 +782,8 @@ async def _compose_once(tree, outlines = packed if isinstance(packed[0], str) else ("", packed[0])if not isinstance(outlines, dict):outlines = {}+ if excerpts:+ outlines = {**outlines, **excerpts}notify(STAGE_THINKING,@@ -752,6 +792,7 @@ async def _compose_once(terminal_name,files=len(candidates),writer_label=_writer_label(brain),+ read=len(excerpts or {}),),)@@ -891,7 +932,9 @@ async def compose()if not use_llm:- found = await asyncio.to_thread(_file_candidates, session, subject, max_files * 2)+ found, _excerpts = await asyncio.to_thread(+ _gather_files, session, subject, kind, max_files * 2+ )return _deterministic("raw", candidates=found)started = time.monotonic()@@ -948,7 +991,9 @@ async def _compose_after_start()try:- candidates = await asyncio.to_thread(_file_candidates, session, subject, max_files * 2)+ candidates, excerpts = await asyncio.to_thread(+ _gather_files, session, subject, kind, max_files * 2+ )except BaseException:# Cancelled — or broken — before the writer probe was consumed. The# probe task is OURS: abandoned here it would run on unobserved and@@ -1000,7 +1045,8 @@ async def _compose_after_start(# All attempts share ONE budget. The user is waiting through the whole# sequence, and three full timeouts in a row is not a rescue — it is the# same fallback three times slower.- budget_s = min(COMPOSE_TIMEOUT_S, FAST_BUDGET_S)+ peek_extra_s = PEEK_EXTRA_S.get(kind, 0.0) if excerpts else 0.0+ budget_s = min(COMPOSE_TIMEOUT_S, FAST_BUDGET_S + peek_extra_s)deadline = started + budget_stried: list[str] = [writer_source] if writer_source else []attempts: dict[asyncio.Task[str], str] = {}@@ -1039,6 +1085,7 @@ async def _compose_after_start(notify=notify,attachments=attached,conversation=spoken_before,+ excerpts=excerpts,),timeout=remaining,)@@ -1208,6 +1255,7 @@ __all__ = ["HEDGE_AFTER_API_S","HEDGE_AFTER_S","MAX_FILE_REFERENCES",+ "PEEK_EXTRA_S","STAGE_DRAFTING","STAGE_FALLBACK","STAGE_HEDGE",diff --git a/tests/unit/agentic_ide/test_file_index.py b/tests/unit/agentic_ide/test_file_index.pyindex 9139a597c7..dc48c33e07 100644--- a/tests/unit/agentic_ide/test_file_index.py+++ b/tests/unit/agentic_ide/test_file_index.py@@ -9,11 +9,14 @@ agent that starts by searching for the file you already named.from __future__ import annotations+import shutil+import subprocessfrom pathlib import Pathimport pytestfrom jarvis.agentic_ide import file_index+from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS@pytest.fixture()@@ -201,3 +204,40 @@ def test_a_documentation_request_still_reaches_documentation(tmp_path: Path):hits = file_index.build_index(str(tmp_path)).suggest("update the architecture docs", limit=3)assert "docs/architecture-overview.md" in hits++[email protected](shutil.which("git") is None, reason="needs git on PATH")+def test_a_checkout_is_listed_by_git_so_ignored_data_never_crowds_the_code(+ tmp_path: Path,+) -> None:+ """Live 2026-10-01: 21 000 of 30 000 walked files came from two ignored+ data folders and the walk stopped at its cap. Git knows the project."""+ git = shutil.which("git")+ assert git is not None+ subprocess.run(+ [git, "init", "-q", str(tmp_path)],+ check=True,+ creationflags=NO_WINDOW_CREATIONFLAGS,+ )+ (tmp_path / ".gitignore").write_text("data/\n", encoding="utf-8")+ (tmp_path / "src").mkdir()+ (tmp_path / "src" / "wake_gate.py").write_text("x", encoding="utf-8")+ (tmp_path / "data").mkdir()+ (tmp_path / "data" / "wake_log.json").write_text("{}", encoding="utf-8")+ (tmp_path / ".hidden").mkdir()+ (tmp_path / ".hidden" / "wake_secret.py").write_text("x", encoding="utf-8")++ rels = {entry.rel for entry in file_index.build_index(tmp_path).entries}++ assert "src/wake_gate.py" in rels+ assert "data/wake_log.json" not in rels+ assert ".hidden/wake_secret.py" not in rels+++def test_a_folder_that_is_no_checkout_is_still_walked(tmp_path: Path) -> None:+ (tmp_path / "src").mkdir()+ (tmp_path / "src" / "wake_gate.py").write_text("x", encoding="utf-8")++ rels = {entry.rel for entry in file_index.build_index(tmp_path).entries}++ assert rels == {"src/wake_gate.py"}diff --git a/tests/unit/agentic_ide/test_file_peek.py b/tests/unit/agentic_ide/test_file_peek.pynew file mode 100644index 0000000000..eea22a92c2--- /dev/null+++ b/tests/unit/agentic_ide/test_file_peek.py@@ -0,0 +1,86 @@+"""The glance into the top files before a brief is written."""++from __future__ import annotations++from pathlib import Path++from jarvis.agentic_ide.file_peek import peek, plan_for+from jarvis.agentic_ide.task_kind import KIND_IMPLEMENT, KIND_INVESTIGATE, KIND_NEUTRAL+++def _write(root: Path, rel: str, text: str) -> None:+ path = root / rel+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(text, encoding="utf-8")+++def test_content_decides_between_files_the_names_cannot_separate(tmp_path: Path) -> None:+ """The file that actually holds the behaviour beats a better-named one."""+ _write(tmp_path, "wake/settings.py", "COLOR = 'blue'\n")+ _write(+ tmp_path,+ "wake/gate.py",+ "WAKE_TIMEOUT_S = 2.5\n\n\ndef wake_timeout_expired(now: float) -> bool:\n"+ " return now > WAKE_TIMEOUT_S\n",+ )++ result = peek(str(tmp_path), "the wake timeout", ["wake/settings.py", "wake/gate.py"], "")++ assert result.ranked[0] == "wake/gate.py"+ assert "def wake_timeout_expired(now: float) -> bool" in result.excerpts["wake/gate.py"]+ assert "WAKE_TIMEOUT_S = 2.5" in result.excerpts["wake/gate.py"]+++def test_excerpts_quote_numbered_task_lines_and_skip_imports(tmp_path: Path) -> None:+ _write(+ tmp_path,+ "a.py",+ "from wake import timeout\n\n\ndef run():\n limit = timeout * 2 # wake budget\n",+ )++ excerpt = peek(str(tmp_path), "wake timeout", ["a.py"], KIND_INVESTIGATE).excerpts["a.py"]++ assert "L5: limit = timeout * 2 # wake budget" in excerpt+ assert "from wake import" not in excerpt+++def test_depth_follows_the_task_kind() -> None:+ deep, build, glance = (+ plan_for(KIND_INVESTIGATE),+ plan_for(KIND_IMPLEMENT),+ plan_for(KIND_NEUTRAL),+ )+ assert deep.files > build.files > glance.files+ assert deep.total_chars > build.total_chars > glance.total_chars+ assert plan_for("unknown") == glance+++def test_only_the_top_files_are_excerpted_within_the_total_budget(tmp_path: Path) -> None:+ rels = [f"m{i}.py" for i in range(8)]+ for rel in rels:+ _write(tmp_path, rel, "def ranking():\n pass\n" * 200)++ result = peek(str(tmp_path), "ranking", rels, KIND_NEUTRAL)+ plan = plan_for(KIND_NEUTRAL)++ assert len(result.excerpts) <= plan.files+ assert sum(len(text) for text in result.excerpts.values()) <= plan.total_chars+ assert len(result.ranked) == min(len(rels), plan.pool)+++def test_nothing_outside_the_workspace_and_no_crash_on_missing_files(tmp_path: Path) -> None:+ (tmp_path.parent / "secret.py").write_text("password = 'x'\n", encoding="utf-8")++ result = peek(str(tmp_path), "password", ["../secret.py", "missing.py"], KIND_INVESTIGATE)++ assert result.excerpts == {}+ assert result.ranked == ["../secret.py", "missing.py"]+++def test_an_expired_deadline_costs_the_excerpts_not_the_order(tmp_path: Path) -> None:+ _write(tmp_path, "a.py", "def a(): ...\n")++ result = peek(str(tmp_path), "a", ["a.py"], KIND_IMPLEMENT, deadline_s=0.0)++ assert result.excerpts == {}+ assert result.ranked == ["a.py"]diff --git a/tests/unit/agentic_ide/test_prompt_blueprint.py b/tests/unit/agentic_ide/test_prompt_blueprint.pyindex 3d74da2667..72e9808afe 100644--- a/tests/unit/agentic_ide/test_prompt_blueprint.py+++ b/tests/unit/agentic_ide/test_prompt_blueprint.py@@ -278,7 +278,7 @@ def test_the_target_length_sits_inside_the_hard_ceiling():3000 budget — a model reads "under N" as "be brief"."""assert TARGET_MIN_CHARS < TARGET_MAX_CHARS < MAX_BODY_CHARS- assert TARGET_MAX_CHARS == 900+ assert TARGET_MAX_CHARS == 1200assert TARGET_MIN_CHARS == 280diff --git a/tests/unit/agentic_ide/test_prompt_composer.py b/tests/unit/agentic_ide/test_prompt_composer.pyindex ab6e4381f2..06da4d3678 100644--- a/tests/unit/agentic_ide/test_prompt_composer.py+++ b/tests/unit/agentic_ide/test_prompt_composer.py@@ -258,19 +258,21 @@ async def test_the_writer_gets_the_rules_for_the_detected_kind(assert "IMPLEMENTATION task" not in seen["system"]-async def test_the_writer_gets_candidate_paths_not_file_bodies(+async def test_the_writer_gets_the_tree_and_a_look_inside_the_top_files(workspace: _Session, monkeypatch: pytest.MonkeyPatch) -> None:- """The tree index names the files; the agent opens them.+ """Paths alone pointed at the right folder, not the right symbol.- Sending AST outlines made the writer prompt thousands of characters and- looked like reading the repo. The wait was the model, not the disk, but- the bodies still have no place on a 1 s path.+ Since 2026-10-01 Jarvis glances into the top candidates: their outline+ plus the lines that mention the task reach the writer, so the brief can+ name ``candidate_shape_ok`` instead of "the wake check"."""provider = Path(workspace.folder) / "jarvis" / "plugins" / "wake" / "vosk_kws_provider.py"provider.write_text('"""Vosk keyword spotting."""\n\n\n'- "def candidate_shape_ok(span: float) -> bool:\n return True\n",+ "def candidate_shape_ok(span: float) -> bool:\n"+ " # the vosk wake gate\n"+ " return True\n",encoding="utf-8",)_prime(workspace)@@ -288,17 +290,42 @@ async def test_the_writer_gets_candidate_paths_not_file_bodies(assert "WORKSPACE TREE" in seen["user"]assert "jarvis/plugins/wake/" in seen["user"]- assert "vosk_kws_provider.py" in seen["user"]- assert "FILE OUTLINES" not in seen["user"]- assert "candidate_shape_ok" not in seen["user"]+ assert "FILE OUTLINES AND TASK-RELEVANT LINES" in seen["user"]+ assert "candidate_shape_ok" in seen["user"]+ assert "L5: # the vosk wake gate" in seen["user"]# House rules stay out: the receiving agent already has them.assert "HOUSE RULES" not in seen["user"]-def test_the_writer_does_not_read_file_bodies() -> None:- """Bodies were the over-sync. Paths come from the in-memory tree."""- assert prompt_composer._OUTLINE_FILES == 0 # noqa: SLF001- assert prompt_composer._OUTLINE_CHARS == 0 # noqa: SLF001+async def test_looking_into_files_widens_the_budget_by_task_kind(+ workspace: _Session, monkeypatch: pytest.MonkeyPatch+) -> None:+ """Excerpts are input the writer must read; a bare-rewrite budget would+ send every looked-at brief to the fallback. Only when something was read."""+ _prime(workspace)++ async def _hang(**_kwargs: object) -> str:+ import asyncio++ await asyncio.sleep(60)+ return "## Task\nNever."++ monkeypatch.setattr(prompt_composer, "FAST_BUDGET_S", 0.05)+ monkeypatch.setattr(prompt_composer, "PEEK_EXTRA_S", {"review": 0.2})+ monkeypatch.setattr(prompt_composer, "_llm_compose", _hang)++ result = await prompt_composer.compose(+ "review the vosk wake provider", session=workspace, terminal_name="Kai"+ )++ assert result.composed_by == "fallback"+ assert "after 0.25s" in result.note+++def test_a_deep_look_gets_more_time_than_a_glance() -> None:+ extra = prompt_composer.PEEK_EXTRA_S+ assert extra["investigate"] > extra["implement"] > extra["neutral"] > 0+ assert prompt_composer.FAST_BUDGET_S + max(extra.values()) <= 4.5async def test_a_slow_writer_ships_the_plain_brief_inside_the_fast_budget(@@ -315,6 +342,7 @@ async def test_a_slow_writer_ships_the_plain_brief_inside_the_fast_budget(return "## Task\nNever."monkeypatch.setattr(prompt_composer, "FAST_BUDGET_S", 0.05)+ monkeypatch.setattr(prompt_composer, "PEEK_EXTRA_S", {})monkeypatch.setattr(prompt_composer, "COMPOSE_TIMEOUT_S", 90.0)monkeypatch.setattr(prompt_composer, "_llm_compose", _hang)