Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(editor-files): steer agents correctly on keyless indexes and mid-edit (#3109)

Raghav Chamadiyac967caac6d2a
diff --git a/docs/architecture/editor-files.md b/docs/architecture/editor-files.md
index 683578b57..eb2740aa2 100644
--- a/docs/architecture/editor-files.md
+++ b/docs/architecture/editor-files.md
@@ -134,7 +134,9 @@ Auto-generated from indexed data. Updates on every `repowise update`.
**Static** — the same text for every repo. Hardcoded in `claude_md.j2`. Teaches
Claude Code *when* to call each MCP tool using natural workflow framing rather than
-imperatives.
+imperatives. One exception: a keyless index (template prose, no semantic search)
+gets a bullet saying low-confidence answers and full-text-only hits are expected,
+and its tool table drops the clauses about `confidence: "high"` and `[fts]` hits.
This is the most important part. The phrasing matters: "Starting a new task?
Call `get_overview()` first" is more effective than "ALWAYS call `get_overview()`
diff --git a/packages/core/src/repowise/core/generation/editor_files/data.py b/packages/core/src/repowise/core/generation/editor_files/data.py
index 672fda15b..656b4f395 100644
--- a/packages/core/src/repowise/core/generation/editor_files/data.py
+++ b/packages/core/src/repowise/core/generation/editor_files/data.py
@@ -10,13 +10,13 @@ from __future__ import annotations
from dataclasses import dataclass, field
-def _render_tool_table() -> str:
+def _render_tool_table(*, keyless: bool = False) -> str:
# Local import: tool_table is a leaf module; importing lazily keeps data.py
# free of import-order coupling for the many tests that build these
# dataclasses directly.
from .tool_table import render_tool_table
- return render_tool_table()
+ return render_tool_table(keyless=keyless)
@dataclass(frozen=True)
@@ -130,11 +130,24 @@ class EditorFileData:
code_health: CodeHealthBlock | None = None
kg_layers: list[KGLayerSummary] = field(default_factory=list)
kg_tour: list[KGTourStepSummary] = field(default_factory=list)
- # Rendered MCP tool table (single source: tool_table.py). A data field
- # rather than a Jinja global so any environment can render the template.
- tool_table_md: str = field(default_factory=lambda: _render_tool_table())
index_scope: dict = field(default_factory=dict)
+ @property
+ def keyless(self) -> bool:
+ """Whether the index was built with no model: template prose, no semantic search."""
+ scope = self.index_scope
+ search = scope.get("search") if isinstance(scope.get("search"), dict) else {}
+ return (
+ scope.get("content_provenance") in ("template", "none")
+ and search.get("semantic") == "unavailable"
+ )
+
+ @property
+ def tool_table_md(self) -> str:
+ # Rendered MCP tool table (single source: tool_table.py). Exposed on the
+ # data rather than as a Jinja global so any environment can render it.
+ return _render_tool_table(keyless=self.keyless)
+
# ---------------------------------------------------------------------------
# Workspace-level data containers
@@ -165,5 +178,6 @@ class WorkspaceEditorFileData:
package_deps: list[dict] = field(default_factory=list) # package dep entries
contract_links: list[dict] = field(default_factory=list) # matched contract links
contracts_by_type: dict[str, int] = field(default_factory=dict) # {"http": 5, …}
- # Rendered MCP tool table (single source: tool_table.py).
+ # Rendered MCP tool table (single source: tool_table.py). Always the keyed
+ # table: member repos can differ in keyless state, and one keyed repo needs it.
tool_table_md: str = field(default_factory=lambda: _render_tool_table())
diff --git a/packages/core/src/repowise/core/generation/editor_files/tool_table.py b/packages/core/src/repowise/core/generation/editor_files/tool_table.py
index 6b38e6f16..e347840eb 100644
--- a/packages/core/src/repowise/core/generation/editor_files/tool_table.py
+++ b/packages/core/src/repowise/core/generation/editor_files/tool_table.py
@@ -47,6 +47,15 @@ Budgets in ``tests/unit/server/mcp/test_tool_table_drift.py``.
from __future__ import annotations
+#: Row text that is true only on a model-backed index. A keyless index answers
+#: every question at low confidence and serves full-text hits only, so these
+#: clauses are dropped there rather than steering the agent to distrust them.
+_KEYED_ONLY: dict[str, str] = {
+ "get_answer": 'Cite `confidence: "high"` or `grounding: "extracted"` directly; ',
+ "search_codebase": " A hit whose `sources` are `[fts]` only has no semantic agreement, "
+ "so verify it.",
+}
+
# Tool name -> (signature shown in the table, agent-facing row text).
TOOL_TABLE_ROWS: dict[str, tuple[str, str]] = {
"get_answer": (
@@ -58,9 +67,9 @@ TOOL_TABLE_ROWS: dict[str, tuple[str, str]] = {
# payload on the strength of it, so it re-searched after every call.
# `retrieval_quality` is the field that rates what such a payload does
# carry. Reworded, not lengthened: 186 chars against the 179 it replaced.
- 'First call for any how/where/why question. Cite `confidence: "high"` or '
- '`grounding: "extracted"` directly; `degraded` means judge by '
- "`retrieval_quality`. `symbol_bodies` has live bodies.",
+ "First call for any how/where/why question. "
+ + _KEYED_ONLY["get_answer"]
+ + "`degraded` means judge by `retrieval_quality`. `symbol_bodies` has live bodies.",
),
"get_context": (
"get_context(targets=[...])",
@@ -77,8 +86,7 @@ TOOL_TABLE_ROWS: dict[str, tuple[str, str]] = {
"search_codebase": (
"search_codebase(query)",
"Hybrid search, auto-routed by query shape; force with "
- "`mode=symbol|path|concept|hybrid`. A hit whose `sources` are `[fts]` only "
- "has no semantic agreement, so verify it.",
+ "`mode=symbol|path|concept|hybrid`." + _KEYED_ONLY["search_codebase"],
),
"get_why": (
"get_why(query, targets?)",
@@ -115,9 +123,11 @@ TOOL_TABLE_ROWS: dict[str, tuple[str, str]] = {
}
-def render_tool_table() -> str:
+def render_tool_table(*, keyless: bool = False) -> str:
"""Markdown table of the tool rows, in the dict's curated order."""
lines = ["| Tool | When and why |", "|------|--------------|"]
- for signature, row in TOOL_TABLE_ROWS.values():
+ for name, (signature, row) in TOOL_TABLE_ROWS.items():
+ if keyless and name in _KEYED_ONLY:
+ row = row.replace(_KEYED_ONLY[name], "")
lines.append(f"| `{signature}` | {row} |")
return "\n".join(lines)
diff --git a/packages/core/src/repowise/core/generation/templates/agents_md.j2 b/packages/core/src/repowise/core/generation/templates/agents_md.j2
index f6d31989a..34e4a6fed 100644
--- a/packages/core/src/repowise/core/generation/templates/agents_md.j2
+++ b/packages/core/src/repowise/core/generation/templates/agents_md.j2
@@ -1,14 +1,17 @@
## Codebase Intelligence for {{ data.repo_name }} (Repowise)
-Indexed by [Repowise](https://repowise.dev). Last indexed: {{ data.indexed_at }}{% if data.indexed_commit %} (commit {{ data.indexed_commit }}){% endif %}{% if data.avg_confidence %}. Confidence: {{ (data.avg_confidence * 100) | int }}%.{% endif %}
+Indexed by [Repowise](https://repowise.dev). Last indexed: {{ data.indexed_at }}{% if data.indexed_commit %} (commit {{ data.indexed_commit }}){% endif %}{% if data.avg_confidence and not data.keyless %}. Confidence: {{ (data.avg_confidence * 100) | int }}%.{% elif data.keyless %}. {% endif %}
{% if data.index_scope %}
-Scope: {{ data.index_scope.run_mode }} index · {{ data.index_scope.content_provenance }} content · {{ data.index_scope.git_tier }} Git{% if data.index_scope.file_pages.omitted is not none and data.index_scope.file_pages.omitted %} · {{ data.index_scope.file_pages.omitted }} eligible file pages omitted{% endif %}. Missing or unavailable evidence is not a negative finding. {% if data.index_scope.upgrade.status in ['pending', 'resumable', 'failed'] %}Run `repowise update --full` to continue the model-backed upgrade (cost is previewed before generation).{% endif %}
-Machine-readable scope: `{{ data.index_scope | tojson }}`
+Scope: {{ data.index_scope.run_mode }} index · {{ data.index_scope.content_provenance }} content · {{ data.index_scope.git_tier }} Git{% if data.index_scope.file_pages.omitted is not none and data.index_scope.file_pages.omitted %} · {{ data.index_scope.file_pages.omitted }} eligible file pages omitted{% endif %}. Missing or unavailable evidence is not a negative finding.{% if data.index_scope.upgrade.status in ['pending', 'resumable', 'failed'] and not data.keyless %} Run `repowise update --full` to continue the model-backed upgrade (cost is previewed before generation).{% endif %}
+
{% endif %}
### How to work in this repo
-- **Trust the index.** `verified: true` and `_meta.complete` mean the bytes were checked against the live tree, so never re-read them. Re-read only what `bounds: "approximate"` or `_meta.stale_warning` names. `confidence` rates the prose, not the evidence: on `low` read the top evidence row or the `candidate_files` the reply names, and run `repowise update` and ask again if `_meta.hint` says the index is behind HEAD. `index_behind: true` alone is informational.
+- **Trust the index.** `verified: true` and `_meta.complete` mean the bytes were checked against the live tree, so never re-read them. Re-read only what `bounds: "approximate"` names. When `_meta.stale_warning` is set, Read the files that response served. After a batch of uncommitted edits, `repowise update --working-tree` refreshes the index. `confidence` rates the prose, not the evidence: on `low` read the top evidence row or the `candidate_files` the reply names, and run `repowise update` and ask again if `_meta.hint` says the index is behind HEAD. `index_behind: true` alone is informational.
+{% if data.keyless %}
+- **No model on this index.** `get_answer` replies are low confidence by design, so open its top `best_guesses` / `candidate_files` rows; `search_codebase` is full-text only, so `[fts]` hits are normal.
+{% endif %}
- **A zero carries its basis.** An empty `callers`/`callees`/`used_by` comes with a `*_basis` saying how much of that language's calls the graph resolved, so read it before concluding nothing calls a symbol. On `get_answer`, `_meta.scope_hint` names the areas the answer did not touch.
- **Pre-edit, not instead-of-edit.** These tools decide *which* files to read and edit. Reading a file before you edit it is correct and expected.
- **Noisy commands** (tests, builds, `git log`/`diff`, searches, listings): prefer `repowise distill <cmd>`, the same command with its exit code preserved and errors-first output. A `[repowise#<ref>: N lines omitted]` marker is recoverable via `repowise expand <ref>` (add `-q <regex>` to filter); never re-run the command to see omitted output.
diff --git a/packages/core/src/repowise/core/generation/templates/claude_md.j2 b/packages/core/src/repowise/core/generation/templates/claude_md.j2
index 7096f5d08..54fd2faf9 100644
--- a/packages/core/src/repowise/core/generation/templates/claude_md.j2
+++ b/packages/core/src/repowise/core/generation/templates/claude_md.j2
@@ -1,14 +1,17 @@
## Codebase Intelligence for {{ data.repo_name }} (Repowise)
-Indexed by [Repowise](https://repowise.dev). Last indexed: {{ data.indexed_at }}{% if data.indexed_commit %} (commit {{ data.indexed_commit }}){% endif %}{% if data.avg_confidence %}. Confidence: {{ (data.avg_confidence * 100) | int }}%.{% endif %}
+Indexed by [Repowise](https://repowise.dev). Last indexed: {{ data.indexed_at }}{% if data.indexed_commit %} (commit {{ data.indexed_commit }}){% endif %}{% if data.avg_confidence and not data.keyless %}. Confidence: {{ (data.avg_confidence * 100) | int }}%.{% elif data.keyless %}. {% endif %}
{% if data.index_scope %}
-Scope: {{ data.index_scope.run_mode }} index · {{ data.index_scope.content_provenance }} content · {{ data.index_scope.git_tier }} Git{% if data.index_scope.file_pages.omitted is not none and data.index_scope.file_pages.omitted %} · {{ data.index_scope.file_pages.omitted }} eligible file pages omitted{% endif %}. Missing or unavailable evidence is not a negative finding. {% if data.index_scope.upgrade.status in ['pending', 'resumable', 'failed'] %}Run `repowise update --full` to continue the model-backed upgrade (cost is previewed before generation).{% endif %}
-Machine-readable scope: `{{ data.index_scope | tojson }}`
+Scope: {{ data.index_scope.run_mode }} index · {{ data.index_scope.content_provenance }} content · {{ data.index_scope.git_tier }} Git{% if data.index_scope.file_pages.omitted is not none and data.index_scope.file_pages.omitted %} · {{ data.index_scope.file_pages.omitted }} eligible file pages omitted{% endif %}. Missing or unavailable evidence is not a negative finding.{% if data.index_scope.upgrade.status in ['pending', 'resumable', 'failed'] and not data.keyless %} Run `repowise update --full` to continue the model-backed upgrade (cost is previewed before generation).{% endif %}
+
{% endif %}
### How to work in this repo
-- **Trust the index.** `verified: true` and `_meta.complete` mean the bytes were checked against the live tree, so never re-read them. Re-read only what `bounds: "approximate"` or `_meta.stale_warning` names. `confidence` rates the prose, not the evidence: on `low` read the top evidence row or the `candidate_files` the reply names, and run `repowise update` and ask again if `_meta.hint` says the index is behind HEAD. `index_behind: true` alone is informational.
+- **Trust the index.** `verified: true` and `_meta.complete` mean the bytes were checked against the live tree, so never re-read them. Re-read only what `bounds: "approximate"` names. When `_meta.stale_warning` is set, Read the files that response served. After a batch of uncommitted edits, `repowise update --working-tree` refreshes the index. `confidence` rates the prose, not the evidence: on `low` read the top evidence row or the `candidate_files` the reply names, and run `repowise update` and ask again if `_meta.hint` says the index is behind HEAD. `index_behind: true` alone is informational.
+{% if data.keyless %}
+- **No model on this index.** `get_answer` replies are low confidence by design, so open its top `best_guesses` / `candidate_files` rows; `search_codebase` is full-text only, so `[fts]` hits are normal.
+{% endif %}
- **A zero carries its basis.** An empty `callers`/`callees`/`used_by` comes with a `*_basis` saying how much of that language's calls the graph resolved, so read it before concluding nothing calls a symbol. On `get_answer`, `_meta.scope_hint` names the areas the answer did not touch.
- **Pre-edit, not instead-of-edit.** These tools decide *which* files to read and edit. Claude Code requires a raw Read of any file you will Edit, and that Read is correct and expected.
- **Noisy commands** (tests, builds, `git log`/`diff`, searches, listings): prefer `repowise distill <cmd>` — same command, exit code preserved, errors-first output. A `[repowise#<ref>: N lines omitted]` marker is recoverable via `repowise expand <ref>` (add `-q <regex>` to filter); never re-run the command to see omitted output.
diff --git a/tests/unit/generation/test_editor_file_base.py b/tests/unit/generation/test_editor_file_base.py
index f8fc4dd5f..a4eba1fd4 100644
--- a/tests/unit/generation/test_editor_file_base.py
+++ b/tests/unit/generation/test_editor_file_base.py
@@ -66,7 +66,7 @@ def test_render_contains_repo_name(gen):
assert "test-repo" in result
-def test_render_contains_machine_readable_index_scope(gen):
+def test_render_contains_index_scope_line_without_the_json(gen):
import dataclasses
data = dataclasses.replace(
@@ -83,11 +83,93 @@ def test_render_contains_machine_readable_index_scope(gen):
result = gen.render(data)
assert "Scope: fast index · none content · essential Git" in result
assert "5 eligible file pages omitted" in result
- assert '"eligible": 5' in result
- assert '"generated": 0' in result
+ # MCP serves the full scope in `_meta` and on get_overview; this file is
+ # read into every session, so it carries the one-line summary only.
+ assert '"eligible": 5' not in result
+ assert "Machine-readable scope" not in result
assert "repowise update --full" in result
+_KEYLESS_SCOPE = {
+ "run_mode": "standard",
+ "content_provenance": "template",
+ "git_tier": "full",
+ "file_pages": {"eligible": 28, "generated": 25, "omitted": 3},
+ "upgrade": {"status": "pending"},
+ "provider": {"embedder": "mock", "model_cost_possible": False},
+ "search": {"full_text": "available", "semantic": "unavailable"},
+}
+_KEYED_SCOPE = {
+ **_KEYLESS_SCOPE,
+ "content_provenance": "model",
+ "upgrade": {"status": "resumable"},
+ "provider": {"embedder": "openai", "model_cost_possible": True},
+ "search": {"full_text": "available", "semantic": "available"},
+}
+_KEYLESS_BULLET = "**No model on this index.**"
+
+
[email protected](params=["claude_md.j2", "agents_md.j2"])
+def any_gen(request):
+ class _Gen(_TestGenerator):
+ template_name = request.param
+
+ return _Gen()
+
+
+def _scoped(scope: dict) -> EditorFileData:
+ import dataclasses
+
+ return dataclasses.replace(_minimal_data(), avg_confidence=1.0, index_scope=scope)
+
+
+def test_keyless_index_gets_keyless_steering(any_gen):
+ result = any_gen.render(_scoped(_KEYLESS_SCOPE))
+ assert _KEYLESS_BULLET in result
+ # Template pages store confidence 1.0, so the figure would read as 100%.
+ assert "Confidence:" not in result
+ assert "(commit a1b2c3d). Scope:" in result
+ # `--full` needs a key; offering it to a keyless index is a dead end.
+ assert "repowise update --full" not in result
+ assert "[fts]` only has no semantic agreement" not in result
+ assert 'Cite `confidence: "high"`' not in result
+ assert "`degraded` means judge by `retrieval_quality`" in result
+
+
+def test_keyed_index_keeps_model_guidance(any_gen):
+ result = any_gen.render(_scoped(_KEYED_SCOPE))
+ assert _KEYLESS_BULLET not in result
+ assert "Confidence: 100%" in result
+ assert "repowise update --full" in result
+ assert "[fts]` only has no semantic agreement" in result
+ assert 'Cite `confidence: "high"`' in result
+
+
[email protected]("scope", [_KEYLESS_SCOPE, _KEYED_SCOPE], ids=["keyless", "keyed"])
[email protected]("upgrade", ["pending", "complete"])
+def test_render_has_no_trailing_whitespace_or_double_blank_lines(any_gen, scope, upgrade):
+ result = any_gen.render(_scoped({**scope, "upgrade": {"status": upgrade}}))
+ assert not [line for line in result.splitlines() if line != line.rstrip()]
+ assert "\n\n\n" not in result
+
+
+def test_legacy_empty_scope_renders_keyed_text_and_no_scope_block(any_gen):
+ data = _scoped({})
+ assert data.keyless is False
+ result = any_gen.render(data)
+ assert "Scope:" not in result
+ assert _KEYLESS_BULLET not in result
+ assert "Confidence: 100%" in result
+ assert "[fts]` only has no semantic agreement" in result
+ assert 'Cite `confidence: "high"`' in result
+
+
+def test_stale_warning_guidance_points_at_served_files(any_gen):
+ result = any_gen.render(_minimal_data())
+ assert "When `_meta.stale_warning` is set, Read the files that response served." in result
+ assert "`repowise update --working-tree`" in result
+
+
def _health_block(
maintainability_average: float | None,
performance_average: float | None = None,