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(generation): FAQ-weighted docs budget tilts depth toward asked-about modules (#781)

Raghav Chamadiya937529174b9d
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/command.py b/packages/cli/src/repowise/cli/commands/update_cmd/command.py
index 13d6bd200..c4050fec3 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/command.py
@@ -1067,6 +1067,11 @@ def run_update(
emitter.error(str(exc))
raise
+ # Surface the FAQ-weighted budget tilt when session demand shaped this run
+ # (silent when there is no history to weight; human console mode only).
+ if emitter is None and getattr(generator, "faq_demand_summary", None):
+ console.print(f"[dim]{generator.faq_demand_summary}[/dim]")
+
if checkpointer.failure:
degraded.append(f"Per-page crash checkpointing: {checkpointer.failure}")
diff --git a/packages/core/src/repowise/core/generation/page_generator/core.py b/packages/core/src/repowise/core/generation/page_generator/core.py
index 66ec63a65..1f090549e 100644
--- a/packages/core/src/repowise/core/generation/page_generator/core.py
+++ b/packages/core/src/repowise/core/generation/page_generator/core.py
@@ -160,6 +160,10 @@ class PageGenerator(PerTypeGenerationMixin):
# table.
self._prior_pages: dict[str, PriorPage] = prior_pages or {}
self._reuse_count: int = 0
+ # One-line summary of the FAQ-weighted budget tilt for this run, set by
+ # the orchestrator when session demand was found (else None). The CLI
+ # surfaces it after generation so the usage-weighting is visible.
+ self.faq_demand_summary: str | None = None
# Lazily computed by _generation_fingerprint(); every input it folds
# is fixed for the generator's lifetime.
self._gen_fingerprint: str | None = None
diff --git a/packages/core/src/repowise/core/generation/page_generator/orchestrate.py b/packages/core/src/repowise/core/generation/page_generator/orchestrate.py
index 341a84309..98d1bd019 100644
--- a/packages/core/src/repowise/core/generation/page_generator/orchestrate.py
+++ b/packages/core/src/repowise/core/generation/page_generator/orchestrate.py
@@ -236,6 +236,10 @@ class _GenerationRun:
# and one run stale on update. Inert unless
# module_grouping == "curated".
kg_modules=self.kg_modules or self.kg_ctx.get_modules() or None,
+ # Per-file question demand from session transcripts: tilts the
+ # file_page budget toward modules agents ask about. Empty (no
+ # session history / disabled) leaves selection uniform.
+ demand=self._compute_demand() or None,
)
)
@@ -267,6 +271,32 @@ class _GenerationRun:
),
)
+ def _compute_demand(self) -> dict[str, int]:
+ """Per-file question demand for the FAQ-weighted budget tilt.
+
+ Best-effort transcript sweep; any failure (no repo path, no session
+ history, mining error) yields an empty map and selection stays
+ uniform. Runs only on real generation — the cost estimator builds its
+ own demand-free SelectionInputs, so estimates are untouched.
+ """
+ if not self.repo_path:
+ return {}
+ try:
+ from repowise.core.repo_config import load_repo_config
+ from repowise.core.sessions.miners.demand import (
+ aggregate_file_demand,
+ demand_summary_line,
+ )
+
+ repo_config = load_repo_config(self.repo_path)
+ demand = aggregate_file_demand(self.repo_path, repo_config=repo_config)
+ # Surface the usage-weighting to the CLI (shown after generation).
+ self.gen.faq_demand_summary = demand_summary_line(demand)
+ return demand
+ except Exception as exc: # never let mining break generation
+ log.warning("page_selection.demand_failed", error=str(exc))
+ return {}
+
def _announce_total(self) -> None:
counts = self.selection.counts()
layer_page_count = 0
diff --git a/packages/core/src/repowise/core/generation/selection/__init__.py b/packages/core/src/repowise/core/generation/selection/__init__.py
index d8873f71f..cc3abe266 100644
--- a/packages/core/src/repowise/core/generation/selection/__init__.py
+++ b/packages/core/src/repowise/core/generation/selection/__init__.py
@@ -13,7 +13,12 @@ Import direction (one-way):
ingestion.models ← generation.models ← selection
"""
-from .budget import BucketAllocation, allocate_budget
+from .budget import (
+ BucketAllocation,
+ ModuleDemandRow,
+ allocate_budget,
+ allocate_module_file_pages,
+)
from .scoring import (
score_api_contract,
score_file,
@@ -32,10 +37,12 @@ from .selector import (
__all__ = [
"BucketAllocation",
+ "ModuleDemandRow",
"ModuleGroup",
"Selection",
"SelectionInputs",
"allocate_budget",
+ "allocate_module_file_pages",
"score_api_contract",
"score_file",
"score_infra",
diff --git a/packages/core/src/repowise/core/generation/selection/budget.py b/packages/core/src/repowise/core/generation/selection/budget.py
index c13312448..9e6c74f38 100644
--- a/packages/core/src/repowise/core/generation/selection/budget.py
+++ b/packages/core/src/repowise/core/generation/selection/budget.py
@@ -14,13 +14,20 @@ Design choices
its share (e.g. only 2 SCCs exist but share gives 5), the difference
is reallocated to the file_page bucket — file pages are the most
flexible bucket.
+
+FAQ-weighted tilt (:func:`allocate_module_file_pages`) is a second,
+optional layer: it keeps the *total* file_page count the bucket
+allocation produced but redistributes those slots across modules by how
+often agents ask about each, so hot modules get documented deeper and
+cold ones lean out. With no demand data it is an exact passthrough.
"""
from __future__ import annotations
+from collections import Counter, OrderedDict
+from collections.abc import Callable
from dataclasses import dataclass
-
# Page-type identifiers handled by the budget. Onboarding is curated and
# sized by ``len(specs)``; it is not budgeted here.
BUCKET_TYPES = (
@@ -168,3 +175,187 @@ def allocate_budget(
infra_page=raw["infra_page"],
scc_page=raw["scc_page"],
)
+
+
+# ---------------------------------------------------------------------------
+# FAQ-weighted per-module reallocation of the file_page budget.
+# ---------------------------------------------------------------------------
+
+#: A module keeps at least this many file pages when it had any in the
+#: demand-free baseline: the "lean baseline" floor of requirement (b). A
+#: well-covered but never-asked-about module leans down toward this floor to
+#: fund high-demand modules; it can never be zeroed out below it.
+LEAN_MODULE_FLOOR = 1
+
+
+@dataclass(frozen=True)
+class ModuleDemandRow:
+ """One module's line in the reallocation audit table."""
+
+ module: str
+ demand: int
+ baseline_pages: int
+ allocated_pages: int
+ candidates: int
+
+ @property
+ def delta(self) -> int:
+ return self.allocated_pages - self.baseline_pages
+
+
+def allocate_module_file_pages(
+ ranked_files: list[str],
+ total: int,
+ demand_by_file: dict[str, int] | None,
+ module_of: Callable[[str], str],
+) -> tuple[list[str], list[ModuleDemandRow]]:
+ """Pick *total* file pages from *ranked_files*, tilted by module demand.
+
+ ``ranked_files`` is the score-descending file-page candidate list.
+ ``module_of`` maps a path to its module key (the generation pipeline's
+ wiki-page granularity). Returns ``(selected_paths, audit_rows)``.
+
+ Guarantees:
+
+ - **Conservation.** ``len(selected) == min(total, len(ranked_files))``,
+ exactly what the demand-free top-*total* would emit. This reallocates
+ slots across modules; it never inflates the total.
+ - **Floor.** Every module with a baseline page keeps at least
+ :data:`LEAN_MODULE_FLOOR` (never dropped below today's lean baseline).
+ - **Determinism.** All ordering ties break on the module key, then the
+ original score rank, so identical inputs give identical output.
+ - **Zero-data passthrough.** ``demand_by_file`` empty (or resolving to no
+ in-repo demand) returns ``ranked_files[:total]`` unchanged, so a repo
+ with no session history is byte-identical to today.
+
+ ``audit_rows`` carries per-module demand, baseline vs. allocated page
+ counts, and available candidates for the inspectable dry-run.
+ """
+ if total <= 0:
+ return [], []
+ capped_total = min(total, len(ranked_files))
+ baseline = ranked_files[:capped_total]
+ if not demand_by_file:
+ return baseline, []
+
+ # Candidates grouped by module, preserving global score order.
+ mod_files: OrderedDict[str, list[str]] = OrderedDict()
+ for path in ranked_files:
+ mod_files.setdefault(module_of(path), []).append(path)
+
+ module_demand: dict[str, int] = {
+ module: sum(demand_by_file.get(p, 0) for p in paths) for module, paths in mod_files.items()
+ }
+ if not any(module_demand.values()):
+ return baseline, [] # demand exists but none of it lands on candidates
+
+ base_count = Counter(module_of(p) for p in baseline)
+ cap = {module: len(paths) for module, paths in mod_files.items()}
+
+ # Floor: modules with a baseline page keep LEAN_MODULE_FLOOR (bounded by
+ # their candidate supply and, defensively, by the total budget).
+ alloc: dict[str, int] = {module: 0 for module in mod_files}
+ reserved = 0
+ for module in mod_files:
+ if base_count.get(module, 0) >= 1:
+ floor = min(LEAN_MODULE_FLOOR, cap[module], capped_total - reserved)
+ alloc[module] = floor
+ reserved += floor
+
+ # Distribute the remaining slots by demand (largest-remainder, capped at
+ # each module's spare candidate supply). Ties break on the module key.
+ remaining = capped_total - reserved
+ _distribute_by_demand(alloc, cap, module_demand, remaining)
+
+ # Assemble the selection: each module's top-``alloc`` files, then spill any
+ # still-unfilled slots back down the demand-free ranking so the total is
+ # always met exactly (hot modules can saturate their candidate supply).
+ selected: list[str] = []
+ picked: set[str] = set()
+ for module, paths in mod_files.items():
+ for path in paths[: alloc[module]]:
+ selected.append(path)
+ picked.add(path)
+ if len(selected) < capped_total:
+ for path in ranked_files:
+ if path not in picked:
+ selected.append(path)
+ picked.add(path)
+ if len(selected) >= capped_total:
+ break
+
+ # Re-order to the global score ranking so downstream (landmarks, level
+ # ordering) sees the same shape it always has.
+ rank = {path: i for i, path in enumerate(ranked_files)}
+ selected.sort(key=lambda p: rank[p])
+
+ final_count = Counter(module_of(p) for p in selected)
+ audit = [
+ ModuleDemandRow(
+ module=module,
+ demand=module_demand.get(module, 0),
+ baseline_pages=base_count.get(module, 0),
+ allocated_pages=final_count.get(module, 0),
+ candidates=cap[module],
+ )
+ for module in mod_files
+ if module_demand.get(module, 0) or base_count.get(module, 0) != final_count.get(module, 0)
+ ]
+ audit.sort(key=lambda r: (-r.demand, r.module))
+ return selected, audit
+
+
+def _distribute_by_demand(
+ alloc: dict[str, int],
+ cap: dict[str, int],
+ module_demand: dict[str, int],
+ remaining: int,
+) -> None:
+ """Add *remaining* slots to *alloc* in proportion to demand, capped.
+
+ Largest-remainder apportionment over demand-carrying modules, then any
+ leftover (from flooring or saturated caps) goes one at a time to the
+ highest-demand module with spare capacity. Mutates *alloc* in place.
+ """
+ if remaining <= 0:
+ return
+ total_demand = sum(module_demand.values())
+ if total_demand <= 0:
+ return
+
+ # Proportional floor share, remembering the fractional remainder.
+ order = sorted(module_demand, key=lambda m: (-module_demand[m], m))
+ remainders: list[tuple[float, str]] = []
+ handed_out = 0
+ for module in order:
+ spare = cap[module] - alloc[module]
+ if spare <= 0 or module_demand[module] <= 0:
+ continue
+ exact = remaining * module_demand[module] / total_demand
+ give = min(int(exact), spare)
+ alloc[module] += give
+ handed_out += give
+ if give < spare:
+ remainders.append((exact - int(exact), module))
+
+ # Hand out the rounding leftover by largest fractional remainder, then by
+ # demand order for anything still unplaced.
+ leftover = remaining - handed_out
+ remainders.sort(key=lambda t: (-t[0], t[1]))
+ for _, module in remainders:
+ if leftover <= 0:
+ break
+ if cap[module] - alloc[module] > 0:
+ alloc[module] += 1
+ leftover -= 1
+ while leftover > 0:
+ progressed = False
+ for module in order:
+ if leftover <= 0:
+ break
+ if cap[module] - alloc[module] > 0:
+ alloc[module] += 1
+ leftover -= 1
+ progressed = True
+ if not progressed:
+ break # every demand module saturated; caller spills to baseline
diff --git a/packages/core/src/repowise/core/generation/selection/selector.py b/packages/core/src/repowise/core/generation/selection/selector.py
index dc9b07d75..95d59f5ea 100644
--- a/packages/core/src/repowise/core/generation/selection/selector.py
+++ b/packages/core/src/repowise/core/generation/selection/selector.py
@@ -18,7 +18,13 @@ import structlog
from repowise.core.ingestion.languages.registry import REGISTRY as _LANG_REGISTRY
from ..tour import DEFAULT_MAX_LANDMARKS, tour_landmark_paths
-from .budget import BucketAllocation, allocate_budget, compute_budget
+from .budget import (
+ BucketAllocation,
+ ModuleDemandRow,
+ allocate_budget,
+ allocate_module_file_pages,
+ compute_budget,
+)
from .scoring import (
score_api_contract,
score_file,
@@ -114,6 +120,12 @@ class SelectionInputs:
# ``config.module_grouping == "curated"``; ``None``/empty falls back to
# community grouping (the fallback-matrix "degraded" row).
kg_modules: list[dict] | None = None
+ # Per-file question demand mined from session transcripts
+ # (``core.sessions.miners.demand.aggregate_file_demand``): repo-relative
+ # path -> question count. Tilts the file_page budget toward high-demand
+ # modules. ``None``/empty reproduces the uniform, demand-free selection
+ # byte-for-byte (fresh installs with no session history).
+ demand: dict[str, int] | None = None
# ---------------------------------------------------------------------------
@@ -385,6 +397,82 @@ def _coverage_pct(cfg: Any) -> float:
return float(getattr(cfg, "coverage_pct", None) or getattr(cfg, "max_pages_pct", 0.20))
+def _build_file_module_map(
+ module_groups: list[tuple[float, ModuleGroup]],
+) -> dict[str, str]:
+ """Map each grouped file to its module key (the wiki-page granularity).
+
+ Built from every candidate module group, not just the selected top-K, so
+ demand attribution covers all grouped files. Files in no group fall back to
+ their top-level directory (:func:`_fallback_module`) at lookup time.
+ """
+ file_to_module: dict[str, str] = {}
+ for _, group in module_groups:
+ for path in group.file_paths:
+ file_to_module.setdefault(path, group.key)
+ return file_to_module
+
+
+def _fallback_module(path: str) -> str:
+ """Module key for a file in no group: its top-level directory.
+
+ Mirrors the ``top_dir`` grouping fallback the pipeline itself uses, so an
+ ungrouped file still attributes to a stable, human-legible bucket.
+ """
+ parts = Path(path).parts
+ return parts[0] if len(parts) > 1 else "root"
+
+
+def _select_file_pages(
+ files: list[tuple[float, str]],
+ file_page_budget: int,
+ module_groups: list[tuple[float, ModuleGroup]],
+ demand: dict[str, int] | None,
+) -> list[str]:
+ """The file_page allow-set, tilted toward high-demand modules.
+
+ Falls straight through to the demand-free top-``file_page_budget`` when
+ there is no demand, so behaviour is unchanged on fresh installs.
+ """
+ ranked = [p for _, p in files]
+ if not demand:
+ return ranked[:file_page_budget]
+
+ file_to_module = _build_file_module_map(module_groups)
+
+ def module_of(path: str) -> str:
+ return file_to_module.get(path) or _fallback_module(path)
+
+ selected, audit = allocate_module_file_pages(ranked, file_page_budget, demand, module_of)
+ _log_demand_tilt(audit, file_page_budget)
+ return selected
+
+
+def _log_demand_tilt(audit: list[ModuleDemandRow], file_page_budget: int) -> None:
+ """Emit the inspectable per-module reallocation table (dry-run audit)."""
+ if not audit:
+ return
+ moved = [r for r in audit if r.delta]
+ log.info(
+ "page_selection.demand_tilt",
+ file_page_budget=file_page_budget,
+ modules_reweighted=len(audit),
+ modules_moved=len(moved),
+ gained=sum(r.delta for r in moved if r.delta > 0),
+ table=[
+ {
+ "module": r.module,
+ "demand": r.demand,
+ "baseline": r.baseline_pages,
+ "allocated": r.allocated_pages,
+ "delta": r.delta,
+ "candidates": r.candidates,
+ }
+ for r in audit[:25]
+ ],
+ )
+
+
def _ensure_landmarks(selected: list[str], landmarks: list[str]) -> list[str]:
"""Guarantee every *landmark* is in *selected*, keeping the count honest.
@@ -442,10 +530,13 @@ def select_pages(inputs: SelectionInputs) -> Selection:
n_files=len(inputs.parsed_files),
)
+ # File pages, tilted toward the modules agents ask about most (demand-free
+ # top-K when there is no session data, so fresh installs are unchanged).
+ selected_files = _select_file_pages(files, allocation.file_page, modules, inputs.demand)
+
# The guided tour wants its highest-value entry points to land on real
# pages. Force those landmarks into the file_page allow-set, displacing the
# lowest-scored picks so the budget total stays honest (see _ensure_landmarks).
- selected_files = [p for _, p in files[: allocation.file_page]]
if selected_files or allocation.file_page > 0:
file_candidate_set = {p for _, p in files}
landmarks = [
diff --git a/packages/core/src/repowise/core/pipeline/phases/generation.py b/packages/core/src/repowise/core/pipeline/phases/generation.py
index 5eccbd0c9..de241f7d4 100644
--- a/packages/core/src/repowise/core/pipeline/phases/generation.py
+++ b/packages/core/src/repowise/core/pipeline/phases/generation.py
@@ -163,6 +163,10 @@ async def run_generation(
f"Onboarding: {len(slots_made)}/8 slots — {', '.join(slots_made)}",
)
progress.on_message("info", f"Generated {len(generated_pages)} pages")
+ # Surface the FAQ-weighted budget tilt when session demand shaped it
+ # (silent on fresh repos with no history — nothing to weight yet).
+ if getattr(generator, "faq_demand_summary", None):
+ progress.on_message("info", generator.faq_demand_summary)
_phase_done(progress, "onboarding")
_phase_done(progress, "generation")
diff --git a/packages/core/src/repowise/core/sessions/miners/demand.py b/packages/core/src/repowise/core/sessions/miners/demand.py
new file mode 100644
index 000000000..219f2acf5
--- /dev/null
+++ b/packages/core/src/repowise/core/sessions/miners/demand.py
@@ -0,0 +1,307 @@
+"""FAQ-weighted docs budget: mine per-file question demand from transcripts.
+
+The generation planner documents a repo uniformly by default: page budget is
+spread by graph centrality, blind to what agents actually ask about. This
+miner reads the shared :class:`~repowise.core.sessions.Event` stream and counts,
+per file, how many agent *questions* resolved to it: ``get_answer`` calls
+(attributed to the files their answer cited) and ``search_codebase`` calls
+(attributed to the files their hits resolved to). Rolled up to the module
+granularity the generation pipeline uses for wiki pages, those counts let the
+planner tilt documentation depth toward the modules agents keep asking about
+and lean out the cold ones (see
+``core.generation.selection.budget.allocate_module_file_pages``).
+
+Read-only and local: transcripts are read from the user's own machine and never
+leave it. No LLM, no writes. A repo with no session history yields an empty
+map, and the planner then reproduces its uniform behaviour byte-for-byte.
+
+Design notes
+------------
+- Demand is a *snapshot* signal, not accreting institutional memory, so this is
+ a full re-sweep each generation (like the gate's ``scan_usage``), not a
+ cursor-advanced incremental miner. It reads only question-bearing lines
+ (``_prefilter``), so the sweep stays cheap.
+- One question call contributes at most once per file it resolves to, capped
+ per call, so a single broad search can't flood a module's count.
+- Served/hit paths from the index are already repo-relative POSIX; attribution
+ keys on them directly and drops anything that isn't a plain in-repo path.
+"""
+
+from __future__ import annotations
+
+import json
+from collections import Counter
+from collections.abc import Callable, Iterable
+from pathlib import Path
+from typing import Any
+
+import structlog
+
+from repowise.core.sessions import ClaudeCodeAdapter, Event
+
+logger = structlog.get_logger(__name__)
+
+__all__ = [
+ "aggregate_file_demand",
+ "demand_summary_line",
+ "faq_weighting_enabled",
+ "mine_events_demand",
+ "rollup_to_modules",
+]
+
+#: repowise MCP tools whose results resolve to files. Kept narrow on purpose:
+#: get_context/get_symbol/get_risk targets are agent-chosen inputs, not the
+#: index answering a question, so they are not demand in the FAQ sense.
+_ANSWER_TOOL = "get_answer"
+_SEARCH_TOOL = "search_codebase"
+
+#: Per-call caps so one wide answer/search can't dominate a module's tally.
+_MAX_ANSWER_FILES = 5
+_MAX_SEARCH_FILES = 10
+
+#: Only these transcript lines can carry a question or its result; skipping the
+#: rest keeps the full-history sweep cheap.
+_PREFILTER_TOKENS = (
+ '"type":"user"',
+ '"type": "user"',
+ '"type":"assistant"',
+ '"type": "assistant"',
+)
+
+
+def faq_weighting_enabled(repo_config: dict[str, Any] | None) -> bool:
+ """Resolve the ``generation.faq_weighting`` config gate (default on)."""
+ cfg = repo_config or {}
+ gen_cfg = cfg.get("generation") or {}
+ if not isinstance(gen_cfg, dict):
+ return True
+ return gen_cfg.get("faq_weighting", True) is not False
+
+
+def _short_mcp(name: str) -> str | None:
+ """The bare repowise tool name for an MCP tool call, else None."""
+ if "repowise" not in name.lower():
+ # Direct (non-MCP) tool names never match a repowise tool.
+ return name if name in (_ANSWER_TOOL, _SEARCH_TOOL) else None
+ return name.rsplit("__", 1)[-1]
+
+
+def _result_text(content: Any) -> str:
+ if isinstance(content, str):
+ return content
+ if isinstance(content, list):
+ return " ".join(str(b.get("text", "")) for b in content if isinstance(b, dict))
+ return str(content or "")
+
+
+def _parse_result_json(text: str) -> dict[str, Any]:
+ try:
+ data = json.loads(text)
+ except (ValueError, TypeError):
+ return {}
+ if isinstance(data, dict) and isinstance(data.get("result"), dict):
+ return data["result"]
+ return data if isinstance(data, dict) else {}
+
+
+def _norm_rel(path: Any) -> str | None:
+ """Repo-relative POSIX path for an index-served reference, else None.
+
+ Strips a ``::symbol`` suffix and a trailing ``:line-range`` so a symbol id
+ or ranged reference attributes to its file. Rejects absolute paths, drive
+ letters, and parent escapes, none of which the index emits for in-repo
+ files.
+ """
+ if not isinstance(path, str):
+ return None
+ p = path.strip().replace("\\", "/")
+ if not p:
+ return None
+ p = p.split("::", 1)[0] # symbol id -> file
+ # Trailing line range on a bare path (``a/b.py:10-40`` or ``a/b.py:10``).
+ head, sep, tail = p.rpartition(":")
+ if sep and head and all(c.isdigit() or c == "-" for c in tail):
+ p = head
+ while p.startswith("./"):
+ p = p[2:]
+ if not p or p.startswith("/") or ".." in p.split("/") or ":" in p:
+ return None
+ return p
+
+
+def _answer_files(result: dict[str, Any]) -> list[str]:
+ """Files a ``get_answer`` response resolved to, most-grounded first."""
+ files: list[str] = []
+ files.extend(f for f in result.get("citations") or [] if isinstance(f, str))
+ for q in result.get("quotes") or []:
+ if isinstance(q, dict) and isinstance(q.get("path"), str):
+ files.append(q["path"])
+ for r in result.get("retrieval") or []:
+ if isinstance(r, dict):
+ hit = r.get("path") or r.get("target_path")
+ if isinstance(hit, str):
+ files.append(hit)
+ for g in result.get("best_guesses") or []:
+ if isinstance(g, dict) and isinstance(g.get("file"), str):
+ files.append(g["file"])
+ return files
+
+
+def _search_files(result: dict[str, Any]) -> list[str]:
+ """Files a ``search_codebase`` response's hits resolved to, in rank order."""
+ files: list[str] = []
+ for item in result.get("results") or []:
+ if not isinstance(item, dict):
+ continue
+ hit = item.get("file") or item.get("target_path") or item.get("symbol_id")
+ if isinstance(hit, str):
+ files.append(hit)
+ return files
+
+
+def _attribute(files: Iterable[str], cap: int, demand: Counter) -> None:
+ """Count each distinct in-repo file once, up to *cap* files for this call."""
+ seen: set[str] = set()
+ for raw in files:
+ rel = _norm_rel(raw)
+ if rel is None or rel in seen:
+ continue
+ seen.add(rel)
+ demand[rel] += 1
+ if len(seen) >= cap:
+ break
+
+
+def mine_events_demand(events: Iterable[Event], repo_prefix: str) -> Counter:
+ """Per-file question demand over one session's events (pure, streaming).
+
+ *repo_prefix* is the lowercased resolved repo root; only events whose
+ ``cwd`` sits inside it count, matching the distill/decision miners. Pairs
+ each ``get_answer`` / ``search_codebase`` call to its result by tool-use id
+ and attributes the call to the files the result named.
+ """
+ demand: Counter = Counter()
+ #: tool_use id -> short tool name, awaiting its result.
+ pending: dict[str, str] = {}
+
+ for event in events:
+ cwd = (event.cwd or "").lower().rstrip("\\/")
+ if cwd and not cwd.startswith(repo_prefix):
+ continue
+
+ for use in event.tool_uses:
+ short = _short_mcp(use.name)
+ if short in (_ANSWER_TOOL, _SEARCH_TOOL):
+ pending[use.id] = short
+ # Results normally arrive within a couple of events; cap orphans.
+ while len(pending) > 200:
+ pending.pop(next(iter(pending)))
+
+ for result in event.tool_results:
+ tool = pending.pop(result.tool_use_id, None)
+ if tool is None:
+ continue
+ parsed = _parse_result_json(_result_text(result.content))
+ if not parsed:
+ continue
+ if tool == _ANSWER_TOOL:
+ _attribute(_answer_files(parsed), _MAX_ANSWER_FILES, demand)
+ else:
+ _attribute(_search_files(parsed), _MAX_SEARCH_FILES, demand)
+
+ return demand
+
+
+def _prefilter(raw: str) -> bool:
+ return any(tok in raw for tok in _PREFILTER_TOKENS)
+
+
+def aggregate_file_demand(
+ repo_path: Path | str,
+ *,
+ adapter: ClaudeCodeAdapter | None = None,
+ projects_root: Path | None = None,
+ repo_config: dict[str, Any] | None = None,
+) -> dict[str, int]:
+ """Per-file question demand for *repo_path* from its transcript history.
+
+ Full best-effort sweep over the repo's Claude Code transcripts. Returns
+ ``{repo_relative_path: question_count}``; an empty dict when FAQ weighting
+ is disabled, no transcripts exist, or anything goes wrong (the planner then
+ falls back to its uniform behaviour). Never raises.
+ """
+ if not faq_weighting_enabled(repo_config):
+ return {}
+ repo_root = Path(repo_path).resolve()
+ repo_prefix = str(repo_root).lower().rstrip("\\/")
+ adapter = adapter or ClaudeCodeAdapter()
+
+ demand: Counter = Counter()
+ try:
+ transcripts = adapter.discover(repo_root, projects_root=projects_root)
+ except OSError:
+ return {}
+
+ for path in transcripts:
+ try:
+ with path.open("rb") as fh:
+ events = _iter_events(adapter, fh)
+ demand.update(mine_events_demand(events, repo_prefix))
+ except OSError:
+ continue
+
+ if demand:
+ logger.info(
+ "faq_demand.aggregated",
+ transcripts=len(transcripts),
+ files_with_demand=len(demand),
+ total_questions=sum(demand.values()),
+ )
+ return dict(demand)
+
+
+def _iter_events(adapter: ClaudeCodeAdapter, fh: Iterable[bytes]) -> Iterable[Event]:
+ """Normalized events from prefiltered transcript lines."""
+ for raw in fh:
+ line = raw.decode("utf-8", errors="replace")
+ if not _prefilter(line):
+ continue
+ event = adapter.normalize(line)
+ if event is not None:
+ yield event
+
+
+def demand_summary_line(file_demand: dict[str, int]) -> str | None:
+ """A one-line, human summary of the demand behind the budget tilt.
+
+ ``None`` when there is no demand (nothing to say, keeps fresh installs
+ quiet). Reports only exact, non-eroding counts: files and questions.
+ """
+ if not file_demand:
+ return None
+ questions = sum(file_demand.values())
+ files = len(file_demand)
+ return (
+ f"FAQ-weighted docs: tilted page budget toward the files behind "
+ f"{questions} question{'s' if questions != 1 else ''} across "
+ f"{files} file{'s' if files != 1 else ''} in this repo's session history."
+ )
+
+
+def rollup_to_modules(
+ file_demand: dict[str, int],
+ file_to_module: Callable[[str], str | None] | dict[str, str],
+) -> dict[str, int]:
+ """Roll per-file demand up to modules via *file_to_module*.
+
+ *file_to_module* maps a repo-relative path to its module key (the same
+ granularity the generation pipeline groups wiki pages by), or a plain dict.
+ Files that map to ``None`` are dropped. Deterministic; empty in, empty out.
+ """
+ resolve = file_to_module.get if isinstance(file_to_module, dict) else file_to_module
+ modules: Counter = Counter()
+ for path, count in file_demand.items():
+ module = resolve(path)
+ if module:
+ modules[module] += count
+ return dict(modules)
diff --git a/tests/unit/generation/test_selection_demand.py b/tests/unit/generation/test_selection_demand.py
new file mode 100644
index 000000000..187b79d53
--- /dev/null
+++ b/tests/unit/generation/test_selection_demand.py
@@ -0,0 +1,193 @@
+"""FAQ-weighted per-module file_page reallocation tests.
+
+Exercises the pure allocator (:func:`allocate_module_file_pages`) and the
+selector glue (:func:`_select_file_pages`) that maps files to modules. The
+contract under test: reallocate the file_page budget toward high-demand
+modules while conserving the total, flooring cold modules, staying
+deterministic, and reproducing the demand-free selection byte-for-byte when
+there is no session data.
+"""
+
+from __future__ import annotations
+
+from repowise.core.generation.selection.budget import (
+ LEAN_MODULE_FLOOR,
+ allocate_module_file_pages,
+)
+from repowise.core.generation.selection.selector import (
+ ModuleGroup,
+ _fallback_module,
+ _select_file_pages,
+)
+
+
+def _module_of(path: str) -> str:
+ return path.split("/")[0]
+
+
+# Nine candidates, score-descending: module a=3, b=2, c=4 files.
+RANKED = ["a/1", "a/2", "a/3", "b/1", "b/2", "c/1", "c/2", "c/3", "c/4"]
+
+
+# ---------------------------------------------------------------------------
+# Passthrough (zero-data byte-identity)
+# ---------------------------------------------------------------------------
+
+
+def test_empty_demand_is_exact_passthrough():
+ selected, audit = allocate_module_file_pages(RANKED, 4, {}, _module_of)
+ assert selected == RANKED[:4]
+ assert audit == []
+
+
+def test_none_demand_is_exact_passthrough():
+ selected, audit = allocate_module_file_pages(RANKED, 4, None, _module_of)
+ assert selected == RANKED[:4]
+ assert audit == []
+
+
+def test_demand_not_on_candidates_is_passthrough():
+ # Demand names files that are not candidates -> nothing to tilt.
+ selected, audit = allocate_module_file_pages(RANKED, 4, {"gone/old.py": 99}, _module_of)
+ assert selected == RANKED[:4]
+ assert audit == []
+
+
+# ---------------------------------------------------------------------------
+# Conservation
+# ---------------------------------------------------------------------------
+
+
+def test_total_is_conserved():
+ selected, _ = allocate_module_file_pages(RANKED, 4, {"c/1": 10}, _module_of)
+ assert len(selected) == 4
+
+
+def test_total_capped_at_candidate_supply():
+ selected, _ = allocate_module_file_pages(RANKED, 99, {"c/1": 10}, _module_of)
+ assert len(selected) == len(RANKED)
+ assert set(selected) == set(RANKED)
+
+
+def test_zero_budget_returns_empty():
+ selected, audit = allocate_module_file_pages(RANKED, 0, {"c/1": 10}, _module_of)
+ assert selected == []
+ assert audit == []
+
+
+# ---------------------------------------------------------------------------
+# Floor + tilt
+# ---------------------------------------------------------------------------
+
+
+def test_single_module_skew_deepens_hot_and_floors_cold():
+ # All demand on module c (baseline gave c zero pages). Budget 4.
+ # Baseline: a/1,a/2,a/3,b/1 -> a=3, b=1, c=0.
+ demand = {"c/1": 10, "c/2": 10}
+ selected, _audit = allocate_module_file_pages(RANKED, 4, demand, _module_of)
+
+ assert len(selected) == 4
+ counts = {m: sum(1 for p in selected if _module_of(p) == m) for m in "abc"}
+ # Hot module deepened from 0 -> 2; well-covered cold module a leaned to
+ # its floor; b kept its floor.
+ assert counts["c"] == 2
+ assert counts["a"] == LEAN_MODULE_FLOOR
+ assert counts["b"] == LEAN_MODULE_FLOOR
+ # The floor keeps each cold module's single most important file.
+ assert "a/1" in selected and "b/1" in selected
+ assert "a/2" not in selected and "a/3" not in selected
+
+
+def test_floor_never_drops_a_baseline_module_below_lean():
+ # Every module has a baseline page; demand piles entirely on one. No
+ # module with a baseline page may vanish.
+ ranked = ["a/1", "b/1", "c/1", "a/2", "b/2", "c/2"]
+ demand = {"a/1": 50, "a/2": 50}
+ selected, _ = allocate_module_file_pages(ranked, 3, demand, _module_of)
+ modules = {_module_of(p) for p in selected}
+ assert {"a", "b", "c"} <= modules # b and c floored in, not zeroed
+ assert len(selected) == 3
+
+
+def test_hot_module_saturates_then_spills_to_baseline():
+ # Demand on module b, but b has only 2 candidates. Extra budget spills
+ # back down the demand-free ranking rather than inflating b past supply.
+ demand = {"b/1": 100, "b/2": 100}
+ selected, _ = allocate_module_file_pages(RANKED, 6, demand, _module_of)
+ assert len(selected) == 6
+ b_count = sum(1 for p in selected if _module_of(p) == "b")
+ assert b_count == 2 # capped at b's candidate supply
+
+
+# ---------------------------------------------------------------------------
+# Determinism + audit
+# ---------------------------------------------------------------------------
+
+
+def test_deterministic_across_runs():
+ demand = {"c/1": 10, "c/2": 5, "b/1": 5}
+ first, _ = allocate_module_file_pages(RANKED, 5, demand, _module_of)
+ second, _ = allocate_module_file_pages(RANKED, 5, demand, _module_of)
+ assert first == second
+
+
+def test_selected_is_ordered_by_original_rank():
+ demand = {"c/1": 10, "c/2": 10}
+ selected, _ = allocate_module_file_pages(RANKED, 4, demand, _module_of)
+ rank = {p: i for i, p in enumerate(RANKED)}
+ assert selected == sorted(selected, key=lambda p: rank[p])
+
+
+def test_audit_reports_demand_and_movement():
+ demand = {"c/1": 10, "c/2": 10}
+ _, audit = allocate_module_file_pages(RANKED, 4, demand, _module_of)
+ rows = {r.module: r for r in audit}
+ assert rows["c"].demand == 20
+ assert rows["c"].baseline_pages == 0
+ assert rows["c"].allocated_pages == 2
+ assert rows["c"].delta == 2
+ # Audit is demand-descending.
+ assert audit[0].module == "c"
+
+
+# ---------------------------------------------------------------------------
+# Selector glue: file -> module mapping
+# ---------------------------------------------------------------------------
+
+
+def _group(key: str, files: tuple[str, ...]) -> tuple[float, ModuleGroup]:
+ return (
+ 1.0,
+ ModuleGroup(key=key, display=key, language="python", file_paths=files),
+ )
+
+
+def test_fallback_module_is_top_dir():
+ assert _fallback_module("pkg/sub/x.py") == "pkg"
+ assert _fallback_module("root_file.py") == "root"
+
+
+def test_select_file_pages_passthrough_without_demand():
+ files = [(9.0, "a/1"), (8.0, "a/2"), (7.0, "b/1")]
+ groups = [_group("a", ("a/1", "a/2")), _group("b", ("b/1",))]
+ assert _select_file_pages(files, 2, groups, None) == ["a/1", "a/2"]
+
+
+def test_select_file_pages_tilts_by_module_group():
+ # Module groups define the granularity; demand on group b pulls its file in.
+ files = [(9.0, "a/1"), (8.0, "a/2"), (7.0, "b/1")]
+ groups = [_group("a", ("a/1", "a/2")), _group("b", ("b/1",))]
+ demand = {"b/1": 20}
+ selected = _select_file_pages(files, 2, groups, demand)
+ assert "b/1" in selected # hot module's file forced in
+ assert len(selected) == 2
+
+
+def test_select_file_pages_uses_fallback_for_ungrouped_file():
+ # c/1 is in no module group -> attributed to its top-dir "c".
+ files = [(9.0, "a/1"), (8.0, "a/2"), (7.0, "c/1")]
+ groups = [_group("a", ("a/1", "a/2"))]
+ demand = {"c/1": 20}
+ selected = _select_file_pages(files, 2, groups, demand)
+ assert "c/1" in selected
+ assert len(selected) == 2
diff --git a/tests/unit/sessions/test_demand_miner.py b/tests/unit/sessions/test_demand_miner.py
new file mode 100644
index 000000000..8e30dc3f8
--- /dev/null
+++ b/tests/unit/sessions/test_demand_miner.py
@@ -0,0 +1,252 @@
+"""Tests for the FAQ-weighted docs-budget demand miner.
+
+Covers per-file attribution from get_answer / search_codebase results, module
+rollup (the attribution the planner budgets on), empty-store passthrough, and
+single-module skew.
+"""
+
+from __future__ import annotations
+
+import json
+
+from repowise.core.sessions import Event, ToolResult, ToolUse
+from repowise.core.sessions.miners.demand import (
+ _norm_rel,
+ aggregate_file_demand,
+ demand_summary_line,
+ faq_weighting_enabled,
+ mine_events_demand,
+ rollup_to_modules,
+)
+
+REPO_PREFIX = "c:\\users\\x\\repo"
+CWD = "C:\\Users\\x\\repo"
+
+
+def _answer_call(use_id: str = "a1", name: str = "mcp__repowise__get_answer") -> Event:
+ return Event(kind="assistant", cwd=CWD, tool_uses=[ToolUse(id=use_id, name=name, input={})])
+
+
+def _search_call(use_id: str = "s1", name: str = "mcp__repowise__search_codebase") -> Event:
+ return Event(kind="assistant", cwd=CWD, tool_uses=[ToolUse(id=use_id, name=name, input={})])
+
+
+def _result(use_id: str, payload: dict) -> Event:
+ # The demand miner reads the message-level result block content, which the
+ # adapter fills from the tool_result block's ``content`` (a JSON string).
+ return Event(
+ kind="user",
+ cwd=CWD,
+ tool_results=[ToolResult(tool_use_id=use_id, content=json.dumps(payload))],
+ )
+
+
+# ---------------------------------------------------------------------------
+# _norm_rel
+# ---------------------------------------------------------------------------
+
+
+def test_norm_rel_strips_symbol_and_line_range():
+ assert _norm_rel("pkg/mod.py::Thing") == "pkg/mod.py"
+ assert _norm_rel("pkg/mod.py:10-40") == "pkg/mod.py"
+ assert _norm_rel("pkg/mod.py:12") == "pkg/mod.py"
+ assert _norm_rel("./pkg/mod.py") == "pkg/mod.py"
+ assert _norm_rel("pkg\\mod.py") == "pkg/mod.py"
+
+
+def test_norm_rel_rejects_non_repo_paths():
+ assert _norm_rel("/abs/path.py") is None
+ assert _norm_rel("C:/Users/x/repo/f.py") is None # drive letter -> absolute
+ assert _norm_rel("../outside.py") is None
+ assert _norm_rel("") is None
+ assert _norm_rel(None) is None
+
+
+# ---------------------------------------------------------------------------
+# get_answer attribution
+# ---------------------------------------------------------------------------
+
+
+def test_get_answer_attributes_to_citations():
+ events = [
+ _answer_call("a1"),
+ _result("a1", {"citations": ["pkg/a.py", "pkg/b.py"]}),
+ ]
+ demand = mine_events_demand(events, REPO_PREFIX)
+ assert demand == {"pkg/a.py": 1, "pkg/b.py": 1}
+
+
+def test_get_answer_reads_nested_result_envelope():
+ # Real MCP results wrap the payload under a top-level "result" key.
+ events = [
+ _answer_call("a1"),
+ _result("a1", {"result": {"citations": ["pkg/a.py"], "quotes": [{"path": "pkg/c.py"}]}}),
+ ]
+ demand = mine_events_demand(events, REPO_PREFIX)
+ assert demand == {"pkg/a.py": 1, "pkg/c.py": 1}
+
+
+def test_get_answer_dedups_and_caps_per_call():
+ # Same file cited many ways counts once; >5 distinct files caps at 5.
+ payload = {
+ "citations": ["pkg/a.py", "pkg/a.py"],
+ "best_guesses": [{"file": f"pkg/f{i}.py"} for i in range(10)],
+ }
+ events = [_answer_call("a1"), _result("a1", payload)]
+ demand = mine_events_demand(events, REPO_PREFIX)
+ assert demand["pkg/a.py"] == 1
+ assert sum(demand.values()) == 5 # per-call cap
+
+
+# ---------------------------------------------------------------------------
+# search_codebase attribution
+# ---------------------------------------------------------------------------
+
+
+def test_search_attributes_to_hit_files_and_symbols():
+ payload = {
+ "results": [
+ {"file": "pkg/a.py"},
+ {"target_path": "pkg/b.py"},
+ {"symbol_id": "pkg/c.py::Thing"},
+ ]
+ }
+ events = [_search_call("s1"), _result("s1", payload)]
+ demand = mine_events_demand(events, REPO_PREFIX)
+ assert demand == {"pkg/a.py": 1, "pkg/b.py": 1, "pkg/c.py": 1}
+
+
+def test_two_calls_accumulate():
+ events = [
+ _answer_call("a1"),
+ _result("a1", {"citations": ["pkg/a.py"]}),
+ _search_call("s1"),
+ _result("s1", {"results": [{"file": "pkg/a.py"}]}),
+ ]
+ demand = mine_events_demand(events, REPO_PREFIX)
+ assert demand == {"pkg/a.py": 2}
+
+
+# ---------------------------------------------------------------------------
+# scoping + robustness
+# ---------------------------------------------------------------------------
+
+
+def test_events_outside_repo_prefix_are_skipped():
+ other = Event(
+ kind="assistant",
+ cwd="C:\\Users\\x\\other-repo",
+ tool_uses=[ToolUse(id="a1", name="mcp__repowise__get_answer", input={})],
+ )
+ result = Event(
+ kind="user",
+ cwd="C:\\Users\\x\\other-repo",
+ tool_results=[
+ ToolResult(tool_use_id="a1", content=json.dumps({"citations": ["pkg/a.py"]}))
+ ],
+ )
+ assert mine_events_demand([other, result], REPO_PREFIX) == {}
+
+
+def test_empty_store_yields_empty():
+ assert mine_events_demand([], REPO_PREFIX) == {}
+
+
+def test_unpaired_result_ignored():
+ events = [_result("orphan", {"citations": ["pkg/a.py"]})]
+ assert mine_events_demand(events, REPO_PREFIX) == {}
+
+
+def test_non_repowise_tool_ignored():
+ events = [
+ Event(kind="assistant", cwd=CWD, tool_uses=[ToolUse(id="g1", name="Grep", input={})]),
+ _result("g1", {"citations": ["pkg/a.py"]}),
+ ]
+ assert mine_events_demand(events, REPO_PREFIX) == {}
+
+
+# ---------------------------------------------------------------------------
+# module rollup (the attribution the planner budgets on)
+# ---------------------------------------------------------------------------
+
+
+def test_rollup_to_modules_with_dict_map():
+ file_demand = {"pkg/a/x.py": 3, "pkg/a/y.py": 2, "pkg/b/z.py": 5}
+ mapping = {"pkg/a/x.py": "pkg/a", "pkg/a/y.py": "pkg/a", "pkg/b/z.py": "pkg/b"}
+ assert rollup_to_modules(file_demand, mapping) == {"pkg/a": 5, "pkg/b": 5}
+
+
+def test_rollup_to_modules_with_callable():
+ file_demand = {"pkg/a/x.py": 3, "pkg/b/z.py": 5}
+
+ def module_of(path: str) -> str:
+ return path.rsplit("/", 1)[0]
+
+ assert rollup_to_modules(file_demand, module_of) == {"pkg/a": 3, "pkg/b": 5}
+
+
+def test_rollup_drops_unmapped_files():
+ file_demand = {"pkg/a/x.py": 3, "gone/old.py": 9}
+ mapping = {"pkg/a/x.py": "pkg/a"} # gone/old.py -> None
+ assert rollup_to_modules(file_demand, mapping) == {"pkg/a": 3}
+
+
+def test_rollup_empty_in_empty_out():
+ assert rollup_to_modules({}, {}) == {}
+
+
+def test_single_module_skew_rolls_up_cleanly():
+ # All demand concentrated in one module: the exact shape the gate found.
+ file_demand = {f"hot/f{i}.py": 10 for i in range(4)}
+ file_demand["cold/f.py"] = 1
+ mapping = {p: p.split("/")[0] for p in file_demand}
+ modules = rollup_to_modules(file_demand, mapping)
+ assert modules == {"hot": 40, "cold": 1}
+
+
+# ---------------------------------------------------------------------------
+# config gate + aggregate entry point
+# ---------------------------------------------------------------------------
+
+
+def test_faq_weighting_enabled_default_on():
+ assert faq_weighting_enabled(None) is True
+ assert faq_weighting_enabled({}) is True
+ assert faq_weighting_enabled({"generation": {"faq_weighting": True}}) is True
+
+
+def test_faq_weighting_kill_switch():
+ assert faq_weighting_enabled({"generation": {"faq_weighting": False}}) is False
+
+
+def test_aggregate_disabled_returns_empty(tmp_path):
+ # Kill switch short-circuits before any transcript I/O.
+ out = aggregate_file_demand(tmp_path, repo_config={"generation": {"faq_weighting": False}})
+ assert out == {}
+
+
+def test_aggregate_no_transcripts_returns_empty(tmp_path):
+ # No transcript dir for this repo -> empty, no error (fresh install).
+ out = aggregate_file_demand(tmp_path, projects_root=tmp_path / "nope")
+ assert out == {}
+
+
+# ---------------------------------------------------------------------------
+# summary line (the CLI first-impression surface)
+# ---------------------------------------------------------------------------
+
+
+def test_summary_line_none_when_no_demand():
+ assert demand_summary_line({}) is None
+
+
+def test_summary_line_reports_exact_counts():
+ line = demand_summary_line({"a.py": 3, "b.py": 2})
+ assert "5 questions" in line
+ assert "2 files" in line
+
+
+def test_summary_line_singular_grammar():
+ line = demand_summary_line({"a.py": 1})
+ assert "1 question " in line
+ assert "1 file " in line