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: phase timing in state.json, COM contract method FP cap, ASP.NET host extensions (#182)

Raghav Chamadiya7898f733ea70
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd.py b/packages/cli/src/repowise/cli/commands/init_cmd.py
index 9929a4d5a..1b89ae093 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd.py
@@ -554,7 +554,7 @@ def _workspace_init(
load_dotenv,
print_banner,
)
- from repowise.core.pipeline import run_pipeline
+ from repowise.core.pipeline import PhaseTimingRecorder, run_pipeline
from repowise.core.workspace import RepoEntry, WorkspaceConfig
start = time.monotonic()
@@ -677,7 +677,7 @@ def _workspace_init(
TimeElapsedColumn(),
console=console,
) as progress_bar:
- callback = RichProgressCallback(progress_bar, console)
+ callback = PhaseTimingRecorder(RichProgressCallback(progress_bar, console))
result = run_async(
run_pipeline(
@@ -690,6 +690,7 @@ def _workspace_init(
progress=callback,
)
)
+ repo_phase_timings: dict[str, float] = callback.timings
total_files += result.file_count
total_symbols += result.symbol_count
@@ -767,6 +768,8 @@ def _workspace_init(
if repo_docs_enabled and provider is not None:
state["provider"] = provider.provider_name
state["model"] = provider.model_name
+ if repo_phase_timings:
+ state["phase_timings"] = repo_phase_timings
save_state(repo.path, state)
# Update workspace config with indexing metadata
@@ -1234,7 +1237,7 @@ def init_command(
cost_declined = False
llm_client = provider if not index_only else decision_provider
- from repowise.core.pipeline import run_pipeline
+ from repowise.core.pipeline import PhaseTimingRecorder, run_pipeline
with Progress(
SpinnerColumn(),
@@ -1245,7 +1248,11 @@ def init_command(
TextColumn("[green]${task.fields[cost]:.3f}[/green]"),
console=console,
) as progress_bar:
- callback = RichProgressCallback(progress_bar, console)
+ rich_callback = RichProgressCallback(progress_bar, console)
+ # Wrap the Rich callback so we can record per-phase wall-clock
+ # durations without changing the pipeline API. Timings get
+ # persisted to state.json below.
+ callback = PhaseTimingRecorder(rich_callback)
# Always run ingestion + analysis first (generate_docs=False).
# Generation happens separately after cost confirmation.
@@ -1266,6 +1273,11 @@ def init_command(
)
)
+ # Surface per-phase timing data to the caller — both for the
+ # state.json persistence below and for any future "profile" tooling
+ # that wants to introspect a run.
+ phase_timings: dict[str, float] = callback.timings
+
# ---- Analysis summary (shown between analysis and generation) ----
_graph = result.graph_builder.graph()
_dc_unreachable_pre = sum(
@@ -1543,6 +1555,8 @@ def init_command(
base_state = load_state(repo_path)
base_state["last_sync_commit"] = head
base_state["docs_enabled"] = not effective_index_only and provider is not None
+ if phase_timings:
+ base_state["phase_timings"] = phase_timings
if effective_index_only or provider is None:
save_state(repo_path, base_state)
@@ -1586,6 +1600,8 @@ def init_command(
state["docs_enabled"] = True
total_tokens = sum(p.total_tokens for p in (result.generated_pages or []))
state["total_tokens"] = total_tokens
+ if phase_timings:
+ state["phase_timings"] = phase_timings
save_state(repo_path, state)
save_config(
diff --git a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
index cbb81078d..66fe29104 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
@@ -26,6 +26,7 @@ from .constants import (
_NON_CODE_LANGUAGES,
_is_fixture_path,
)
+from .contract_methods import is_contract_method
# Symbol kinds that cannot be independently imported by name in any
# supported language. Flagging them as "unused exports" is a guaranteed
@@ -479,6 +480,17 @@ class DeadCodeAnalyzer:
if sym.get("kind") == "interface" and not self._file_has_implementors(node):
confidence = min(confidence, 0.4)
+ # COM / IUnknown / IDispatch contract methods
+ # (``QueryInterface``, ``AddRef``, ``Release``, …) are
+ # dispatched through native vtables — no static caller
+ # edge will ever land in the graph. Clamp below the
+ # safe-to-delete threshold so we never ship them as
+ # confident dead code on Windows / COM-heavy C++ repos.
+ if is_contract_method(
+ sym_name, sym.get("kind"), sym.get("language", "unknown")
+ ):
+ confidence = min(confidence, 0.4)
+
safe = confidence >= 0.7
git_meta = self.git_meta_map.get(str(node), {})
@@ -545,6 +557,10 @@ class DeadCodeAnalyzer:
continue
if node_data.get("kind") in _non_importable_kinds(node_data.get("language", "unknown")):
continue
+ if is_contract_method(
+ sym_name, node_data.get("kind"), node_data.get("language", "unknown")
+ ):
+ continue
if self._name_matches_dynamic(sym_name, dynamic_patterns):
continue
diff --git a/packages/core/src/repowise/core/analysis/dead_code/contract_methods.py b/packages/core/src/repowise/core/analysis/dead_code/contract_methods.py
new file mode 100644
index 000000000..5955dc852
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/dead_code/contract_methods.py
@@ -0,0 +1,76 @@
+"""Well-known contract method names whose absence-of-callers is not evidence of death.
+
+Some method names are reserved by language runtimes, ABI conventions,
+or COM-style interface contracts. They are dispatched through vtables /
+reflection / native interop — never through a static call edge the
+graph can observe.
+
+The dead-code analyzer treats a symbol matching one of these as if it
+implements a contract: confidence is clamped below the safe-to-delete
+threshold (≤ 0.4) so the report doesn't ship them as confident dead
+code. The clamp is conservative on purpose — these are heuristic name
+matches, not language-aware semantic checks.
+
+Currently covers:
+
+* **COM / IUnknown / IDispatch** — every COM object must expose
+ ``QueryInterface``, ``AddRef``, ``Release`` (and dispatch types add
+ ``GetIDsOfNames``, ``Invoke``, etc.). They never appear as static
+ callers in C# / C++ COM-interop code because the runtime resolves
+ the vtable slot.
+
+Extend this list (and the matching helper) when other reserved-name
+patterns surface — e.g. WinRT activation factories, .NET ``ToString``
+overrides without static callers, etc.
+"""
+
+from __future__ import annotations
+
+
+# Method names reserved by COM / IUnknown / IDispatch. Case-sensitive —
+# Windows COM uses PascalCase universally.
+_COM_CONTRACT_METHOD_NAMES: frozenset[str] = frozenset({
+ # IUnknown
+ "QueryInterface",
+ "AddRef",
+ "Release",
+ # IDispatch
+ "GetTypeInfoCount",
+ "GetTypeInfo",
+ "GetIDsOfNames",
+ "Invoke",
+ # IClassFactory
+ "CreateInstance",
+ "LockServer",
+ # IMarshal (rarely user-implemented but same rationale)
+ "GetUnmarshalClass",
+ "GetMarshalSizeMax",
+ "MarshalInterface",
+ "UnmarshalInterface",
+ "ReleaseMarshalData",
+ "DisconnectObject",
+})
+
+
+# Languages where COM contract names are load-bearing. C++ / C# are the
+# overwhelming majority; Rust ``windows-rs`` derivations also surface
+# these names in user code via the ``#[implement]`` macro.
+_COM_LANGUAGES: frozenset[str] = frozenset({"cpp", "c", "csharp", "rust"})
+
+
+def is_contract_method(sym_name: str, sym_kind: str | None, language: str | None) -> bool:
+ """Return True if *sym_name* is a reserved contract-method name in *language*.
+
+ The check is intentionally narrow: only kind=``method`` symbols in
+ a language where the name is load-bearing match. A user-defined
+ free function named ``Release`` in TypeScript is left alone.
+ """
+ # C++ tree-sitter sometimes emits method definitions outside the
+ # class body (e.g. ``STDMETHODIMP CFoo::QueryInterface(...)``) as
+ # kind=function rather than method. Accept both — the name + COM
+ # language combination is restrictive enough on its own.
+ if sym_kind not in ("method", "function"):
+ return False
+ if language not in _COM_LANGUAGES:
+ return False
+ return sym_name in _COM_CONTRACT_METHOD_NAMES
diff --git a/packages/core/src/repowise/core/ingestion/aspnet_extensions.py b/packages/core/src/repowise/core/ingestion/aspnet_extensions.py
new file mode 100644
index 000000000..848cd8675
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/aspnet_extensions.py
@@ -0,0 +1,165 @@
+"""ASP.NET host-builder extension-method resolution.
+
+ASP.NET Core minimal-API and DI registration code lives in static
+classes exposing extension methods that take ``this
+IEndpointRouteBuilder`` / ``this IServiceCollection`` /
+``this IApplicationBuilder`` (and similar) as their first parameter.
+The call site looks like ``app.MapCatalogApi();`` or
+``services.AddCatalogServices()`` and binds to a definition like:
+
+.. code-block:: csharp
+
+ public static IEndpointRouteBuilder MapCatalogApi(
+ this IEndpointRouteBuilder app)
+ { ... }
+
+The static graph never connects ``Program.cs`` (the caller) to the
+file that defines the extension method, so the defining file shows up
+as an orphan and the surrounding endpoint module reads as dead code.
+
+This module closes the gap with a two-pass scan that lives next to
+:mod:`framework_edges` but is kept separate for clarity and unit
+testability:
+
+1. **Definition pass** — find every ``public static T MapXxx(this
+ <host> ...)`` or ``AddXxx(this <host> ...)`` signature and index
+ it by method name.
+2. **Call-site pass** — find every ``.MapXxx(`` / ``.AddXxx(`` call
+ in the same set of C# files and emit a framework edge from the
+ caller file to the defining file.
+
+The host-type allowlist is conservative (well-known ASP.NET builder
+types) to avoid binding e.g. ``list.Map(...)`` LINQ to an unrelated
+extension method.
+"""
+
+from __future__ import annotations
+
+import re
+from pathlib import Path
+from typing import TYPE_CHECKING, Any
+
+if TYPE_CHECKING:
+ import networkx as nx
+
+
+# Host types whose extension methods we want to link. Restricting the
+# allowlist avoids false positives from generic ``T``-parameterised
+# helpers and from LINQ-style ``Map`` on collections.
+_ASPNET_HOST_TYPES: tuple[str, ...] = (
+ "IEndpointRouteBuilder",
+ "IApplicationBuilder",
+ "IServiceCollection",
+ "WebApplication",
+ "WebApplicationBuilder",
+ "IHostBuilder",
+ "IHostApplicationBuilder",
+ "IMvcBuilder",
+ "IRouteBuilder",
+)
+
+
+# ``public static <return-type> <name>(this <host-type> ...``
+# - return-type is permissive (any token sequence up to the name) so we
+# handle ``IEndpointRouteBuilder``, ``RouteHandlerBuilder``, ``void``,
+# ``IServiceCollection`` etc.
+# - method name must start with ``Map`` or ``Add`` (the only two
+# prefixes ASP.NET conventionally uses for host extensions).
+_EXTENSION_DEF_RE = re.compile(
+ r"\bpublic\s+static\s+[\w<>,\s\.\?\[\]]+?\s+"
+ r"(?P<name>(?:Map|Add|Use)[A-Z]\w*)\s*"
+ r"(?:<[^>]+>\s*)?" # optional generic param list
+ r"\(\s*this\s+"
+ r"(?P<host>[\w\.]+)"
+ r"\b"
+)
+
+
+_EXTENSION_CALL_RE = re.compile(r"\.\s*(?P<name>(?:Map|Add|Use)[A-Z]\w*)\s*\(")
+
+
+def build_extension_index(cs_texts: dict[str, str]) -> dict[str, str]:
+ """Map ``Map*`` / ``Add*`` / ``Use*`` extension-method name → defining file.
+
+ *cs_texts* maps repo-relative C# file path to its source text.
+ Last-write-wins on duplicate method names — duplicates are rare in
+ well-formed solutions and last-wins is no worse than any other
+ arbitrary tie-break for graph attachment.
+ """
+ index: dict[str, str] = {}
+ host_allow = set(_ASPNET_HOST_TYPES)
+ for path, text in cs_texts.items():
+ for m in _EXTENSION_DEF_RE.finditer(text):
+ host = m.group("host")
+ # Tolerate ``Microsoft.Extensions.DependencyInjection.IServiceCollection``
+ host_short = host.rsplit(".", 1)[-1]
+ if host_short not in host_allow:
+ continue
+ index[m.group("name")] = path
+ return index
+
+
+def add_extension_method_edges(
+ graph: nx.DiGraph,
+ cs_texts: dict[str, str],
+ path_set: set[str],
+) -> int:
+ """Emit framework edges from caller files to extension-method definitions.
+
+ Returns the number of edges added. Edges are tagged
+ ``edge_type="framework"`` so they feed dead-code's existing
+ "incoming framework edge ⇒ live" check.
+ """
+ if not cs_texts:
+ return 0
+
+ index = build_extension_index(cs_texts)
+ if not index:
+ return 0
+
+ count = 0
+ for caller_path, text in cs_texts.items():
+ if caller_path not in path_set:
+ continue
+ seen_for_caller: set[str] = set()
+ for m in _EXTENSION_CALL_RE.finditer(text):
+ name = m.group("name")
+ target = index.get(name)
+ if target is None or target == caller_path:
+ continue
+ if target in seen_for_caller or target not in path_set:
+ continue
+ if _add_edge_if_new(graph, caller_path, target):
+ seen_for_caller.add(target)
+ count += 1
+ return count
+
+
+def _add_edge_if_new(graph: nx.DiGraph, source: str, target: str) -> bool:
+ """Add a framework edge if no edge already connects source → target."""
+ if source == target or graph.has_edge(source, target):
+ return False
+ graph.add_edge(source, target, edge_type="framework", imported_names=[])
+ return True
+
+
+def collect_csharp_texts(parsed_files: dict[str, Any], path_set: set[str]) -> dict[str, str]:
+ """Read each C# file's source text once, keyed by repo-relative path.
+
+ Returning a dict keeps the two passes (definition + call site)
+ cache-friendly: large solutions otherwise read every .cs file
+ twice from disk just for this analysis.
+ """
+ texts: dict[str, str] = {}
+ for path, parsed in parsed_files.items():
+ if parsed.file_info.language != "csharp":
+ continue
+ if path not in path_set:
+ continue
+ try:
+ texts[path] = Path(parsed.file_info.abs_path).read_text(
+ encoding="utf-8-sig", errors="ignore"
+ )
+ except OSError:
+ continue
+ return texts
diff --git a/packages/core/src/repowise/core/ingestion/framework_edges.py b/packages/core/src/repowise/core/ingestion/framework_edges.py
index dd9faeed9..b754cbbdf 100644
--- a/packages/core/src/repowise/core/ingestion/framework_edges.py
+++ b/packages/core/src/repowise/core/ingestion/framework_edges.py
@@ -374,6 +374,18 @@ def _add_aspnet_edges(
if target and target in path_set and _add_edge_if_new(graph, db_path, target):
count += 1
+ # ---- 6. Host-builder extension-method calls ----
+ # ``app.MapCatalogApi()`` / ``services.AddCatalogServices()`` bind to
+ # extension methods declared on ``IEndpointRouteBuilder`` /
+ # ``IServiceCollection`` / etc. Without this pass the defining file
+ # has no static importer and reads as orphaned. Lives in its own
+ # module so the regex set and host-type allowlist stay testable in
+ # isolation.
+ from .aspnet_extensions import add_extension_method_edges, collect_csharp_texts
+
+ cs_texts = collect_csharp_texts(parsed_files, path_set)
+ count += add_extension_method_edges(graph, cs_texts, path_set)
+
return count
diff --git a/packages/core/src/repowise/core/pipeline/__init__.py b/packages/core/src/repowise/core/pipeline/__init__.py
index 77258a054..ff2108814 100644
--- a/packages/core/src/repowise/core/pipeline/__init__.py
+++ b/packages/core/src/repowise/core/pipeline/__init__.py
@@ -12,10 +12,12 @@ Usage::
from .orchestrator import PipelineResult, run_generation, run_pipeline
from .persist import persist_pipeline_result
+from .phase_timing import PhaseTimingRecorder
from .progress import LoggingProgressCallback, ProgressCallback
__all__ = [
"LoggingProgressCallback",
+ "PhaseTimingRecorder",
"PipelineResult",
"ProgressCallback",
"persist_pipeline_result",
diff --git a/packages/core/src/repowise/core/pipeline/phase_timing.py b/packages/core/src/repowise/core/pipeline/phase_timing.py
new file mode 100644
index 000000000..d7d00c20b
--- /dev/null
+++ b/packages/core/src/repowise/core/pipeline/phase_timing.py
@@ -0,0 +1,85 @@
+"""Phase-timing recorder for the indexing pipeline.
+
+A ``ProgressCallback`` decorator that observes ``on_phase_start`` /
+``on_phase_done`` events and records the wall-clock duration of each
+phase. Designed to compose with the real (Rich / Logging) callback so
+the timing data is collected without touching pipeline internals.
+
+The CLI writes the resulting ``timings`` dict into ``state.json`` so
+before/after perf comparisons across runs become trivial:
+
+.. code-block:: text
+
+ state.json
+ {
+ "last_sync_commit": "...",
+ "phase_timings": {
+ "traverse": 4.21,
+ "parse": 88.3,
+ "graph.imports": 312.5,
+ ...
+ }
+ }
+"""
+
+from __future__ import annotations
+
+import time
+from typing import Any
+
+
+class PhaseTimingRecorder:
+ """Observes pipeline phase events and records wall-clock durations.
+
+ Wraps another ``ProgressCallback`` (or ``None``) and transparently
+ delegates every call. Concurrent / nested phases are supported —
+ each phase name is timed independently from its own
+ ``on_phase_start`` to its matching ``on_phase_done``.
+
+ Repeated phases (a phase whose ``on_phase_start`` fires more than
+ once in a single run) accumulate; the total is the sum of every
+ visit. This matches how the user perceives the cost — "how much
+ wall-clock time did this phase consume".
+ """
+
+ def __init__(self, inner: Any | None = None) -> None:
+ self._inner = inner
+ self._starts: dict[str, float] = {}
+ self._totals: dict[str, float] = {}
+
+ @property
+ def timings(self) -> dict[str, float]:
+ """Mapping of phase name → accumulated seconds (rounded to 0.01s)."""
+ return {name: round(secs, 2) for name, secs in self._totals.items()}
+
+ # ---- ProgressCallback protocol ----------------------------------
+
+ def on_phase_start(self, phase: str, total: int | None) -> None:
+ self._starts[phase] = time.monotonic()
+ if self._inner is not None:
+ self._inner.on_phase_start(phase, total)
+
+ def on_item_done(self, phase: str) -> None:
+ if self._inner is not None:
+ self._inner.on_item_done(phase)
+
+ def on_phase_done(self, phase: str) -> None:
+ started = self._starts.pop(phase, None)
+ if started is not None:
+ self._totals[phase] = self._totals.get(phase, 0.0) + (time.monotonic() - started)
+ if self._inner is not None:
+ fn = getattr(self._inner, "on_phase_done", None)
+ if callable(fn):
+ fn(phase)
+
+ def on_message(self, level: str, text: str) -> None:
+ if self._inner is not None:
+ self._inner.on_message(level, text)
+
+ # Forward any other attribute the inner callback exposes (e.g.
+ # ``set_cost`` on the Rich callback). Keeps the recorder a true
+ # transparent wrapper without enumerating optional surface area.
+ def __getattr__(self, name: str) -> Any:
+ if self._inner is None:
+ raise AttributeError(name)
+ return getattr(self._inner, name)
diff --git a/tests/unit/ingestion/test_csharp_framework_edges.py b/tests/unit/ingestion/test_csharp_framework_edges.py
index c18367df2..1516c5986 100644
--- a/tests/unit/ingestion/test_csharp_framework_edges.py
+++ b/tests/unit/ingestion/test_csharp_framework_edges.py
@@ -126,6 +126,65 @@ public class AppDbContext : DbContext {
add_framework_edges(graph, parsed, ctx, tech_stack=[])
assert graph.has_edge("Infra/AppDbContext.cs", "Domain/User.cs")
+ def test_map_extension_method_resolves_to_definition(self, tmp_path: Path) -> None:
+ """``app.MapCatalogApi()`` should link Program.cs to the file declaring
+ ``public static IEndpointRouteBuilder MapCatalogApi(this IEndpointRouteBuilder app)``.
+ """
+ (tmp_path / "Program.cs").write_text(
+ """using Microsoft.AspNetCore.Builder;
+var app = WebApplication.CreateBuilder(args).Build();
+app.MapCatalogApi();
+app.Run();
+"""
+ )
+ (tmp_path / "Apis").mkdir()
+ (tmp_path / "Apis" / "CatalogApi.cs").write_text(
+ """using Microsoft.AspNetCore.Routing;
+namespace Acme.Api;
+public static class CatalogApi {
+ public static IEndpointRouteBuilder MapCatalogApi(this IEndpointRouteBuilder app)
+ {
+ return app;
+ }
+}
+"""
+ )
+ parsed = _build_parsed_files(tmp_path)
+ graph = nx.DiGraph()
+ for p in parsed:
+ graph.add_node(p)
+ ctx = _ctx(tmp_path, parsed)
+
+ add_framework_edges(graph, parsed, ctx, tech_stack=["aspnet"])
+ assert graph.has_edge("Program.cs", "Apis/CatalogApi.cs")
+ assert graph["Program.cs"]["Apis/CatalogApi.cs"]["edge_type"] == "framework"
+
+ def test_add_extension_on_non_aspnet_host_is_ignored(self, tmp_path: Path) -> None:
+ """Generic ``.Map(...)`` on a non-allowlisted host (e.g. ``List``) must
+ not bind to an unrelated extension method definition.
+ """
+ (tmp_path / "Program.cs").write_text(
+ """using Microsoft.AspNetCore.Builder;
+var items = new List<int>();
+items.MapSomething();
+"""
+ )
+ (tmp_path / "Other.cs").write_text(
+ """namespace Acme;
+public static class Helpers {
+ public static List<int> MapSomething(this List<int> xs) => xs;
+}
+"""
+ )
+ parsed = _build_parsed_files(tmp_path)
+ graph = nx.DiGraph()
+ for p in parsed:
+ graph.add_node(p)
+ ctx = _ctx(tmp_path, parsed)
+ add_framework_edges(graph, parsed, ctx, tech_stack=["aspnet"])
+ # ``List<int>`` is not in the host allowlist → no edge.
+ assert not graph.has_edge("Program.cs", "Other.cs")
+
def test_no_edges_when_no_aspnet_signal(self, tmp_path: Path) -> None:
(tmp_path / "Plain.cs").write_text(
"namespace Plain;\npublic class Foo {}\n"
diff --git a/tests/unit/pipeline/test_phase_timing.py b/tests/unit/pipeline/test_phase_timing.py
new file mode 100644
index 000000000..3d8123d00
--- /dev/null
+++ b/tests/unit/pipeline/test_phase_timing.py
@@ -0,0 +1,87 @@
+"""Unit tests for ``PhaseTimingRecorder``."""
+
+from __future__ import annotations
+
+import time
+
+from repowise.core.pipeline import PhaseTimingRecorder
+
+
+class _CollectingCallback:
+ """Inner callback that records the events it received."""
+
+ def __init__(self) -> None:
+ self.events: list[tuple[str, str, int | None]] = []
+ self.messages: list[tuple[str, str]] = []
+
+ def on_phase_start(self, phase: str, total: int | None) -> None:
+ self.events.append(("start", phase, total))
+
+ def on_item_done(self, phase: str) -> None:
+ self.events.append(("item", phase, None))
+
+ def on_phase_done(self, phase: str) -> None:
+ self.events.append(("done", phase, None))
+
+ def on_message(self, level: str, text: str) -> None:
+ self.messages.append((level, text))
+
+
+def test_records_phase_duration() -> None:
+ inner = _CollectingCallback()
+ rec = PhaseTimingRecorder(inner)
+
+ rec.on_phase_start("parse", 10)
+ time.sleep(0.02)
+ rec.on_phase_done("parse")
+
+ assert "parse" in rec.timings
+ assert rec.timings["parse"] >= 0.01
+
+
+def test_repeated_phases_accumulate() -> None:
+ rec = PhaseTimingRecorder()
+
+ rec.on_phase_start("graph.metrics", None)
+ time.sleep(0.01)
+ rec.on_phase_done("graph.metrics")
+
+ rec.on_phase_start("graph.metrics", None)
+ time.sleep(0.01)
+ rec.on_phase_done("graph.metrics")
+
+ # Both visits sum into a single accumulated bucket.
+ assert rec.timings["graph.metrics"] >= 0.02
+
+
+def test_delegates_to_inner_callback() -> None:
+ inner = _CollectingCallback()
+ rec = PhaseTimingRecorder(inner)
+
+ rec.on_phase_start("traverse", 5)
+ rec.on_item_done("traverse")
+ rec.on_phase_done("traverse")
+ rec.on_message("info", "hello")
+
+ assert ("start", "traverse", 5) in inner.events
+ assert ("item", "traverse", None) in inner.events
+ assert ("done", "traverse", None) in inner.events
+ assert ("info", "hello") in inner.messages
+
+
+def test_none_inner_is_safe() -> None:
+ """The recorder must work standalone (no inner callback) — e.g. when
+ a test or headless worker just wants timing data."""
+ rec = PhaseTimingRecorder()
+ rec.on_phase_start("p", None)
+ rec.on_item_done("p")
+ rec.on_message("info", "x")
+ rec.on_phase_done("p")
+ assert "p" in rec.timings
+
+
+def test_unstarted_phase_is_ignored() -> None:
+ """An ``on_phase_done`` with no matching start should be a no-op."""
+ rec = PhaseTimingRecorder()
+ rec.on_phase_done("never-started")
+ assert rec.timings == {}
diff --git a/tests/unit/test_dead_code.py b/tests/unit/test_dead_code.py
index c35999c05..c4a261dc5 100644
--- a/tests/unit/test_dead_code.py
+++ b/tests/unit/test_dead_code.py
@@ -244,6 +244,116 @@ def test_interface_without_implementor_demoted_below_safe_threshold():
assert f.safe_to_delete is False
+def test_com_contract_method_demoted_below_safe_threshold():
+ """``QueryInterface`` / ``AddRef`` / ``Release`` are reached through
+ a native COM vtable — never via a static caller. The analyzer must
+ not flag them as confident dead code.
+ """
+ g = _build_graph(
+ nodes={
+ "src/CoFoo.cpp": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 3,
+ "symbols": [
+ {
+ "name": "QueryInterface",
+ "kind": "method",
+ "visibility": "public",
+ "decorators": [],
+ "start_line": 10,
+ "end_line": 25,
+ "complexity_estimate": 1,
+ "language": "cpp",
+ },
+ {
+ "name": "AddRef",
+ "kind": "function",
+ "visibility": "public",
+ "decorators": [],
+ "start_line": 27,
+ "end_line": 30,
+ "complexity_estimate": 1,
+ "language": "cpp",
+ },
+ {
+ "name": "Release",
+ "kind": "method",
+ "visibility": "public",
+ "decorators": [],
+ "start_line": 32,
+ "end_line": 40,
+ "complexity_estimate": 1,
+ "language": "cpp",
+ },
+ ],
+ },
+ },
+ edges=[],
+ )
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze({
+ "detect_unreachable_files": False,
+ "detect_zombie_packages": False,
+ "min_confidence": 0.0,
+ })
+ com_findings = [
+ f for f in report.findings
+ if f.symbol_name in {"QueryInterface", "AddRef", "Release"}
+ ]
+ for f in com_findings:
+ assert f.confidence <= 0.4, f"COM method flagged at unsafe confidence {f.confidence}"
+ assert f.safe_to_delete is False
+
+
+def test_release_in_non_com_language_not_clamped():
+ """A free function named ``Release`` in TypeScript/Python is *not* a
+ COM contract method — the contract-method clamp must not apply.
+ """
+ g = _build_graph(
+ nodes={
+ "src/foo.ts": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 1,
+ "symbols": [
+ {
+ "name": "Release",
+ "kind": "function",
+ "visibility": "public",
+ "decorators": [],
+ "start_line": 1,
+ "end_line": 5,
+ "complexity_estimate": 1,
+ "language": "typescript",
+ },
+ ],
+ },
+ },
+ edges=[],
+ )
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze({
+ "detect_unreachable_files": False,
+ "detect_zombie_packages": False,
+ "min_confidence": 0.0,
+ })
+ # TS ``function`` kind is universally skipped from unused-export
+ # detection (functions surface as variables in JS-style modules),
+ # so the strongest assertion is "no spurious COM clamp masked the
+ # real behaviour". The function should still be detectable somehow
+ # downstream; here we just confirm the analyzer didn't crash and
+ # didn't ship it under contract-method semantics.
+ com_findings = [f for f in report.findings if f.symbol_name == "Release"]
+ for f in com_findings:
+ # If it surfaces at all, it must do so under the *normal*
+ # rule — not under the COM clamp specifically. The normal
+ # rule yields 0.7 / 1.0 depending on file-level importers.
+ assert f.confidence >= 0.7 or f.confidence < 0.4
+
+
# ---------------------------------------------------------------------------
# 5. test_framework_decorator_excluded
# ---------------------------------------------------------------------------