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.

feat(editor-files): a lean CLAUDE.md and AGENTS.md block with sections you can add back (#4235)

Raghav Chamadiyae4ad071d35d5
diff --git a/docs/architecture/ARCHITECTURE.md b/docs/architecture/ARCHITECTURE.md
index 2c5235cc2..9cfd43374 100644
--- a/docs/architecture/ARCHITECTURE.md
+++ b/docs/architecture/ARCHITECTURE.md
@@ -1579,7 +1579,7 @@ Key files:
| `core/generation/editor_files/fetcher.py` | `EditorFileDataFetcher`, queries DB for architecture summary, modules, hotspots, decisions |
| `core/generation/editor_files/tech_stack.py` | Filesystem scan for languages, frameworks, build commands |
| `core/generation/editor_files/claude_md.py` | `ClaudeMdGenerator`, 30-line subclass that binds filename + template |
-| `core/generation/templates/claude_md.j2` | Jinja2 template for the Repowise-managed section |
+| `core/generation/templates/_editor_block.j2` | Jinja2 template for the Repowise-managed section |
| `cli/commands/claude_md_cmd.py` | `repowise generate-claude-md` CLI command |
| `server/routers/claude_md.py` | `GET/POST /api/repos/{id}/claude-md` REST endpoints |
diff --git a/docs/architecture/code-health.md b/docs/architecture/code-health.md
index 73f1d671a..3817203e4 100644
--- a/docs/architecture/code-health.md
+++ b/docs/architecture/code-health.md
@@ -1155,7 +1155,7 @@ filter rules in `core/generation/editor_files/data.py`:
Everything else is filtered out so the CLAUDE.md doesn't drown a fresh
agent in noise. The Jinja stanza lives in
-`core/generation/templates/claude_md.j2`.
+`core/generation/templates/_editor_block.j2`.
---
diff --git a/docs/architecture/editor-files.md b/docs/architecture/editor-files.md
index f0405c2b0..2955b1e41 100644
--- a/docs/architecture/editor-files.md
+++ b/docs/architecture/editor-files.md
@@ -115,41 +115,27 @@ which the placeholder comment warns against.
## 4. What goes into the Repowise section
-The section has three parts. Total target length: **150–250 lines**. Conciseness
-is intentional — research shows AI assistants ignore bloated configuration files.
-
-### Part 1: Codebase Intelligence
-
-Auto-generated from indexed data. Updates on every `repowise update`.
-
-| Sub-section | Source | Cap |
-|-------------|--------|-----|
-| Architecture summary | First 4 sentences from `repo_overview` wiki page | 4 sentences |
-| Key Modules | `module_page` pages sorted by PageRank desc, joined with git_metadata for owner | Top 10 |
-| Entry Points | The curated `kg_project_meta` list; otherwise `graph_nodes` where `is_entry_point=True`, ranked on execution-start evidence | Top 10 |
-| Tech Stack | Filesystem scan (package.json, pyproject.toml, Cargo.toml, go.mod, etc.) | All detected |
-| Hotspots | `git_metadata` where `is_hotspot=True`, sorted by `churn_percentile` desc | Top 5 |
-
-### Part 2: MCP Tools Workflow Guide
-
-**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. 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()`
-before doing anything."
-
-### Part 3: Codebase Conventions
-
-Auto-generated from indexed data.
-
-| Sub-section | Source | Cap |
-|-------------|--------|-----|
-| Architectural Decisions | `decision_records` where `status='active'`, sorted by `staleness_score` asc | Top 8 |
-| Commands | Filesystem scan: `package.json` scripts, `Makefile` targets, `pyproject.toml` pytest/ruff | All detected |
+The block is read into the agent's context on every turn, so it is lean by
+default. `editor_files.sections` picks the sections (see
+[CONFIG.md](../reference/CONFIG.md#the-editor_files-block)); the fetcher runs
+only the queries the chosen sections render. Both templates include the shared
+`_editor_block.j2` and differ only in the pre-edit sentence.
+
+| Section | Default | Source | Cap |
+|---------|---------|--------|-----|
+| Header | always | Date and commit; a `Scope:` line only when the index lacks a model, has essential Git history only, or has a model upgrade pending | — |
+| `architecture` | on | First 4 sentences from the `repo_overview` wiki page | 4 sentences |
+| `key_modules` | on | `module_page` pages by PageRank desc | Top 10 |
+| `entry_points` | on | The curated `kg_project_meta` list, else `is_entry_point` nodes ranked on execution-start evidence | Top 6 |
+| `hotspots` | on | `git_metadata` bug magnets and hotspots, fix history first, with the last fix date | Top 5 |
+| `health` | on | Health score, band and worst file | 1 line |
+| `code_health` | off | Every health signal (replaces `health`) | 1 line |
+| `fix_first` | off | The Fix-first queue | Top 3 |
+| `decisions` | on | Accepted active `decision_records`, titles only, by `staleness_score` asc | Top 3 |
+| `how_to_work` | on | Static: pre-edit, distill, decision capture; a keyless bullet when the index has no model | 3-4 bullets |
+| `how_to_work_full` | off | The long protocol (replaces `how_to_work`) | — |
+| `tools` | on | `tool_table.py`, the MCP tool table | All tools |
+| `commands` | off | Manifest scan: `package.json` scripts, `Makefile`, `pyproject.toml` | All detected |
---
@@ -210,8 +196,7 @@ LIMIT 5
SELECT * FROM decision_records
WHERE repository_id = :repo_id AND status = 'active'
ORDER BY staleness_score ASC
-LIMIT 8
-# → uses first 100 chars of rationale field
+LIMIT 9 -- 3 shown, titles only; the spare rows cover records in excluded paths
```
**Average confidence** (`_get_avg_confidence`)
@@ -472,6 +457,7 @@ Returns 422 if `local_path` is not accessible from the server.
# .repowise/config.yaml
editor_files:
claude_md: true # default: true. Set false to disable entirely.
+ sections: ["+commands"] # optional; adjusts the default section set
```
The `--no-claude-md` CLI flag sets `editor_files.claude_md: false` in
diff --git a/docs/reference/CONFIG.md b/docs/reference/CONFIG.md
index ad314315a..2523f43ac 100644
--- a/docs/reference/CONFIG.md
+++ b/docs/reference/CONFIG.md
@@ -13,6 +13,7 @@ The `.repowise/` directory, provider setup, API keys, and what's customizable.
[The `distill:` block](#the-distill-block) ·
[The `hooks:` block](#the-hooks-block) ·
[The `mcp:` block](#the-mcp-block) ·
+[The `editor_files:` block](#the-editor_files-block) ·
[The `decisions:` block](#the-decisions-block) ·
[`policies.yaml`](#repowisepoliciesyaml) ·
[The `security:` block](#the-security-block) ·
@@ -407,6 +408,25 @@ mcp:
default. The workspace-only three are ignored if named in single-repo mode. See
[MCP_TOOLS.md](../agent/MCP_TOOLS.md#configuring-the-tool-surface).
+### The `editor_files:` block
+
+Controls the generated block in `.claude/CLAUDE.md` and `AGENTS.md`. The block
+is read into the agent's context on every turn, so the default is lean.
+`sections` adjusts it with the `mcp.tools` grammar: `+name` / `-name` change
+the default set, unprefixed names replace it.
+
+```yaml
+editor_files:
+ claude_md: true
+ sections: ["+commands", "+fix_first"]
+```
+
+- Default: `architecture`, `key_modules`, `entry_points`, `hotspots`, `health`
+ (score and worst file), `decisions` (top three titles), `how_to_work` (three
+ bullets), `tools`.
+- Opt-in: `code_health` (all health signals, replaces `health`), `fix_first`,
+ `commands` (build/test/lint read from manifests), `how_to_work_full`.
+
### The `decisions:` block
Controls decision capture: whether it runs at all, which sources it uses, and
diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/decision_inject.py b/packages/cli/src/repowise/cli/commands/augment_cmd/decision_inject.py
index d75d45216..d19ca1797 100644
--- a/packages/cli/src/repowise/cli/commands/augment_cmd/decision_inject.py
+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/decision_inject.py
@@ -877,15 +877,7 @@ _FIX_NOTICE_MIN_COUNT = 3
def _humanize_age(days: int) -> str:
- """Render an age as "2 weeks ago" / "3 months ago", never as a bare count.
-
- Deliberately duplicated by ``editor_files/fetcher.py``, which renders the
- same recency phrasing into CLAUDE.md. Sharing it would mean this hook
- importing ``repowise.core``, and the cheapest module that could host it
- costs ~660ms to import (``analysis.health.__init__`` builds the whole
- HealthAnalyzer) against this module's sub-100ms budget. Ten lines of copy
- is the cheaper trade; keep the two phrasings in step by hand.
- """
+ """Render an age as "2 weeks ago" / "3 months ago", never as a bare count."""
if days <= 1:
return "today" if days <= 0 else "yesterday"
if days < 14:
diff --git a/packages/core/src/repowise/core/analysis/health/README.md b/packages/core/src/repowise/core/analysis/health/README.md
index 5017b75c1..22c97bf9a 100644
--- a/packages/core/src/repowise/core/analysis/health/README.md
+++ b/packages/core/src/repowise/core/analysis/health/README.md
@@ -199,4 +199,4 @@ parallel path automatically when `len(parsed_files) >= 500`.
- API: `packages/server/src/repowise/server/routers/code_health.py`.
- UI primitives: `packages/ui/src/health/`. Web routes:
`packages/web/src/app/repos/[id]/health/`.
-- CLAUDE.md template stanza: `packages/core/src/repowise/core/generation/templates/claude_md.j2`.
+- CLAUDE.md template stanza: `packages/core/src/repowise/core/generation/templates/_editor_block.j2`.
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 b02ac6e12..fe127a8c7 100644
--- a/packages/core/src/repowise/core/generation/editor_files/data.py
+++ b/packages/core/src/repowise/core/generation/editor_files/data.py
@@ -13,6 +13,8 @@ from typing import TYPE_CHECKING
if TYPE_CHECKING:
from repowise.core.persistence.crud.analysis.performance import PerformanceHeadline
+from .sections import DEFAULT_SECTIONS
+
def _render_tool_table(*, keyless: bool = False) -> str:
# Local import: tool_table is a leaf module; importing lazily keeps data.py
@@ -46,12 +48,13 @@ class HotspotFile:
owner: str | None
# Bug-fix history for the same file. ``fix_count`` is the windowed
# production-code fix count (``GitMetadata.prior_defect_count``), and
- # ``last_fix_age`` is pre-rendered ("2 weeks ago") because a count with no
- # recency reads as an accusation about 2019. ``bug_magnet`` is only ever set
- # alongside an age, per the recency contract in ``types/health.ts``.
+ # ``last_fix_date`` (``YYYY-MM-DD``) anchors it, because a count with no
+ # recency reads as an accusation about 2019; a date stays true between
+ # regenerations. ``bug_magnet`` is only ever set alongside a date, per the
+ # recency contract in ``types/health.ts``.
fix_count: int = 0
bug_magnet: bool = False
- last_fix_age: str | None = None
+ last_fix_date: str | None = None
@dataclass(frozen=True)
@@ -135,6 +138,7 @@ class EditorFileData:
kg_layers: list[KGLayerSummary] = field(default_factory=list)
kg_tour: list[KGTourStepSummary] = field(default_factory=list)
index_scope: dict = field(default_factory=dict)
+ sections: frozenset[str] = DEFAULT_SECTIONS
@property
def keyless(self) -> bool:
@@ -146,6 +150,27 @@ class EditorFileData:
and search.get("semantic") == "unavailable"
)
+ @property
+ def scope_gaps(self) -> list[str]:
+ """What this index lacks, for the header; empty when nothing does."""
+ scope = self.index_scope
+ upgrade = scope.get("upgrade") if isinstance(scope.get("upgrade"), dict) else {}
+ gaps = []
+ if self.keyless:
+ gaps.append("no model (template prose, full-text search)")
+ if scope.get("git_tier") == "essential":
+ gaps.append("essential Git history only")
+ if self.upgrade_pending:
+ gaps.append(f"model upgrade {upgrade.get('status')}")
+ return gaps
+
+ @property
+ def upgrade_pending(self) -> bool:
+ upgrade = self.index_scope.get("upgrade")
+ status = upgrade.get("status") if isinstance(upgrade, dict) else None
+ # `--full` needs a key, so a keyless index is never told to continue one.
+ return status in ("pending", "resumable", "failed") and not self.keyless
+
@property
def tool_table_md(self) -> str:
# Rendered MCP tool table (single source: tool_table.py). Exposed on the
diff --git a/packages/core/src/repowise/core/generation/editor_files/fetcher.py b/packages/core/src/repowise/core/generation/editor_files/fetcher.py
index 3505540ad..c6e95799f 100644
--- a/packages/core/src/repowise/core/generation/editor_files/fetcher.py
+++ b/packages/core/src/repowise/core/generation/editor_files/fetcher.py
@@ -6,9 +6,11 @@ Uses the existing CRUD layer where possible; raw selects for aggregate queries.
from __future__ import annotations
+import dataclasses
import json
import re
import subprocess
+from collections.abc import Iterable
from datetime import UTC, datetime
from pathlib import Path
@@ -51,13 +53,14 @@ from .data import (
KGLayerSummary,
KGTourStepSummary,
)
+from .sections import load_sections, resolve_sections
from .tech_stack import detect_build_commands, detect_tech_stack
-# Maximum items per section to keep CLAUDE.md within ~200 lines
+# Maximum items per section: the block is read into every agent turn.
_MAX_MODULES = 10
_MAX_ENTRY_POINTS = 10
_MAX_HOTSPOTS = 5
-_MAX_DECISIONS = 8
+_MAX_DECISIONS = 3
_MAX_FIX_FIRST = 3
@@ -87,13 +90,20 @@ class EditorFileDataFetcher:
session: AsyncSession,
repo_id: str,
repo_path: Path,
+ *,
+ sections: Iterable[str] | None = None,
) -> None:
self._session = session
self._repo_id = repo_id
self._repo_path = repo_path
+ # ``None`` reads ``editor_files.sections`` from the repo's config.
+ self._sections = (
+ load_sections(repo_path) if sections is None else resolve_sections(list(sections))
+ )
async def fetch(self) -> EditorFileData:
- """Run all queries and return a populated EditorFileData."""
+ """Run the queries the configured sections need and return EditorFileData."""
+ s = self._sections
repo = await crud.get_repository(self._session, self._repo_id)
repo_name = repo.name if repo else self._repo_path.name
@@ -111,18 +121,25 @@ class EditorFileDataFetcher:
repo_name=repo_name,
indexed_at=datetime.now(UTC).strftime("%Y-%m-%d"),
indexed_commit=stored_commit or _get_head_short_sha(self._repo_path),
- architecture_summary=await self._get_architecture_summary(),
- key_modules=await self._get_key_modules(),
- entry_points=await self._get_entry_points(),
+ architecture_summary=(
+ await self._get_architecture_summary() if "architecture" in s else ""
+ ),
+ key_modules=await self._get_key_modules() if "key_modules" in s else [],
+ entry_points=await self._get_entry_points() if "entry_points" in s else [],
tech_stack=detect_tech_stack(self._repo_path),
- hotspots=await self._get_hotspots(),
- decisions=await self._get_decisions(),
- build_commands=detect_build_commands(self._repo_path),
+ hotspots=await self._get_hotspots() if "hotspots" in s else [],
+ decisions=await self._get_decisions() if "decisions" in s else [],
+ build_commands=detect_build_commands(self._repo_path) if "commands" in s else {},
avg_confidence=await self._get_avg_confidence(),
- code_health=await self._get_code_health(),
+ code_health=(
+ await self._get_code_health(full="code_health" in s, fix_first="fix_first" in s)
+ if s & {"health", "code_health", "fix_first"}
+ else None
+ ),
kg_layers=kg_layers,
kg_tour=kg_tour,
index_scope=self._get_index_scope(),
+ sections=s,
)
def _get_index_scope(self) -> dict:
@@ -277,7 +294,6 @@ class EditorFileDataFetcher:
GitMetadata.file_path.asc(), # deterministic tie-break
)
)
- now = datetime.now(UTC)
hotspots: list[HotspotFile] = []
for row in result.all():
if len(hotspots) >= _MAX_HOTSPOTS:
@@ -285,12 +301,12 @@ class EditorFileDataFetcher:
if not (self._repo_path / row[0]).exists():
continue
last_fix_at = row[6]
- age: str | None = None
+ fixed_on: str | None = None
if isinstance(last_fix_at, datetime):
- # SQLite hands these back naive; re-attach UTC before subtracting
- # or the delta is wrong by the local offset (see signals.iso_utc).
+ # SQLite hands these back naive; re-attach UTC before converting
+ # or the date can shift by the local offset (see signals.iso_utc).
moment = last_fix_at if last_fix_at.tzinfo else last_fix_at.replace(tzinfo=UTC)
- age = _humanize_age(max(0, (now - moment).days))
+ fixed_on = moment.astimezone(UTC).strftime("%Y-%m-%d")
hotspots.append(
HotspotFile(
path=row[0],
@@ -298,9 +314,9 @@ class EditorFileDataFetcher:
commit_count_90d=row[2],
owner=row[3],
fix_count=row[4] or 0,
- # Never claim "bug magnet" without an age to anchor it.
- bug_magnet=bool(row[5]) and age is not None,
- last_fix_age=age,
+ # Never claim "bug magnet" without a date to anchor it.
+ bug_magnet=bool(row[5]) and fixed_on is not None,
+ last_fix_date=fixed_on,
)
)
return hotspots
@@ -361,11 +377,14 @@ class EditorFileDataFetcher:
avg = result.scalar_one_or_none()
return round(float(avg), 2) if avg is not None else 0.0
- async def _get_code_health(self) -> CodeHealthBlock | None:
+ async def _get_code_health(
+ self, *, full: bool = True, fix_first: bool = True
+ ) -> CodeHealthBlock | None:
"""Build the compact code-health block for CLAUDE.md.
- KPIs, then the lead of the Fix-first queue every other surface renders.
- ``None`` when no health data yet.
+ The headline KPIs, then (``full``) the pillar and performance figures and
+ (``fix_first``) the lead of the Fix-first queue every other surface
+ renders. ``None`` when no health data yet.
"""
# Scored rows only: a file in a language health has no dialect for
# carries no score, and a repository of nothing else has no block.
@@ -411,6 +430,18 @@ class EditorFileDataFetcher:
# line renders conditionally, drop this fallback and pass ``hotspot_kpi``
# straight through. Affects only repos with no recent churn at all.
hotspot_for_claude_md = hotspot_kpi if hotspot_kpi is not None else avg
+ band = headline_band(round(avg, 2), analysed_share(len(metric_rows), unanalysed))
+ headline = CodeHealthBlock(
+ hotspot_health=round(hotspot_for_claude_md, 2),
+ average_health=round(avg, 2),
+ band=BAND_LABEL[band] if band is not None else "",
+ analysed_note=analysed_note(len(metric_rows), unanalysed),
+ worst_score=round(worst.score, 2) if worst is not None else None,
+ worst_path=worst.file_path if worst is not None else None,
+ fix_first=await self._get_fix_first() if fix_first else [],
+ )
+ if not full:
+ return headline
# Maintainability pillar headline: NLOC-weighted over the per-file
# maintainability scores, skipping rows that predate the split. ``None``
@@ -457,14 +488,8 @@ class EditorFileDataFetcher:
self._session, self._repo_id, limit=DECLINE_LOOKBACK + 1
)
- band = headline_band(round(avg, 2), analysed_share(len(metric_rows), unanalysed))
- return CodeHealthBlock(
- hotspot_health=round(hotspot_for_claude_md, 2),
- average_health=round(avg, 2),
- band=BAND_LABEL[band] if band is not None else "",
- analysed_note=analysed_note(len(metric_rows), unanalysed),
- worst_score=round(worst.score, 2) if worst is not None else None,
- worst_path=worst.file_path if worst is not None else None,
+ return dataclasses.replace(
+ headline,
hotspot_trend=hotspot_trend(history),
maintainability_average=(
round(maintainability_average, 2) if maintainability_average is not None else None
@@ -478,7 +503,6 @@ class EditorFileDataFetcher:
),
performance_skipped_files=perf_coverage.skipped_files,
performance_unsupported_languages=perf_coverage.unsupported_languages,
- fix_first=await self._get_fix_first(),
)
async def _get_fix_first(self) -> list[dict]:
@@ -591,24 +615,6 @@ def _get_head_short_sha(repo_path: Path) -> str:
return ""
-def _humanize_age(days: int) -> str:
- """Render an age as "2 weeks ago" / "3 months ago", never as a bare count.
-
- Twin of the pre-edit hook's ``decision_inject._humanize_age``, which states
- why the two are not shared: that module is on a sub-100ms budget and cannot
- afford to import ``repowise.core``. Keep the phrasing in step by hand.
- """
- if days <= 1:
- return "today" if days <= 0 else "yesterday"
- if days < 14:
- return f"{days} days ago"
- if days < 60:
- weeks = round(days / 7)
- return f"{weeks} week{'' if weeks == 1 else 's'} ago"
- months = round(days / 30)
- return f"{months} month{'' if months == 1 else 's'} ago"
-
-
def _extract_sentences(text: str, max_sentences: int) -> str:
"""Return up to *max_sentences* prose sentences from the start of *text*.
diff --git a/packages/core/src/repowise/core/generation/editor_files/sections.py b/packages/core/src/repowise/core/generation/editor_files/sections.py
new file mode 100644
index 000000000..5e6ad29de
--- /dev/null
+++ b/packages/core/src/repowise/core/generation/editor_files/sections.py
@@ -0,0 +1,77 @@
+"""Which sections the generated editor-file block carries.
+
+The block is read into the agent's context on every turn, so the default is
+the lean set: what an agent acts on before an edit. ``editor_files.sections``
+in ``.repowise/config.yaml`` adjusts it with the grammar ``mcp.tools`` uses:
+``+name`` / ``-name`` add to or remove from the default, and unprefixed names
+are an explicit list that replaces it.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Iterable
+from pathlib import Path
+
+import structlog
+
+log = structlog.get_logger(__name__)
+
+DEFAULT_SECTIONS: frozenset[str] = frozenset(
+ {
+ "architecture",
+ "key_modules",
+ "entry_points",
+ "hotspots",
+ "health",
+ "decisions",
+ "how_to_work",
+ "tools",
+ }
+)
+
+OPT_IN_SECTIONS: frozenset[str] = frozenset(
+ {"code_health", "fix_first", "commands", "how_to_work_full"}
+)
+
+ALL_SECTIONS: frozenset[str] = DEFAULT_SECTIONS | OPT_IN_SECTIONS
+
+
+def resolve_sections(raw: object) -> frozenset[str]:
+ """The section set a config value names; the default when it names none.
+
+ Unknown names are dropped with a warning rather than failing the write,
+ because the block is regenerated on every update.
+ """
+ if raw is None:
+ return DEFAULT_SECTIONS
+ if isinstance(raw, str):
+ raw = [raw]
+ if isinstance(raw, dict) or not isinstance(raw, Iterable):
+ log.warning("editor_files.sections ignored: expected a list of names", value=raw)
+ return DEFAULT_SECTIONS
+ explicit: set[str] = set()
+ added: set[str] = set()
+ removed: set[str] = set()
+ for name in raw:
+ token = str(name).strip().lower()
+ prefix = token[:1] if token[:1] in ("+", "-") else ""
+ key = token[len(prefix) :]
+ if key not in ALL_SECTIONS:
+ log.warning("editor_files.sections: unknown section", section=name)
+ continue
+ {"+": added, "-": removed}.get(prefix, explicit).add(key)
+ base = explicit if explicit else set(DEFAULT_SECTIONS)
+ return frozenset((base | added) - removed)
+
+
+def load_sections(repo_path: Path) -> frozenset[str]:
+ """The section set ``.repowise/config.yaml`` asks for; the default on any read failure."""
+ from repowise.core.repo_config import load_repo_config
+
+ try:
+ editor_files = load_repo_config(repo_path).get("editor_files")
+ except Exception: # a broken config is reported by the commands that need it
+ return DEFAULT_SECTIONS
+ if not isinstance(editor_files, dict):
+ return DEFAULT_SECTIONS
+ return resolve_sections(editor_files.get("sections"))
diff --git a/packages/core/src/repowise/core/generation/templates/_editor_block.j2 b/packages/core/src/repowise/core/generation/templates/_editor_block.j2
new file mode 100644
index 000000000..0cda56ee6
--- /dev/null
+++ b/packages/core/src/repowise/core/generation/templates/_editor_block.j2
@@ -0,0 +1,97 @@
+{#- Shared body of claude_md.j2 and agents_md.j2; each sets `read_note` first. -#}
+{% set s = data.sections %}
+## Codebase Intelligence for {{ data.repo_name }} (Repowise)
+
+Last indexed: {{ data.indexed_at }}{% if data.indexed_commit %} (commit {{ data.indexed_commit }}){% endif %}.
+{% if data.scope_gaps %}
+Scope: {{ data.scope_gaps | join(' · ') }}. Missing evidence is not a negative finding.{% if data.upgrade_pending %} Run `repowise update --full` to continue the model-backed upgrade (cost is previewed before generation).{% endif %}
+
+{% endif %}
+{% if 'architecture' in s and data.architecture_summary %}
+
+### Architecture
+{{ data.architecture_summary }}
+{% endif %}
+{% if 'key_modules' in s and data.key_modules %}
+
+### Key modules
+{% for mod in data.key_modules %}
+- `{{ mod.name }}`{% if mod.purpose %} — {{ mod.purpose }}{% endif %}
+
+{% endfor %}
+{% endif %}
+{% if 'entry_points' in s and data.entry_points %}
+
+### Entry points
+{% for ep in data.entry_points[:6] %}
+- `{{ ep }}`
+{% endfor %}
+{% endif %}
+{% if 'hotspots' in s and data.hotspots %}
+
+### Files that need care (bug-fix history first, then churn — check `get_risk` before editing)
+{% for h in data.hotspots %}
+- `{{ h.path }}` — {% if h.fix_count and h.last_fix_date %}{{ h.fix_count }} bug fix{{ 'es' if h.fix_count != 1 else '' }}, last fix {{ h.last_fix_date }}{% if h.bug_magnet %} (bug magnet){% endif %}; {% endif %}{{ h.commit_count_90d }} commits/90d
+{% endfor %}
+{% endif %}
+{% set ch = data.code_health %}
+{% set fix_first = ch.fix_first if ch and 'fix_first' in s else [] %}
+{% if ch and ('health' in s or 'code_health' in s or fix_first) %}
+
+### Code health
+{% if 'code_health' in s %}
+Three co-equal signals: code health {{ ch.average_health }}/10 avg{% if ch.band or ch.analysed_note %} ({{ [ch.band, ch.analysed_note] | select | join(', ') }}){% endif %}, hotspot health {{ ch.hotspot_health }}/10{% if ch.hotspot_trend %} ({{ ch.hotspot_trend }}){% endif %}{% if ch.worst_path %}, worst `{{ ch.worst_path }}` at {{ ch.worst_score }}/10{% endif %}{% if ch.maintainability_average is not none %} · maintainability {{ ch.maintainability_average }}/10{% endif %}{% set perf = ch.performance_causes %}{% if ch.performance_average is not none and perf %} · performance {{ perf.now }} cause{{ 's' if perf.now != 1 else '' }} worth fixing now ({{ perf.production }} open in production code, {{ perf.all }} overall){% endif %}. Detail: `get_health()`.
+{% elif 'health' in s %}
+{{ ch.average_health }}/10 avg{% if ch.band or ch.analysed_note %} ({{ [ch.band, ch.analysed_note] | select | join(', ') }}){% endif %}{% if ch.worst_path %}, worst `{{ ch.worst_path }}` at {{ ch.worst_score }}/10{% endif %}. Detail: `get_health()`.
+{% endif %}
+{% if fix_first %}
+
+Fix first:
+{% for f in fix_first %}
+- {{ f.title }} (`{{ f.where }}`): {{ f.why }}
+{% endfor %}
+{% endif %}
+{% endif %}
+{% if 'decisions' in s and data.decisions %}
+
+### Standing decisions (ask `get_why` before diverging)
+{% for d in data.decisions[:3] %}
+- {{ d.title }}{{ d.signed_by }}
+{% endfor %}
+{% endif %}
+{% if 'how_to_work_full' in s %}
+
+### 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"` 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. {{ read_note }}
+- **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.
+- **Recording a decision** you had to reason out: `repowise decision add --title T --decision D` records it without prompting and prints the id (`--format json` to parse it back). It lands `proposed`, for a person to confirm.
+{% elif 'how_to_work' in s %}
+
+### How to work in this repo
+
+- **Pre-edit, not instead-of-edit.** These tools decide *which* files to read and edit. {{ read_note }} Bytes marked `verified: true` need no re-read; re-read only what `bounds: "approximate"` names. An empty `callers`/`used_by` comes with a `*_basis`: read it before concluding nothing calls a symbol.
+{% 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 %}
+- **Noisy commands** (tests, builds, `git log`/`diff`): prefer `repowise distill <cmd>`, same exit code, errors first. Recover a `[repowise#<ref>: N lines omitted]` marker with `repowise expand <ref>` (`-q <regex>` filters); never re-run the command.
+- **Record a decision** you reasoned out: `repowise decision add --title T --decision D` (lands `proposed` for a person to confirm).
+{% endif %}
+{% if 'tools' in s %}
+
+### Tools
+
+{{ data.tool_table_md }}
+{% endif %}
+{% if 'commands' in s and data.build_commands %}
+
+### Commands
+{% for label, cmd in data.build_commands.items() %}
+- {{ label | capitalize }}: `{{ cmd }}`
+{% endfor %}
+{% endif %}
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 3e30d9b31..ae718d70d 100644
--- a/packages/core/src/repowise/core/generation/templates/agents_md.j2
+++ b/packages/core/src/repowise/core/generation/templates/agents_md.j2
@@ -1,76 +1,2 @@
-## 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 and not data.keyless %}. Confidence: {{ (data.avg_confidence * 100) | int }}%.{% else %}.{% 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'] 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"` 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.
-- **Recording a decision** you had to reason out: `repowise decision add --title T --decision D` records it without prompting and prints the id (`--format json` to parse it back). It lands `proposed`, for a person to confirm.
-
-### Tools
-
-{{ data.tool_table_md }}
-{% if data.architecture_summary %}
-
-### Architecture
-{{ data.architecture_summary }}
-{% endif %}
-{% if data.key_modules %}
-
-### Key modules
-{% for mod in data.key_modules %}
-- `{{ mod.name }}`{% if mod.purpose %} — {{ mod.purpose }}{% endif %}
-
-{% endfor %}
-{% endif %}
-{% if data.entry_points %}
-
-### Entry points
-{% for ep in data.entry_points[:6] %}
-- `{{ ep }}`
-{% endfor %}
-{% endif %}
-{% if data.hotspots %}
-
-### Files that need care (bug-fix history first, then churn — check `get_risk` before editing)
-{% for h in data.hotspots %}
-- `{{ h.path }}` — {% if h.fix_count and h.last_fix_age %}{{ h.fix_count }} bug fix{{ 'es' if h.fix_count != 1 else '' }}, last fix {{ h.last_fix_age }}{% if h.bug_magnet %} (bug magnet){% endif %}; {% endif %}{{ h.commit_count_90d }} commits/90d
-{% endfor %}
-{% endif %}
-{% if data.code_health %}
-
-### Code health
-Three co-equal signals: code health {{ data.code_health.average_health }}/10 avg{% if data.code_health.band or data.code_health.analysed_note %} ({{ [data.code_health.band, data.code_health.analysed_note] | select | join(', ') }}){% endif %}, hotspot health {{ data.code_health.hotspot_health }}/10{% if data.code_health.hotspot_trend %} ({{ data.code_health.hotspot_trend }}){% endif %}{% if data.code_health.worst_path %}, worst `{{ data.code_health.worst_path }}` at {{ data.code_health.worst_score }}/10{% endif %}{% if data.code_health.maintainability_average is not none %} · maintainability {{ data.code_health.maintainability_average }}/10{% endif %}{% set perf = data.code_health.performance_causes %}{% if data.code_health.performance_average is not none and perf %} · performance {{ perf.now }} cause{{ 's' if perf.now != 1 else '' }} worth fixing now ({{ perf.production }} open in production code, {{ perf.all }} overall){% endif %}. Detail: `get_health()`.
-{% if data.code_health.fix_first %}
-
-Fix first:
-{% for f in data.code_health.fix_first %}
-- {{ f.title }} (`{{ f.where }}`): {{ f.why }}
-{% endfor %}
-{% endif %}
-{% endif %}
-{% if data.decisions %}
-
-### Standing decisions (ask `get_why` before diverging)
-{% for d in data.decisions[:3] %}
-- {{ d.title }}{{ d.signed_by }}{% if d.rationale %} — {{ d.rationale }}{% endif %}
-
-{% endfor %}
-{% endif %}
-{% if data.build_commands %}
-
-### Commands
-{% for label, cmd in data.build_commands.items() %}
-- {{ label | capitalize }}: `{{ cmd }}`
-{% endfor %}
-{% endif %}
+{% set read_note = "Reading a file before you edit it is correct and expected." %}
+{% include "_editor_block.j2" %}
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 879fe765e..24c60d14d 100644
--- a/packages/core/src/repowise/core/generation/templates/claude_md.j2
+++ b/packages/core/src/repowise/core/generation/templates/claude_md.j2
@@ -1,76 +1,2 @@
-## 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 and not data.keyless %}. Confidence: {{ (data.avg_confidence * 100) | int }}%.{% else %}.{% 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'] 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"` 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.
-- **Recording a decision** you had to reason out: `repowise decision add --title T --decision D` records it without prompting and prints the id (`--format json` to parse it back). It lands `proposed`, for a person to confirm.
-
-### Tools
-
-{{ data.tool_table_md }}
-{% if data.architecture_summary %}
-
-### Architecture
-{{ data.architecture_summary }}
-{% endif %}
-{% if data.key_modules %}
-
-### Key modules
-{% for mod in data.key_modules %}
-- `{{ mod.name }}`{% if mod.purpose %} — {{ mod.purpose }}{% endif %}
-
-{% endfor %}
-{% endif %}
-{% if data.entry_points %}
-
-### Entry points
-{% for ep in data.entry_points[:6] %}
-- `{{ ep }}`
-{% endfor %}
-{% endif %}
-{% if data.hotspots %}
-
-### Files that need care (bug-fix history first, then churn — check `get_risk` before editing)
-{% for h in data.hotspots %}
-- `{{ h.path }}` — {% if h.fix_count and h.last_fix_age %}{{ h.fix_count }} bug fix{{ 'es' if h.fix_count != 1 else '' }}, last fix {{ h.last_fix_age }}{% if h.bug_magnet %} (bug magnet){% endif %}; {% endif %}{{ h.commit_count_90d }} commits/90d
-{% endfor %}
-{% endif %}
-{% if data.code_health %}
-
-### Code health
-Three co-equal signals: code health {{ data.code_health.average_health }}/10 avg{% if data.code_health.band or data.code_health.analysed_note %} ({{ [data.code_health.band, data.code_health.analysed_note] | select | join(', ') }}){% endif %}, hotspot health {{ data.code_health.hotspot_health }}/10{% if data.code_health.hotspot_trend %} ({{ data.code_health.hotspot_trend }}){% endif %}{% if data.code_health.worst_path %}, worst `{{ data.code_health.worst_path }}` at {{ data.code_health.worst_score }}/10{% endif %}{% if data.code_health.maintainability_average is not none %} · maintainability {{ data.code_health.maintainability_average }}/10{% endif %}{% set perf = data.code_health.performance_causes %}{% if data.code_health.performance_average is not none and perf %} · performance {{ perf.now }} cause{{ 's' if perf.now != 1 else '' }} worth fixing now ({{ perf.production }} open in production code, {{ perf.all }} overall){% endif %}. Detail: `get_health()`.
-{% if data.code_health.fix_first %}
-
-Fix first:
-{% for f in data.code_health.fix_first %}
-- {{ f.title }} (`{{ f.where }}`): {{ f.why }}
-{% endfor %}
-{% endif %}
-{% endif %}
-{% if data.decisions %}
-
-### Standing decisions (ask `get_why` before diverging)
-{% for d in data.decisions[:3] %}
-- {{ d.title }}{{ d.signed_by }}{% if d.rationale %} — {{ d.rationale }}{% endif %}
-
-{% endfor %}
-{% endif %}
-{% if data.build_commands %}
-
-### Commands
-{% for label, cmd in data.build_commands.items() %}
-- {{ label | capitalize }}: `{{ cmd }}`
-{% endfor %}
-{% endif %}
+{% set read_note = "Claude Code requires a raw Read of any file you will Edit, and that Read is correct and expected." %}
+{% include "_editor_block.j2" %}
diff --git a/packages/core/src/repowise/core/generation/templates/workspace_claude_md.j2 b/packages/core/src/repowise/core/generation/templates/workspace_claude_md.j2
index 1bc7f1399..2da8855bf 100644
--- a/packages/core/src/repowise/core/generation/templates/workspace_claude_md.j2
+++ b/packages/core/src/repowise/core/generation/templates/workspace_claude_md.j2
@@ -56,8 +56,7 @@ Files that frequently change together across repos — consider reviewing both w
These tools work across all repos in this workspace. Pass `repo="alias"` to scope, `repo="all"` for cross-repo queries, or omit for the default 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.
-- **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.
+- **Trust the index.** Bytes marked `verified: true` need no re-read; re-read only what `bounds: "approximate"` names.
- **Workspace-specific:** `get_overview(repo="all")` returns cross-repo topology (co-changes, package deps, API contracts); `get_risk(changed_files=[...])` picks up cross-repo consumers automatically; `get_blast_radius` / `get_conformance` / `get_architecture` cover cross-repo impact, dependency-rule violations, and coupling.
{{ data.tool_table_md }}
diff --git a/tests/unit/generation/test_editor_file_base.py b/tests/unit/generation/test_editor_file_base.py
index 39d5e6322..531a79e42 100644
--- a/tests/unit/generation/test_editor_file_base.py
+++ b/tests/unit/generation/test_editor_file_base.py
@@ -53,9 +53,8 @@ def test_render_returns_non_empty_string(gen):
def test_render_never_references_repowise_repo_paths(gen):
# The generated file lands in USERS' repos — a `docs/layers/CODE_HEALTH.md`-style
# reference points at a file that only exists in the repowise repo itself.
- import dataclasses
- data = dataclasses.replace(_minimal_data(), code_health=_health_block(6.4))
+ data = _full_health(_health_block(6.4))
result = gen.render(data)
for repo_relative in ("docs/layers/CODE_HEALTH.md", "docs/agent/MCP_TOOLS.md", "docs/agent/DISTILL.md"):
assert repo_relative not in result
@@ -67,14 +66,14 @@ def test_render_contains_repo_name(gen):
assert "test-repo" in result
-def test_render_contains_index_scope_line_without_the_json(gen):
+def test_render_names_only_what_a_degraded_index_lacks(gen):
import dataclasses
data = dataclasses.replace(
_minimal_data(),
index_scope={
"run_mode": "fast",
- "content_provenance": "none",
+ "content_provenance": "model",
"git_tier": "essential",
"file_pages": {"eligible": 5, "generated": 0, "omitted": 5},
"analysis": {"unavailable": [], "skipped": ["generation"]},
@@ -82,15 +81,34 @@ def test_render_contains_index_scope_line_without_the_json(gen):
},
)
result = gen.render(data)
- assert "Scope: fast index · none content · essential Git" in result
- assert "5 eligible file pages omitted" in result
+ assert "Scope: essential Git history only · model upgrade pending." 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.
+ # read into every session, so it names the gaps only.
+ assert "eligible file pages omitted" not in result
+ assert "fast index" not in result
assert '"eligible": 5' not in result
- assert "Machine-readable scope" not in result
assert "repowise update --full" in result
+def test_a_complete_index_has_no_scope_line(gen):
+ import dataclasses
+
+ data = dataclasses.replace(
+ _minimal_data(),
+ index_scope={
+ "run_mode": "standard",
+ "content_provenance": "model",
+ "git_tier": "full",
+ "file_pages": {"eligible": 300, "generated": 48, "omitted": 252},
+ "upgrade": {"status": "complete"},
+ "search": {"full_text": "available", "semantic": "available"},
+ },
+ )
+ result = gen.render(data)
+ assert "Scope:" not in result
+ assert "Last indexed: 2026-03-28 (commit a1b2c3d).\n" in result
+
+
_KEYLESS_SCOPE = {
"run_mode": "standard",
"content_provenance": "template",
@@ -129,7 +147,7 @@ def test_keyless_index_gets_keyless_steering(any_gen):
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
+ assert "(commit a1b2c3d).\nScope: no model (template prose, full-text search)." 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
@@ -140,29 +158,14 @@ def test_keyless_index_gets_keyless_steering(any_gen):
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
+ # The header carries the date and commit only.
+ assert "Confidence:" not in result
+ assert "Scope: model upgrade resumable." in result
assert "repowise update --full" in result
assert "[fts]` only has no semantic agreement" in result
assert 'Cite `confidence: "high"`' in result
-def test_keyed_header_separates_confidence_from_scope(any_gen):
- # Regression for #3103: trim_blocks ate the newline after the confidence
- # sentence, gluing it to the scope sentence ("Confidence: 100%.Scope:").
- result = any_gen.render(_scoped(_KEYED_SCOPE))
- assert "Confidence: 100%. Scope:" in result
- assert ".Scope:" not in result
-
-
-def test_keyed_header_without_confidence_separates_commit_from_scope(any_gen):
- import dataclasses
-
- data = dataclasses.replace(_scoped(_KEYED_SCOPE), avg_confidence=0.0)
- result = any_gen.render(data)
- assert "(commit a1b2c3d). Scope:" in result
- assert ")Scope:" not in result
-
-
@pytest.mark.parametrize("scope", [_KEYLESS_SCOPE, _KEYED_SCOPE], ids=["keyless", "keyed"])
@pytest.mark.parametrize("upgrade", ["pending", "complete"])
def test_render_has_no_trailing_whitespace_or_double_blank_lines(any_gen, scope, upgrade):
@@ -177,15 +180,21 @@ def test_legacy_empty_scope_renders_keyed_text_and_no_scope_block(any_gen):
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
+ import dataclasses
+
+ # In-response warnings carry this guidance, so only the full section repeats it.
+ lean = any_gen.render(_minimal_data())
+ assert "_meta.stale_warning" not in lean
+ full = any_gen.render(
+ dataclasses.replace(_minimal_data(), sections=frozenset({"how_to_work_full"}))
+ )
+ assert "When `_meta.stale_warning` is set, Read the files that response served." in full
+ assert "`repowise update --working-tree`" in full
def _health_block(
@@ -208,6 +217,44 @@ def _health_block(
)
+_FULL_HEALTH = frozenset({"code_health"})
+
+
+def _full_health(block: CodeHealthBlock) -> EditorFileData:
+ import dataclasses
+
+ return dataclasses.replace(_minimal_data(), code_health=block, sections=_FULL_HEALTH)
+
+
+def test_the_default_health_line_is_the_headline_and_worst_file(gen):
+ import dataclasses
+
+ block = dataclasses.replace(
+ _health_block(
+ 6.4,
+ performance_average=9.2,
+ performance_causes=PerformanceHeadline(1, 7, 12, 2.5),
+ ),
+ fix_first=[{"title": "Split f", "where": "src/bad.py:3", "why": "long"}],
+ )
+ result = gen.render(dataclasses.replace(_minimal_data(), code_health=block))
+ assert "### Code health\n7.5/10 avg (Good), worst `src/bad.py` at 2.0/10." in result
+ for detail in ("hotspot health", "maintainability", "worth fixing now", "Fix first"):
+ assert detail not in result.split("### Tools")[0]
+
+
+def test_fix_first_is_opt_in(gen):
+ import dataclasses
+
+ block = dataclasses.replace(
+ _health_block(6.4), fix_first=[{"title": "Split f", "where": "src/bad.py:3", "why": "long"}]
+ )
+ data = dataclasses.replace(
+ _minimal_data(), code_health=block, sections=frozenset({"health", "fix_first"})
+ )
+ assert "- Split f (`src/bad.py:3`): long" in gen.render(data)
+
+
def test_the_headline_reads_the_same_direction_as_every_other_surface(gen):
"""A score out of ten beside a risk-shaped label reads inverted.
@@ -215,18 +262,16 @@ def test_the_headline_reads_the_same_direction_as_every_other_surface(gen):
an agent reads without a page around it, so it carries the same label and
the same band word rather than a bare number.
"""
- import dataclasses
- data = dataclasses.replace(_minimal_data(), code_health=_health_block(6.4))
+ data = _full_health(_health_block(6.4))
result = gen.render(data)
assert "code health 7.5/10 avg (Good)" in result
assert "defect risk 7.5" not in result
def test_the_headline_drops_the_band_when_it_is_unknown(gen):
- import dataclasses
- data = dataclasses.replace(_minimal_data(), code_health=_health_block(6.4, band=""))
+ data = _full_health(_health_block(6.4, band=""))
result = gen.render(data)
assert "code health 7.5/10 avg," in result
assert "avg ()" not in result
@@ -238,25 +283,23 @@ def test_the_headline_states_the_analysed_share(gen):
block = dataclasses.replace(
_health_block(6.4, band=""), analysed_note="analysed 4 of 435 code files"
)
- result = gen.render(dataclasses.replace(_minimal_data(), code_health=block))
+ result = gen.render(_full_health(block))
assert "code health 7.5/10 avg (analysed 4 of 435 code files)," in result
block = dataclasses.replace(block, band="Good")
- result = gen.render(dataclasses.replace(_minimal_data(), code_health=block))
+ result = gen.render(_full_health(block))
assert "avg (Good, analysed 4 of 435 code files)," in result
def test_render_surfaces_maintainability_when_present(gen):
- import dataclasses
- data = dataclasses.replace(_minimal_data(), code_health=_health_block(6.4))
+ data = _full_health(_health_block(6.4))
result = gen.render(data)
assert "maintainability 6.4/10" in result
def test_render_omits_maintainability_when_unmeasured(gen):
- import dataclasses
- data = dataclasses.replace(_minimal_data(), code_health=_health_block(None))
+ data = _full_health(_health_block(None))
result = gen.render(data)
# Defect-risk headline still renders; the maintainability clause is
# suppressed (the word still appears in the static tool table, so match
@@ -276,6 +319,7 @@ def test_render_surfaces_performance_when_present(gen):
performance_causes=PerformanceHeadline(1, 7, 12, 2.5),
performance_coverage_pct=88.0,
),
+ sections=_FULL_HEALTH,
)
result = gen.render(data)
# Leads with the causes worth fixing now, production and overall as context;
@@ -287,9 +331,8 @@ def test_render_surfaces_performance_when_present(gen):
def test_render_omits_performance_when_unmeasured(gen):
- import dataclasses
- data = dataclasses.replace(_minimal_data(), code_health=_health_block(6.4))
+ data = _full_health(_health_block(6.4))
result = gen.render(data)
# Maintainability still renders; the performance clause is suppressed.
assert "maintainability 6.4/10" in result
@@ -429,10 +472,10 @@ def test_render_hotspot_row_leads_with_fix_history(gen):
data = dataclasses.replace(
_minimal_data(),
- hotspots=[_hotspot("src/a.py", fix_count=5, bug_magnet=True, last_fix_age="2 weeks ago")],
+ hotspots=[_hotspot("src/a.py", fix_count=5, bug_magnet=True, last_fix_date="2026-03-14")],
)
result = gen.render(data)
- assert "5 bug fixes, last fix 2 weeks ago (bug magnet); 28 commits/90d" in result
+ assert "5 bug fixes, last fix 2026-03-14 (bug magnet); 28 commits/90d" in result
def test_render_hotspot_row_singularizes_one_fix(gen):
@@ -440,10 +483,10 @@ def test_render_hotspot_row_singularizes_one_fix(gen):
data = dataclasses.replace(
_minimal_data(),
- hotspots=[_hotspot("src/a.py", fix_count=1, last_fix_age="yesterday")],
+ hotspots=[_hotspot("src/a.py", fix_count=1, last_fix_date="2026-03-27")],
)
result = gen.render(data)
- assert "1 bug fix, last fix yesterday" in result
+ assert "1 bug fix, last fix 2026-03-27" in result
assert "1 bug fixes" not in result
@@ -465,7 +508,7 @@ def test_render_never_shows_a_fix_count_without_its_age(gen):
data = dataclasses.replace(
_minimal_data(),
- hotspots=[_hotspot("src/a.py", fix_count=9, bug_magnet=True, last_fix_age=None)],
+ hotspots=[_hotspot("src/a.py", fix_count=9, bug_magnet=True, last_fix_date=None)],
)
result = gen.render(data)
assert "9 bug fixes" not in result
diff --git a/tests/unit/generation/test_editor_file_fetcher.py b/tests/unit/generation/test_editor_file_fetcher.py
index 51d4c8723..7f01c7a35 100644
--- a/tests/unit/generation/test_editor_file_fetcher.py
+++ b/tests/unit/generation/test_editor_file_fetcher.py
@@ -326,7 +326,7 @@ async def test_fetch_hotspots_admits_bug_magnets_that_are_not_churn_hotspots(
assert paths == ["src/broken.py", "src/busy.py"] # fix evidence leads
assert data.hotspots[0].fix_count == 4
assert data.hotspots[0].bug_magnet is True
- assert data.hotspots[0].last_fix_age == "2 weeks ago"
+ assert data.hotspots[0].last_fix_date == (datetime.now(UTC) - timedelta(days=14)).strftime("%Y-%m-%d")
async def test_fetch_hotspots_falls_back_to_churn_order_without_fix_data(session, repo, tmp_path):
@@ -340,7 +340,7 @@ async def test_fetch_hotspots_falls_back_to_churn_order_without_fix_data(session
data = await EditorFileDataFetcher(session, repo.id, tmp_path).fetch()
assert [h.path for h in data.hotspots] == ["src/high.py", "src/low.py"]
- assert all(h.fix_count == 0 and h.last_fix_age is None for h in data.hotspots)
+ assert all(h.fix_count == 0 and h.last_fix_date is None for h in data.hotspots)
async def test_fetch_hotspots_drops_the_magnet_flag_when_recency_is_unknown(
@@ -362,7 +362,7 @@ async def test_fetch_hotspots_drops_the_magnet_flag_when_recency_is_unknown(
data = await EditorFileDataFetcher(session, repo.id, tmp_path).fetch()
assert data.hotspots[0].bug_magnet is False
- assert data.hotspots[0].last_fix_age is None
+ assert data.hotspots[0].last_fix_date is None
async def test_fetch_active_decisions_only(session, repo, tmp_path):
@@ -601,7 +601,7 @@ async def test_code_health_trend_is_read_from_the_snapshots(session, repo, tmp_p
taken_at=_now() + timedelta(days=day),
)
- data = await EditorFileDataFetcher(session, repo.id, tmp_path).fetch()
+ data = await EditorFileDataFetcher(session, repo.id, tmp_path, sections=["code_health"]).fetch()
assert data.code_health.hotspot_trend == "declining"
@@ -636,8 +636,65 @@ async def test_code_health_names_production_files_only(session, repo, tmp_path):
],
)
- data = await EditorFileDataFetcher(session, repo.id, tmp_path).fetch()
+ fetcher = EditorFileDataFetcher(session, repo.id, tmp_path, sections=["+fix_first"])
+ data = await fetcher.fetch()
assert data.code_health.worst_path == "src/a.py"
assert [f["where"] for f in data.code_health.fix_first] == ["src/a.py:1"]
assert data.code_health.fix_first[0]["title"] == "Reduce the branching in f"
+
+
+# ---------------------------------------------------------------------------
+# Sections: the fetcher reads only what the configured block renders
+# ---------------------------------------------------------------------------
+
+
+def _write_config(root: Path, text: str) -> None:
+ (root / ".repowise").mkdir(exist_ok=True)
+ (root / ".repowise" / "config.yaml").write_text(text, encoding="utf-8")
+
+
+async def test_the_lean_default_skips_commands_and_caps_decisions(session, repo, tmp_path):
+ (tmp_path / "package.json").write_text('{"scripts": {"test": "vitest"}}', encoding="utf-8")
+ for i in range(5):
+ await _add_decision(session, repo.id, f"Decision {i}")
+ await session.commit()
+
+ data = await EditorFileDataFetcher(session, repo.id, tmp_path).fetch()
+
+ assert data.build_commands == {}
+ assert len(data.decisions) == 3
+ assert "commands" not in data.sections
+
+
+async def test_config_sections_add_commands_back(session, repo, tmp_path):
+ (tmp_path / "package.json").write_text('{"scripts": {"test": "vitest"}}', encoding="utf-8")
+ _write_config(tmp_path, "editor_files:\n sections: [+commands]\n")
+
+ data = await EditorFileDataFetcher(session, repo.id, tmp_path).fetch()
+
+ assert data.build_commands == {"test": "npm run test"}
+ assert "hotspots" in data.sections and "commands" in data.sections
+
+
+async def test_a_section_left_out_is_never_queried(session, repo, tmp_path):
+ _touch(tmp_path, "src/a.py")
+ await _add_git_meta(session, repo.id, "src/a.py", is_hotspot=True)
+ await _add_decision(session, repo.id, "Use JWT")
+ await _add_metric(session, repo.id, "src/a.py", 7.0)
+ await session.commit()
+
+ data = await EditorFileDataFetcher(session, repo.id, tmp_path, sections=["tools"]).fetch()
+
+ assert data.hotspots == [] and data.decisions == [] and data.code_health is None
+
+
+async def test_the_default_health_line_skips_the_detail_queries(session, repo, tmp_path):
+ await _add_metric(session, repo.id, "src/a.py", 7.0)
+
+ data = await EditorFileDataFetcher(session, repo.id, tmp_path).fetch()
+
+ assert data.code_health.average_health == 7.0
+ assert data.code_health.worst_path == "src/a.py"
+ assert data.code_health.maintainability_average is None
+ assert data.code_health.fix_first == []
diff --git a/tests/unit/generation/test_editor_file_sections.py b/tests/unit/generation/test_editor_file_sections.py
new file mode 100644
index 000000000..6205894a2
--- /dev/null
+++ b/tests/unit/generation/test_editor_file_sections.py
@@ -0,0 +1,220 @@
+"""The ``editor_files.sections`` key and what each section renders."""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.core.generation.editor_files import AgentsMdGenerator, ClaudeMdGenerator
+from repowise.core.generation.editor_files.data import (
+ CodeHealthBlock,
+ DecisionSummary,
+ EditorFileData,
+ HotspotFile,
+ KeyModule,
+)
+from repowise.core.generation.editor_files.sections import (
+ ALL_SECTIONS,
+ DEFAULT_SECTIONS,
+ OPT_IN_SECTIONS,
+ load_sections,
+ resolve_sections,
+)
+
+
+def test_no_key_means_the_default():
+ assert resolve_sections(None) == DEFAULT_SECTIONS
+
+
+def test_prefixed_names_adjust_the_default():
+ assert resolve_sections(["+commands", "-decisions"]) == (DEFAULT_SECTIONS | {"commands"}) - {
+ "decisions"
+ }
+
+
+def test_the_list_replaces_the_default():
+ assert resolve_sections(["hotspots", "Tools"]) == {"hotspots", "tools"}
+
+
+def test_only_one_prefix_is_read():
+ assert resolve_sections(["--architecture"]) == DEFAULT_SECTIONS
+ assert resolve_sections({"commands": True}) == DEFAULT_SECTIONS
+
+
+def test_unknown_names_are_dropped():
+ assert resolve_sections(["hotspots", "nonsense"]) == {"hotspots"}
+
+
+def test_a_bare_string_is_one_name():
+ assert resolve_sections("commands") == {"commands"}
+
+
+def test_a_non_list_value_falls_back_to_the_default():
+ assert resolve_sections(7) == DEFAULT_SECTIONS
+
+
+def test_opt_in_names_are_not_in_the_default():
+ assert not OPT_IN_SECTIONS & DEFAULT_SECTIONS
+ assert {"code_health", "fix_first", "commands", "how_to_work_full"} <= ALL_SECTIONS
+
+
+def test_load_reads_the_repo_config(tmp_path):
+ (tmp_path / ".repowise").mkdir()
+ (tmp_path / ".repowise" / "config.yaml").write_text(
+ "editor_files:\n claude_md: true\n sections: [+fix_first]\n", encoding="utf-8"
+ )
+ assert load_sections(tmp_path) == DEFAULT_SECTIONS | {"fix_first"}
+
+
+def test_load_without_config_is_the_default(tmp_path):
+ assert load_sections(tmp_path) == DEFAULT_SECTIONS
+
+
+def test_a_broken_config_never_fails_the_write(tmp_path):
+ (tmp_path / ".repowise").mkdir()
+ (tmp_path / ".repowise" / "config.yaml").write_text("editor_files: [\n", encoding="utf-8")
+ assert load_sections(tmp_path) == DEFAULT_SECTIONS
+
+
+# ---------------------------------------------------------------------------
+# Rendering
+# ---------------------------------------------------------------------------
+
+
+def _full_data(**kw) -> EditorFileData:
+ base = {
+ "repo_name": "demo",
+ "indexed_at": "2026-10-19",
+ "indexed_commit": "a1b2c3d",
+ "architecture_summary": "A demo service.",
+ "key_modules": [KeyModule(name="src/api", purpose="HTTP layer", file_count=4, owner=None)],
+ "entry_points": ["src/main.py"],
+ "hotspots": [
+ HotspotFile(
+ path="src/api/routes.py",
+ churn_percentile=99.0,
+ commit_count_90d=12,
+ owner=None,
+ fix_count=4,
+ bug_magnet=True,
+ last_fix_date="2026-10-12",
+ )
+ ],
+ "decisions": [
+ DecisionSummary(title=f"Rule {i}", status="active", rationale="because") for i in range(4)
+ ],
+ "build_commands": {"test": "pytest"},
+ "code_health": CodeHealthBlock(
+ hotspot_health=6.0,
+ average_health=7.9,
+ band="Good",
+ worst_score=2.1,
+ worst_path="src/api/routes.py",
+ maintainability_average=8.0,
+ fix_first=[{"title": "Split route", "where": "src/api/routes.py:10", "why": "long"}],
+ ),
+ }
+ return EditorFileData(**{**base, **kw})
+
+
+_HEADINGS = {
+ "architecture": "### Architecture",
+ "key_modules": "### Key modules",
+ "entry_points": "### Entry points",
+ "hotspots": "### Files that need care",
+ "health": "### Code health",
+ "decisions": "### Standing decisions",
+ "how_to_work": "### How to work in this repo",
+ "tools": "### Tools",
+ "commands": "### Commands",
+}
+
+
[email protected](params=[ClaudeMdGenerator, AgentsMdGenerator], ids=["claude", "agents"])
+def gen(request):
+ return request.param()
+
+
[email protected]("section", sorted(_HEADINGS))
+def test_each_section_renders_only_when_listed(gen, section):
+ alone = gen.render(_full_data(sections=frozenset({section})))
+ assert _HEADINGS[section] in alone
+ others = [h for name, h in _HEADINGS.items() if name != section]
+ assert not [h for h in others if h in alone]
+
+
+def test_the_default_is_lean(gen):
+ lean = gen.render(_full_data())
+ full = gen.render(_full_data(sections=ALL_SECTIONS))
+ assert len(lean) < len(full)
+ assert "### Commands" not in lean
+ assert "Fix first" not in lean
+ assert "hotspot health" not in lean
+ # Decision titles only, at most three.
+ assert "- Rule 2\n" in lean and "Rule 3" not in lean
+ assert "because" not in lean
+
+
+def test_the_opt_in_sections_bring_the_detail_back(gen):
+ full = gen.render(_full_data(sections=ALL_SECTIONS))
+ assert "Three co-equal signals" in full
+ assert "maintainability 8.0/10" in full
+ assert "- Split route (`src/api/routes.py:10`): long" in full
+ assert "- Test: `pytest`" in full
+ assert "never re-read them" in full
+
+
+def test_repo_facts_lead_the_block(gen):
+ rendered = gen.render(_full_data())
+ order = [rendered.index(_HEADINGS[s]) for s in ("hotspots", "health", "how_to_work", "tools")]
+ assert order == sorted(order)
+
+
+def test_hotspot_rows_carry_a_date_not_an_age(gen):
+ rendered = gen.render(_full_data())
+ assert "4 bug fixes, last fix 2026-10-12 (bug magnet); 12 commits/90d" in rendered
+ assert " ago" not in rendered
+
+
+def test_zero_accepted_decisions_and_no_health_drop_their_sections(gen):
+ rendered = gen.render(_full_data(decisions=[], code_health=None))
+ assert "### Standing decisions" not in rendered
+ assert "### Code health" not in rendered
+ assert "\n\n\n" not in rendered
+
+
+def test_no_git_renders_without_commit_or_hotspots(gen):
+ rendered = gen.render(_full_data(indexed_commit="", hotspots=[]))
+ assert "Last indexed: 2026-10-19.\n" in rendered
+ assert "### Files that need care" not in rendered
+
+
+def test_the_doctor_stamp_survives(gen):
+ import re
+
+ rendered = gen.render(_full_data())
+ # `repowise doctor` reads the commit back out of this line.
+ assert re.search(r"Last indexed:.*?\(commit\s+([0-9a-fA-F]{7,})\)", rendered)
+
+
+def test_no_trailing_whitespace_in_any_section_mix(gen):
+ for sections in (DEFAULT_SECTIONS, ALL_SECTIONS, frozenset({"fix_first"}), frozenset()):
+ rendered = gen.render(_full_data(sections=sections))
+ assert not [line for line in rendered.splitlines() if line != line.rstrip()]
+ assert "\n\n\n" not in rendered
+
+
+def test_fix_first_alone_keeps_its_heading(gen):
+ rendered = gen.render(_full_data(sections=frozenset({"fix_first"})))
+ assert "### Code health\n\nFix first:" in rendered
+
+
+def test_the_shared_body_differs_only_in_the_read_note():
+ data = _full_data(sections=ALL_SECTIONS)
+ claude = ClaudeMdGenerator().render(data)
+ agents = AgentsMdGenerator().render(data)
+ assert "raw Read of any file you will Edit" in claude
+ assert "Reading a file before you edit it is correct and expected." in agents
+ assert claude.replace(
+ "Claude Code requires a raw Read of any file you will Edit, and that Read is correct and expected.",
+ "Reading a file before you edit it is correct and expected.",
+ ) == agents
diff --git a/tests/unit/generation/test_kg_claude_md_onboarding.py b/tests/unit/generation/test_kg_claude_md_onboarding.py
index 572d8af21..b4c76a0c4 100644
--- a/tests/unit/generation/test_kg_claude_md_onboarding.py
+++ b/tests/unit/generation/test_kg_claude_md_onboarding.py
@@ -107,31 +107,35 @@ class TestClaudeMdKGSection:
# No purpose → no dangling separator.
assert "- `src/core`\n" in rendered
- def test_workflow_protocol_leads(self, jinja_env):
+ def test_workflow_protocol_follows_the_repo_facts(self, jinja_env):
+ from repowise.core.generation.editor_files.data import HotspotFile
+
tmpl = jinja_env.get_template("claude_md.j2")
- rendered = tmpl.render(data=self._data())
+ hot = HotspotFile(path="src/a.py", churn_percentile=99.0, commit_count_90d=3, owner=None)
+ rendered = tmpl.render(data=self._data(entry_points=["src/main.py"], hotspots=[hot]))
assert "### How to work in this repo" in rendered
- # The trust rule survives as a bullet rather than its own section. The
- # separate "### Trust protocol" heading was five bullets of protocol for
- # a response shape the agent sees rarely, and it was cut for size; the
- # load-bearing clause is what has to stay reachable.
- assert "`verified: true`" in rendered
- assert "never re-read them" in rendered
- # `confidence` rates the prose; a low grade points at the evidence the
- # reply already named rather than at a second round-trip.
- assert "`candidate_files` the reply names" in rendered
- # An empty call-graph list is never served without the basis beside it.
+ # The load-bearing trust and basis clauses stay; the rest of the old
+ # bullets ride in the responses themselves (`_meta` hints, stale warnings).
+ assert "`verified: true` need no re-read" in rendered
+ assert '`bounds: "approximate"`' in rendered
assert "`*_basis`" in rendered
+ assert "never re-read them" not in rendered
# Pre-edit framing: the mandatory Read of edit targets is conceded.
assert "raw Read of any file you will Edit" in rendered
# The tool table renders from the single-source module.
assert "| Tool | When and why |" in rendered
assert "`get_answer(question)`" in rendered
- # Protocol comes before the repo-facts data blocks. Anchored on the
- # trust rule rather than on the first heading in the file, which would
- # be ordered correctly by construction and could not fail.
- if "Entry points" in rendered:
- assert rendered.index("`verified: true`") < rendered.index("Entry points")
+ # Repo facts lead: they are what an agent acts on before an edit.
+ protocol = rendered.index("### How to work in this repo")
+ assert rendered.index("### Entry points") < protocol
+ assert rendered.index("### Files that need care") < protocol
+
+ def test_the_full_protocol_is_opt_in(self, jinja_env):
+ tmpl = jinja_env.get_template("claude_md.j2")
+ rendered = tmpl.render(data=self._data(sections=frozenset({"how_to_work_full"})))
+ assert "never re-read them" in rendered
+ assert "`candidate_files` the reply names" in rendered
+ assert "`*_basis`" in rendered
# ---------------------------------------------------------------------------