Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(ingestion+mcp): relative-import binding bug + audit-driven UX/MCP fixes (#149)
Raghav Chamadiyaaa08ed78ecb8
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd.py b/packages/cli/src/repowise/cli/commands/init_cmd.pyindex 635eecf99..71f29d8ee 100644--- a/packages/cli/src/repowise/cli/commands/init_cmd.py+++ b/packages/cli/src/repowise/cli/commands/init_cmd.py@@ -461,7 +461,13 @@ def _workspace_init(try:import structlog- structlog.configure(wrapper_class=structlog.make_filtering_bound_logger(logging.ERROR))+ # cache_logger_on_first_use=False: see init_command for rationale —+ # otherwise module-level ``structlog.get_logger`` calls hold a logger+ # snapshotted before configure() and bypass this filter.+ structlog.configure(+ wrapper_class=structlog.make_filtering_bound_logger(logging.ERROR),+ cache_logger_on_first_use=False,+ )except ImportError:pass@@ -943,8 +949,14 @@ def init_command(try:import structlog+ # Without cache_logger_on_first_use=False, modules that called+ # ``structlog.get_logger(__name__)`` at import time hold a bound logger+ # snapshotted before this configure ran — so debug lines from+ # ``core/ingestion/*`` (graph, traverser, parser, …) would leak past+ # the ERROR filter on the first ``init`` of a session.structlog.configure(wrapper_class=structlog.make_filtering_bound_logger(logging.ERROR),+ cache_logger_on_first_use=False,)except ImportError:passdiff --git a/packages/cli/src/repowise/cli/commands/update_cmd.py b/packages/cli/src/repowise/cli/commands/update_cmd.pyindex a38ffec51..2b1e6d60c 100644--- a/packages/cli/src/repowise/cli/commands/update_cmd.py+++ b/packages/cli/src/repowise/cli/commands/update_cmd.py@@ -144,6 +144,16 @@ def _workspace_update(default=None,help="Update only this repo alias within the workspace.",)+ "--index-only",+ is_flag=True,+ default=False,+ help=(+ "Skip LLM page regeneration. Re-parses files, rebuilds the dependency "+ "graph, and refreshes git/dead-code artifacts only. Useful for tight "+ "iteration on extractors / resolvers without spending tokens."+ ),+)def update_command(path: str | None,provider_name: str | None,@@ -153,6 +163,7 @@ def update_command(dry_run: bool,workspace: bool,repo_alias: str | None,+ index_only: bool = False,concurrency: int = 5,) -> None:"""Incrementally update wiki pages for files changed since last sync."""@@ -285,6 +296,68 @@ def update_command(console.print("[yellow]Dry run — no pages regenerated.[/yellow]")return+ if index_only:+ # Refresh graph, git metadata, and dead-code artifacts without+ # paying for LLM regeneration. Persist what we already computed+ # above and skip provider/decision/page-generation work.+ async def _persist_index_only() -> None:+ from repowise.cli.helpers import get_db_url_for_repo+ from repowise.core.persistence import (+ create_engine,+ create_session_factory,+ get_session,+ init_db,+ upsert_repository,+ )++ url = get_db_url_for_repo(repo_path)+ engine = create_engine(url)+ await init_db(engine)+ sf = create_session_factory(engine)++ async with get_session(sf) as session:+ repo = await upsert_repository(+ session, name=repo_path.name, local_path=str(repo_path)+ )+ repo_id = repo.id++ if git_meta_map:+ try:+ from repowise.core.persistence.crud import (+ recompute_git_percentiles,+ upsert_git_metadata_bulk,+ )++ await upsert_git_metadata_bulk(+ session, repo_id, list(git_meta_map.values())+ )+ await recompute_git_percentiles(session, repo_id)+ except Exception as exc:+ console.print(f"[yellow]Git persist skipped: {exc}[/yellow]")++ if dead_code_report is not None:+ try:+ from repowise.core.persistence.crud import (+ save_dead_code_findings,+ )++ await save_dead_code_findings(+ session, repo_id, dead_code_report.findings+ )+ except Exception as exc:+ console.print(+ f"[yellow]Dead-code persist skipped: {exc}[/yellow]"+ )++ run_async(_persist_index_only())+ save_state(repo_path, {**state, "last_sync_commit": head})+ elapsed = time.monotonic() - start+ console.print(+ f"[green]Index-only update complete[/green] in {elapsed:.1f}s — "+ "graph + git + dead-code refreshed; LLM pages unchanged."+ )+ return+provider = resolve_provider(provider_name, model, repo_path=repo_path)# Attach a DB-backed CostTracker so every LLM call made during this updatediff --git a/packages/cli/src/repowise/cli/ui.py b/packages/cli/src/repowise/cli/ui.pyindex cba517860..2d42ac918 100644--- a/packages/cli/src/repowise/cli/ui.py+++ b/packages/cli/src/repowise/cli/ui.py@@ -219,7 +219,23 @@ def print_scan_summary(console: Console, scan: RepoScanInfo) -> None:lang_parts.append(f"+{len(source_langs) - 4} more")lang_line = ", ".join(lang_parts) if lang_parts else "no source files detected"- body = f" {header_line}\n [dim]{lang_line}[/dim]"+ # Rough wall-time estimate so users know what they're committing to.+ # Calibrated against ~700-file Python+TS repos: traverse+parse+graph+ # comes in around 2 min/1k source files, plus ~1 min/100 LLM pages.+ # We surface a range, not a point, to set honest expectations.+ src_files = sum(source_langs.values()) or scan.total_files+ ingest_min = max(1, round(src_files / 500))+ ingest_max = max(2, round(src_files / 250))+ eta_line = (+ f"~{ingest_min}-{ingest_max} min ingestion"+ " · LLM generation depends on model + page count"+ )++ body = (+ f" {header_line}\n"+ f" [dim]{lang_line}[/dim]\n"+ f" [dim]{eta_line}[/dim]"+ )console.print(Panel(@@ -490,14 +506,40 @@ def interactive_provider_select(# --- model ---default_model = _PROVIDER_DEFAULTS.get(chosen, "")+ if not model_flag:+ console.print(+ " [dim]↳ Smaller is fine — repowise is calibrated for "+ "flash-lite / nano / haiku / 8B-class ollama. Bigger models "+ "don't improve doc quality.[/]"+ )model = model_flag or click.prompt(" Model",default=default_model,)+ if not model_flag and _is_flagship_model(model):+ console.print(+ f" [{WARN}]Note:[/] [dim]'{model}' works, but flash-lite / haiku / "+ "nano produce equivalent docs at ~10x lower cost on most repos.[/]"+ )+return chosen, model+_FLAGSHIP_MODEL_TOKENS = (+ "opus", "gpt-4o", "gpt-5", "-pro", "sonnet-4-7", "sonnet-4-6",+ "ultra", "o1", "o3",+)+++def _is_flagship_model(model: str) -> bool:+ """Heuristic: True if the model name suggests a flagship-tier model."""+ if not model:+ return False+ m = model.lower()+ return any(tok in m for tok in _FLAGSHIP_MODEL_TOKENS)++def _prompt_api_key(console: Console,provider: str,@@ -610,15 +652,18 @@ def interactive_advanced_config(console.print(" [dim]Gitignore-style patterns, comma-separated or one per line.[/dim]")console.print(" [dim]Press Enter with empty input to finish.[/dim]")patterns: list[str] = []+ seen_patterns: set[str] = set()while True:raw = click.prompt(" Pattern", default="", show_default=False)raw = raw.strip()if not raw:break- # Support comma-separated input+ # Support comma-separated input; dedupe so re-pasting / re-entering+ # the same suggestions doesn't bloat the summary panel.for part in raw.split(","):part = part.strip()- if part:+ if part and part not in seen_patterns:+ seen_patterns.add(part)patterns.append(part)result["exclude"] = tuple(patterns)@@ -681,7 +726,7 @@ def interactive_advanced_config()result["test_run"] = click.confirm(- " Test run? (limit to top 10 files for quick validation)",+ " Test run? (full ingestion; LLM page generation limited to top 10 files for quick validation)",default=False,)@@ -699,7 +744,11 @@ def interactive_advanced_config(summary.add_row("Concurrency", str(result["concurrency"]))summary.add_row("Embedder", result["embedder"])if patterns:- summary.add_row("Exclude", ", ".join(patterns))+ if len(patterns) <= 5:+ summary.add_row("Exclude", ", ".join(patterns))+ else:+ # Bullet-list when many patterns — comma-joined wraps unreadably.+ summary.add_row("Exclude", "\n".join(f"• {p}" for p in patterns))summary.add_row("Test run", "yes" if result["test_run"] else "no")console.print(@@ -1114,6 +1163,25 @@ class RichProgressCallback:if phase in self._tasks:self._progress.advance(self._tasks[phase])+ def on_phase_done(self, phase: str) -> None:+ """Mark a phase task as fully complete and hide it from the live+ display, so the phase-summary lines that follow aren't interleaved+ with stale progress bars (issue: phantom/duplicated progress bars).+ """+ task_id = self._tasks.get(phase)+ if task_id is None:+ return+ try:+ task = next(+ (t for t in self._progress.tasks if t.id == task_id), None+ )+ if task is not None and task.total is not None:+ self._progress.update(task_id, completed=task.total, visible=False)+ else:+ self._progress.update(task_id, visible=False)+ except Exception:+ pass+def on_message(self, level: str, text: str) -> None:style_map = {"info": OK, "warning": WARN, "error": ERR}style = style_map.get(level, "")diff --git a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py b/packages/core/src/repowise/core/analysis/dead_code/analyzer.pyindex 86af0bf69..908d06bae 100644--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py@@ -291,6 +291,15 @@ class DeadCodeAnalyzer:continuesym_name = sym.get("name", "")+ # Methods are not independently importable — they're attribute+ # access on an instance — so flagging them as unused-exports+ # produces guaranteed false positives. Same for dunders, which+ # are invoked by the language runtime, not by name lookup.+ if sym.get("kind") == "method":+ continue+ if sym_name.startswith("__") and sym_name.endswith("__"):+ continue+decorators = sym.get("decorators", [])if any(d.startswith(prefix) for d in decorators for prefix in _FRAMEWORK_DECORATORSdiff --git a/packages/core/src/repowise/core/analysis/dead_code/constants.py b/packages/core/src/repowise/core/analysis/dead_code/constants.pyindex 6a0e91c24..59895fbfc 100644--- a/packages/core/src/repowise/core/analysis/dead_code/constants.py+++ b/packages/core/src/repowise/core/analysis/dead_code/constants.py@@ -73,11 +73,38 @@ _FRAMEWORK_DECORATORS: tuple[str, ...] = ("router.put","router.delete","router.patch",+ "router.head",+ "router.options",+ "router.websocket","app.get","app.post",+ "app.put",+ "app.delete",+ "app.patch",+ "app.head",+ "app.options",+ "app.websocket",+ "app.middleware",+ "app.exception_handler",+ # asynccontextmanager / contextmanager — used as values+ # (e.g. FastAPI(lifespan=...)) rather than imported by name.+ "asynccontextmanager",+ "contextmanager",+ "contextlib.asynccontextmanager",+ "contextlib.contextmanager",# Django"admin.register","receiver",+ # Celery / RQ task registration+ "app.task",+ "celery.task",+ "shared_task",+ # Click CLI commands — registered with the parent group/command.+ "click.command",+ "click.group",+ # Typer — same shape.+ "typer.command",+ "typer.callback",)# Default dynamic patterns (plugins, handlers, etc.)diff --git a/packages/core/src/repowise/core/generation/page_generator.py b/packages/core/src/repowise/core/generation/page_generator.pyindex 5509ddf40..ce8c29197 100644--- a/packages/core/src/repowise/core/generation/page_generator.py+++ b/packages/core/src/repowise/core/generation/page_generator.py@@ -297,6 +297,7 @@ class PageGenerator:community: dict[str, int],git_meta_map: dict[str, dict] | None = None,graph_builder: Any | None = None,+ repo_name: str | None = None,) -> GeneratedPage:ctx = self._assembler.assemble_repo_overview(repo_structure,@@ -323,7 +324,8 @@ class PageGenerator:}user_prompt = self._render("repo_overview.j2", ctx=ctx, repo_git_summary=repo_git_summary)response = await self._call_provider("repo_overview", user_prompt, str(uuid.uuid4()))- repo_name = getattr(repo_structure, "name", "repo")+ if not repo_name:+ repo_name = getattr(repo_structure, "name", None) or "repo"return self._build_generated_page("repo_overview",repo_name,@@ -858,6 +860,7 @@ class PageGenerator:community,git_meta_map=git_meta_map,graph_builder=graph_builder,+ repo_name=repo_name,),))diff --git a/packages/core/src/repowise/core/ingestion/extractors/bindings/python.py b/packages/core/src/repowise/core/ingestion/extractors/bindings/python.pyindex 2b444739f..b08740b32 100644--- a/packages/core/src/repowise/core/ingestion/extractors/bindings/python.py+++ b/packages/core/src/repowise/core/ingestion/extractors/bindings/python.py@@ -13,12 +13,22 @@ def extract_python_bindings(stmt_node: Node, src: str) -> tuple[list[str], list[names: list[str] = []bindings: list[NamedBinding] = []is_from_import = stmt_node.type == "import_from_statement"+ # For absolute `from foo.bar import X`, tree-sitter places the module+ # `foo.bar` as the first top-level `dotted_name` child — we must skip it.+ # For relative `from .bar import X`, the module is wrapped in a+ # `relative_import` node, so every top-level `dotted_name` is an+ # imported name and nothing should be skipped.+ has_relative_module = any(c.type == "relative_import" for c in stmt_node.children)+ skip_first_dotted = is_from_import and not has_relative_modulefirst_dotted_seen = Falsefor child in stmt_node.children:if child.type == "wildcard_import":return ["*"], [NamedBinding(local_name="*", exported_name=None, source_file=None)]+ if child.type == "relative_import":+ continue+if child.type == "aliased_import":name_node = child.child_by_field_name("name") or (child.children[0] if child.children else None@@ -48,7 +58,7 @@ def extract_python_bindings(stmt_node: Node, src: str) -> tuple[list[str], list[elif child.type == "dotted_name":text = node_text(child, src)bare = text.split(".")[-1]- if is_from_import and not first_dotted_seen:+ if skip_first_dotted and not first_dotted_seen:first_dotted_seen = Truecontinuenames.append(bare)diff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.pyindex 1c96208dc..b91c0dbd6 100644--- a/packages/core/src/repowise/core/ingestion/parser.py+++ b/packages/core/src/repowise/core/ingestion/parser.py@@ -554,7 +554,6 @@ class ASTParser:compiled = Query(language, scm_text)self._query_cache[lang] = compiled- log.debug("Compiled query", language=lang)return compiledexcept Exception as exc:log.warning("Failed to compile query", language=lang, error=str(exc))diff --git a/packages/core/src/repowise/core/pipeline/orchestrator.py b/packages/core/src/repowise/core/pipeline/orchestrator.pyindex 5313f9904..f2f5c83df 100644--- a/packages/core/src/repowise/core/pipeline/orchestrator.py+++ b/packages/core/src/repowise/core/pipeline/orchestrator.py@@ -29,6 +29,20 @@ from repowise.core.pipeline.progress import ProgressCallbacklogger = structlog.get_logger(__name__)+def _phase_done(progress: ProgressCallback | None, phase: str) -> None:+ """Best-effort call to ``progress.on_phase_done`` — older callbacks may+ not implement it, so fall back to a no-op silently.+ """+ if progress is None:+ return+ fn = getattr(progress, "on_phase_done", None)+ if callable(fn):+ try:+ fn(phase)+ except Exception:+ pass++# ---------------------------------------------------------------------------# Process-pool worker (module-level — must be picklable)# ---------------------------------------------------------------------------@@ -414,6 +428,7 @@ async def _run_ingestion(await asyncio.to_thread(io_pool.shutdown, wait=True)repo_structure = traverser.get_repo_structure(file_infos)+ _phase_done(progress, "traverse")# Filterif skip_tests:@@ -492,6 +507,8 @@ async def _run_ingestion(if _use_process_pool and progress:progress.on_item_done("parse")+ _phase_done(progress, "parse")+# ---- tsconfig path-alias resolver (before graph build) ------------------try:from repowise.core.ingestion.tsconfig_resolver import TsconfigResolver@@ -507,6 +524,11 @@ async def _run_ingestion(# ---- Graph build phase -------------------------------------------------if progress:progress.on_phase_start("graph", 1)+ progress.on_message(+ "info",+ " (graph build can take several minutes on first run — safe to "+ "Ctrl-C, then run 'repowise init --resume' to continue)",+ )await asyncio.to_thread(graph_builder.build)# Add framework-aware synthetic edges (conftest, Django, FastAPI, Flask)@@ -531,6 +553,7 @@ async def _run_ingestion(if progress:progress.on_item_done("graph")+ _phase_done(progress, "graph")# Emit filtering summary so users can see what was included/excludedstats = traverser.stats@@ -623,10 +646,14 @@ async def _run_git_indexing(on_commit_done=_on_commit_done,)git_meta_map = {m["file_path"]: m for m in git_metadata_list}+ _phase_done(progress, "git")+ _phase_done(progress, "co_change")return git_summary, git_metadata_list, git_meta_mapexcept Exception as exc:if progress:progress.on_message("warning", f"Git indexing skipped: {exc}")+ _phase_done(progress, "git")+ _phase_done(progress, "co_change")return None, [], {}@@ -657,10 +684,12 @@ async def _run_dead_code_analysis(f"{unused_exports} unused exports · ~{report.deletable_lines:,} deletable lines",)+ _phase_done(progress, "dead_code")return reportexcept Exception as exc:if progress:progress.on_message("warning", f"Dead code detection skipped: {exc}")+ _phase_done(progress, "dead_code")return None@@ -701,10 +730,12 @@ async def _run_decision_extraction(f"→ {total_decisions} decisions: {inline} inline · {readme} from docs · {git_arch} from git",)+ _phase_done(progress, "decisions")return reportexcept Exception as exc:if progress:progress.on_message("warning", f"Decision extraction skipped: {exc}")+ _phase_done(progress, "decisions")return None@@ -806,5 +837,6 @@ async def run_generation(if progress:progress.on_message("info", f"Generated {len(generated_pages)} pages")+ _phase_done(progress, "generation")return generated_pagesdiff --git a/packages/core/src/repowise/core/pipeline/progress.py b/packages/core/src/repowise/core/pipeline/progress.pyindex 57f5c03e8..7b3e70abd 100644--- a/packages/core/src/repowise/core/pipeline/progress.py+++ b/packages/core/src/repowise/core/pipeline/progress.py@@ -28,6 +28,14 @@ class ProgressCallback(Protocol):"""Called after one unit of work completes within a phase."""...+ def on_phase_done(self, phase: str) -> None:+ """Called when a pipeline phase finishes — implementations should+ hide the still-rendering progress task so phase-summary lines that+ follow aren't interleaved with stale spinners. Optional; default+ implementations should be a no-op so existing callers keep working.+ """+ ...+def on_message(self, level: str, text: str) -> None:"""Emit a free-form message. *level* is 'info', 'warning', or 'error'."""...@@ -42,5 +50,8 @@ class LoggingProgressCallback:def on_item_done(self, phase: str) -> None:logger.debug("item_done", phase=phase)+ def on_phase_done(self, phase: str) -> None:+ logger.info("phase_done", phase=phase)+def on_message(self, level: str, text: str) -> None:getattr(logger, level, logger.info)(text)diff --git a/packages/server/src/repowise/server/mcp_server/tool_dead_code.py b/packages/server/src/repowise/server/mcp_server/tool_dead_code.pyindex 19474c782..b82c8eeba 100644--- a/packages/server/src/repowise/server/mcp_server/tool_dead_code.py+++ b/packages/server/src/repowise/server/mcp_server/tool_dead_code.py@@ -70,7 +70,9 @@ async def get_dead_code(min_confidence: Minimum confidence threshold (default 0.5). Use 0.7 for high-confidencecleanups only.safe_only: Only return findings marked safe_to_delete (default false).- limit: Maximum findings per tier (default 20).+ limit: Maximum findings per tier (default 20). Clamped to 25 because larger+ payloads exceed MCP transport token caps; paginate by tier/directory/owner+ for deeper exploration.tier: Focus on a single tier: "high" (>=0.8), "medium" (0.5-0.8), or "low" (<0.5).directory: Filter findings to a specific directory prefix.owner: Filter findings by primary owner name.@@ -82,6 +84,14 @@ async def get_dead_code(no_unreachable: Suppress unreachable-file findings (default false).no_unused_exports: Suppress unused-export findings (default false)."""+ # MCP transport rejects payloads above ~25k tokens. A single serialized+ # finding is ~400 chars, so 3 tiers x ~25 findings keeps us under budget+ # with headroom for summary/grouping fields.+ _MAX_PER_TIER = 25+ requested_limit = limit+ limit = min(max(limit, 1), _MAX_PER_TIER)+ limit_clamped = requested_limit > _MAX_PER_TIER+# --- repo="all": aggregate dead code across all repos ---if repo == "all":contexts = await _resolve_all_contexts()@@ -202,12 +212,19 @@ async def get_dead_code(# Cross-repo confidence adjustment for workspace-wide findings_adjust_dead_code_cross_repo(tiers, None)- return {+ result_ws: dict[str, Any] = {"workspace": True,"summary": summary,"tiers": tiers,"impact": _compute_impact(tiers),}+ if limit_clamped:+ result_ws["limit_note"] = (+ f"Requested limit={requested_limit} exceeded the MCP transport budget "+ f"and was clamped to {_MAX_PER_TIER}. Use tier/directory/owner filters "+ "or paginate to see more findings."+ )+ return result_ws# --- Single repo path ---ctx = await _resolve_repo_context(repo)@@ -294,6 +311,13 @@ async def get_dead_code(# --- Impact estimate ---result["impact"] = _compute_impact(tiers)+ if limit_clamped:+ result["limit_note"] = (+ f"Requested limit={requested_limit} exceeded the MCP transport budget "+ f"and was clamped to {_MAX_PER_TIER}. Use tier/directory/owner filters "+ "or paginate to see more findings."+ )+return resultdiff --git a/packages/server/src/repowise/server/mcp_server/tool_overview.py b/packages/server/src/repowise/server/mcp_server/tool_overview.pyindex 91c7cd4a1..9af827c3d 100644--- a/packages/server/src/repowise/server/mcp_server/tool_overview.py+++ b/packages/server/src/repowise/server/mcp_server/tool_overview.py@@ -372,8 +372,18 @@ async def get_overview(repo: str | None = None) -> dict:"cohesion": round(cohesion, 3),})+ # Older indexes persisted titles like "Repository Overview: repo" because+ # repo_name was not passed through to generate_repo_overview. Substitute+ # the actual repo name back in so the response is useful without reindex.+ if overview_page:+ persisted_title = overview_page.title or ""+ title = persisted_title.replace(+ "Repository Overview: repo", f"Repository Overview: {repository.name}"+ )+ else:+ title = repository.nameresult = {- "title": overview_page.title if overview_page else repository.name,+ "title": title,"content_md": overview_page.content if overview_page else "No overview generated yet.","key_modules": [{diff --git a/tests/unit/ingestion/test_parser.py b/tests/unit/ingestion/test_parser.pyindex 5694dba05..6457337de 100644--- a/tests/unit/ingestion/test_parser.py+++ b/tests/unit/ingestion/test_parser.py@@ -140,6 +140,36 @@ class TestPythonParser:op_import = next(i for i in result.imports if i.module_path == "python_pkg.models")assert "Operation" in op_import.imported_names+ def test_relative_from_import_single_name(self, parser: ASTParser) -> None:+ # Regression: `from .X import Y` was dropping the only imported name.+ fi = _make_file_info("pkg/__init__.py", "python")+ result = parser.parse_file(fi, b"from .graph import GraphBuilder\n")+ rel_import = next(i for i in result.imports if "graph" in i.module_path)+ assert rel_import.imported_names == ["GraphBuilder"]++ def test_relative_from_import_multiple_names_keeps_first(+ self, parser: ASTParser+ ) -> None:+ # Regression: `from .X import A, B, C` was dropping `A`.+ fi = _make_file_info("pkg/__init__.py", "python")+ result = parser.parse_file(+ fi, b"from .change_detector import AffectedPages, ChangeDetector, FileDiff\n"+ )+ rel_import = next(i for i in result.imports if "change_detector" in i.module_path)+ assert rel_import.imported_names == ["AffectedPages", "ChangeDetector", "FileDiff"]++ def test_absolute_from_import_skips_module_keeps_first_name(+ self, parser: ASTParser+ ) -> None:+ # Guard against over-correction: absolute imports must still drop the+ # module path while keeping every imported name including the first.+ fi = _make_file_info("pkg/use.py", "python")+ result = parser.parse_file(+ fi, b"from python_pkg.models import Operation, Result\n"+ )+ imp = next(i for i in result.imports if i.module_path == "python_pkg.models")+ assert imp.imported_names == ["Operation", "Result"]+def test_function_docstring(self, parser: ASTParser) -> None:fi = _make_file_info("pkg/calc.py", "python")result = parser.parse_file(fi, PYTHON_SOURCE)