Skip to content

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

fix(events): take component snapshots on repos with git owners (#3808)

Raghav Chamadiya66709a52411a
diff --git a/packages/cli/src/repowise/cli/commands/components_cmd.py b/packages/cli/src/repowise/cli/commands/components_cmd.py
index fd670b404..31c01b16d 100644
--- a/packages/cli/src/repowise/cli/commands/components_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/components_cmd.py
@@ -223,7 +223,22 @@ def components_ownership(repo: str | None, fmt: str) -> None:
for name, f in findings:
console.print(f"[yellow]{f['kind']}[/yellow] {escape(name)}: {escape(f['message'])}")
if not findings:
- console.print("[green]No ownership findings.[/green]")
+ console.print("No ownership findings.")
+ # What the check could see, so no findings is not read as all owners active.
+ owned = sum(1 for b in blocks.values() if b.get("files_with_declared_owner"))
+ unmatched = sum(
+ 1
+ for b in blocks.values()
+ if (b.get("declared_individuals") or {}).get("unknown")
+ or any(t.get("activity") == "unknown" for t in b.get("declared_teams", ()))
+ )
+ line = f"{owned} of {len(blocks)} component(s) have a declared owner."
+ if data["indexed"] and unmatched:
+ line += (
+ f" In {unmatched}, a declared owner matches no commit author, so that owner's"
+ " activity is unknown, not inactive."
+ )
+ console.print(f"[dim]{line}[/dim]")
if not data["indexed"]:
console.print(
"[dim]No index found: recent activity is unknown, "
diff --git a/packages/cli/src/repowise/cli/commands/events_cmd.py b/packages/cli/src/repowise/cli/commands/events_cmd.py
index 994982af8..8c6e43543 100644
--- a/packages/cli/src/repowise/cli/commands/events_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/events_cmd.py
@@ -37,13 +37,23 @@ def _parse_since(value: str | None) -> datetime | None:
async def _read(root: Path, since: datetime | None, kinds: tuple[str, ...], limit: int):
- from repowise.core.events.store import list_events
+ """``(events, snapshot runs stored)``, or ``None`` without an index."""
+ from sqlalchemy import func, select
+
+ from repowise.core.events.store import GAP_STAMP, list_events
+ from repowise.core.persistence.models import SnapshotRun
async with repo_index_session(root) as opened:
if opened is None:
return None
session, repo_id = opened
- return await list_events(session, repo_id, since=since, kinds=kinds, limit=limit)
+ events = await list_events(session, repo_id, since=since, kinds=kinds, limit=limit)
+ runs = await session.scalar(
+ select(func.count()).where(
+ SnapshotRun.repository_id == repo_id, ~SnapshotRun.stamp.startswith(GAP_STAMP)
+ )
+ )
+ return events, int(runs or 0)
@click.command("events")
@@ -63,10 +73,11 @@ def events_command(
raise click.BadParameter(f"unknown kind(s) {unknown}; known: {sorted(KINDS)}")
target = resolve_command_target(path=repo, no_workspace_flag=True)
assert target.repo_path is not None
- events = run_async(_read(Path(target.repo_path).resolve(), _parse_since(since), kinds, limit))
- if events is None:
+ read = run_async(_read(Path(target.repo_path).resolve(), _parse_since(since), kinds, limit))
+ if read is None:
console.print("No index found. Run `repowise init` first.")
raise SystemExit(1)
+ events, runs = read
if fmt == "json":
emit_json({"events": [to_cloudevent(e) for e in events]})
return
@@ -77,6 +88,18 @@ def events_command(
from rich.markup import escape
from rich.table import Table
+ if not events:
+ # An empty list is only news once two runs could be compared.
+ if runs < 2:
+ console.print(
+ f"No events yet: {runs} component snapshot(s) stored. Events are what "
+ "moved between two index runs in a row, so they start after the next "
+ "`repowise update` on a new commit."
+ )
+ else:
+ scope = " match these filters" if since or kinds else ""
+ console.print(f"No events{scope} across {runs} stored component snapshots.")
+ return
table = Table("When", "Kind", "Component", "Severity", "Evidence")
for e in events:
evidence = ", ".join(f"{k}={v}" for k, v in e.evidence.items() if k != "basis")
diff --git a/packages/core/src/repowise/core/changes/reconstruct.py b/packages/core/src/repowise/core/changes/reconstruct.py
index 055fe40f1..b16563729 100644
--- a/packages/core/src/repowise/core/changes/reconstruct.py
+++ b/packages/core/src/repowise/core/changes/reconstruct.py
@@ -112,6 +112,8 @@ def change_title(subject: str, body: str, is_merge: bool) -> str:
if subject.startswith(_BOILERPLATE_MERGE):
for line in body.splitlines():
line = line.strip()
+ if line in ("Conflicts:", "# Conflicts:"):
+ break # git's conflict list, kept when a merge commit is not edited
if line and not _TRAILER_LINE.match(line):
return line
return subject
diff --git a/packages/core/src/repowise/core/events/snapshot.py b/packages/core/src/repowise/core/events/snapshot.py
index 486613c45..bbdf47b71 100644
--- a/packages/core/src/repowise/core/events/snapshot.py
+++ b/packages/core/src/repowise/core/events/snapshot.py
@@ -282,16 +282,16 @@ def _ownership(
name = row and row.get("primary_owner_name")
if not name:
continue
- key = resolve(name, row.get("primary_owner_email"))
- if key and not resolve.is_bot(key):
- owners[key] += 1
+ person = resolve(name, row.get("primary_owner_email"))
+ if person and not resolve.is_bot(person):
+ owners[person] += 1
owned = sum(owners.values())
main: list[str] = []
held = 0
- for key, count in sorted(owners.items(), key=lambda kv: (-kv[1], kv[0])):
+ for person, count in sorted(owners.items(), key=lambda kv: (-kv[1], kv[0])):
if held * 2 > owned:
break
- main.append(key)
+ main.append(person)
held += count
recent_authors = {resolve(c["author_name"], c["author_email"]) for c in commits}
return {
diff --git a/packages/core/src/repowise/core/repo_config.py b/packages/core/src/repowise/core/repo_config.py
index e90bfd598..27ef1cc2f 100644
--- a/packages/core/src/repowise/core/repo_config.py
+++ b/packages/core/src/repowise/core/repo_config.py
@@ -416,8 +416,10 @@ def ensure_manifest_tracked(repo_path: Path | str) -> bool:
def _ensure_gitignored(repo_path: Path | str, pattern: str, comment: str) -> None:
- """Add *pattern* to the repo's ``.gitignore`` if not already listed."""
+ """Add *pattern* to the repo's ``.gitignore`` unless git already ignores it."""
gitignore = Path(repo_path) / ".gitignore"
+ if _git_ignores(repo_path, pattern):
+ return # e.g. a ``.repowise/`` rule: a second line would only dirty the file
if gitignore.exists():
content = gitignore.read_text(encoding="utf-8")
@@ -431,3 +433,28 @@ def _ensure_gitignored(repo_path: Path | str, pattern: str, comment: str) -> Non
gitignore.write_text(content, encoding="utf-8")
else:
gitignore.write_text(f"# {comment}\n{pattern}\n", encoding="utf-8")
+
+
+def _git_ignores(repo_path: Path | str, pattern: str) -> bool:
+ """Whether a ``.gitignore`` inside the repo already covers *pattern*.
+
+ Rules from ``.git/info/exclude`` or a global excludes file do not count:
+ teammates do not share them. ``False`` when git cannot say.
+ """
+ import subprocess
+
+ try:
+ result = subprocess.run(
+ ["git", "check-ignore", "-v", "--no-index", pattern],
+ cwd=repo_path,
+ capture_output=True,
+ text=True,
+ timeout=10,
+ )
+ except (OSError, subprocess.SubprocessError):
+ return False
+ if result.returncode != 0:
+ return False
+ # ``<source>:<line>:<rule><TAB><path>``; a repo .gitignore is reported relative.
+ source = result.stdout.split("\t", 1)[0].rsplit(":", 2)[0]
+ return Path(source).name == ".gitignore" and not Path(source).is_absolute()
diff --git a/packages/server/src/repowise/server/chat_views.py b/packages/server/src/repowise/server/chat_views.py
index a6d14e3c6..c77b9559d 100644
--- a/packages/server/src/repowise/server/chat_views.py
+++ b/packages/server/src/repowise/server/chat_views.py
@@ -721,6 +721,9 @@ def _changes_block(artifact: ViewArtifact) -> Mapping[str, Any]:
def _window(block: Mapping[str, Any]) -> str:
window = block.get("window")
+ start = window.get("history_from") if isinstance(window, Mapping) else None
+ if isinstance(start, str):
+ return f" since {start[:10]}, where the indexed history starts"
days = window.get("days") if isinstance(window, Mapping) else None
return f" over the last {days} days of merged changes" if isinstance(days, int) else ""
diff --git a/packages/server/src/repowise/server/mcp_server/_changes.py b/packages/server/src/repowise/server/mcp_server/_changes.py
index 85a3a523f..b407e73d2 100644
--- a/packages/server/src/repowise/server/mcp_server/_changes.py
+++ b/packages/server/src/repowise/server/mcp_server/_changes.py
@@ -247,14 +247,17 @@ async def overview_changes(session: Any, repository: Any) -> dict[str, Any]:
The window ends at the newest merged change, so an idle repository still
shows its last stretch of work; ``window`` names both ends.
"""
- until = (
+ oldest, until = (
await session.execute(
- select(func.max(Change.merged_at)).where(Change.repository_id == repository.id)
+ select(func.min(Change.merged_at), func.max(Change.merged_at)).where(
+ Change.repository_id == repository.id
+ )
)
- ).scalar()
+ ).one()
if until is None:
return {"total": 0}
until = until if until.tzinfo else until.replace(tzinfo=UTC)
+ oldest = oldest if oldest.tzinfo else oldest.replace(tzinfo=UTC)
since = until - timedelta(days=OVERVIEW_WINDOW_DAYS)
rows = (
await session.execute(
@@ -266,12 +269,17 @@ async def overview_changes(session: Any, repository: Any) -> dict[str, Any]:
weeks: Counter[str] = Counter(
_week(m if m.tzinfo else m.replace(tzinfo=UTC)) for m, _, _ in rows
)
- by_week, cursor = [], datetime.fromisoformat(_week(since)).date()
+ window: dict[str, Any] = {"days": OVERVIEW_WINDOW_DAYS, "since": _iso(since), "until": _iso(until)}
+ # The index keeps a bounded commit window: weeks before its oldest change
+ # are unknown, not zero, so the weekly series starts there.
+ if oldest > since:
+ window["history_from"] = _iso(oldest)
+ by_week, cursor = [], datetime.fromisoformat(_week(max(since, oldest))).date()
while cursor <= until.date():
by_week.append({"week": cursor.isoformat(), "changes": weeks.get(cursor.isoformat(), 0)})
cursor += timedelta(days=7)
block: dict[str, Any] = {
- "window": {"days": OVERVIEW_WINDOW_DAYS, "since": _iso(since), "until": _iso(until)},
+ "window": window,
"total": len(rows),
"by_category": dict(Counter(c for _, c, _ in rows).most_common()),
"by_week": by_week,
diff --git a/packages/ui/src/commits/code-evolution-chart.tsx b/packages/ui/src/commits/code-evolution-chart.tsx
index cdaf5b557..728d99672 100644
--- a/packages/ui/src/commits/code-evolution-chart.tsx
+++ b/packages/ui/src/commits/code-evolution-chart.tsx
@@ -267,7 +267,7 @@ export function CodeEvolutionChart({
<ResponsiveContainer width="100%" height={260}>
<AreaChart
data={chartData}
- margin={{ top: 4, right: 8, bottom: 0, left: -16 }}
+ margin={{ top: 4, right: 8, bottom: 0, left: 0 }}
>
<CartesianGrid
strokeDasharray="3 3"
@@ -288,6 +288,8 @@ export function CodeEvolutionChart({
tickLine={false}
width={36}
domain={mode === "share" ? [0, 100] : [0, "auto"]}
+ // Per-band rounding can stack to 100.1; keep the axis at 100%.
+ allowDataOverflow={mode === "share"}
tickFormatter={(v) => (mode === "share" ? `${v}%` : `${v}`)}
/>
<Tooltip
diff --git a/packages/web/src/app/repos/[id]/changes/[changeId]/page.tsx b/packages/web/src/app/repos/[id]/changes/[changeId]/page.tsx
index 616b06867..c4f02c351 100644
--- a/packages/web/src/app/repos/[id]/changes/[changeId]/page.tsx
+++ b/packages/web/src/app/repos/[id]/changes/[changeId]/page.tsx
@@ -70,12 +70,12 @@ async function EvidenceChecklist({ repoId, changeId }: { repoId: string; changeI
<ul className="divide-y divide-[var(--color-border-default)] text-xs">
{evidence.items.map((item) => (
<li key={item.kind} className="flex flex-wrap items-baseline gap-x-3 gap-y-1 py-2">
- <span className="w-48 shrink-0 font-medium text-[var(--color-text-primary)]">
+ <span className="w-full shrink-0 font-medium text-[var(--color-text-primary)] sm:w-48">
{item.label}
</span>
<Badge variant={STATUS_VARIANT[item.status]}>{t(STATUS_KEY[item.status])}</Badge>
<span className="text-[var(--color-text-tertiary)]">{item.basis}</span>
- <span className="min-w-0 flex-1 break-words text-[var(--color-text-secondary)]">
+ <span className="min-w-[10rem] flex-1 break-words text-[var(--color-text-secondary)]">
{valueText(item)}
</span>
</li>
diff --git a/tests/unit/cli/test_components_cmd.py b/tests/unit/cli/test_components_cmd.py
index d5bc17455..c954e5b61 100644
--- a/tests/unit/cli/test_components_cmd.py
+++ b/tests/unit/cli/test_components_cmd.py
@@ -119,6 +119,8 @@ spec: {type: service, lifecycle: production, owner: group:default/money}
text = _invoke(["components", "ownership", "--path", str(repo)])
assert "catalog_entry_no_code ledger" in text.output
+ # The text form says what the check could see, so no findings never reads as all clear.
+ assert "component(s) have a declared owner" in text.output
def test_ownership_reports_a_bad_teams_file_once_without_its_content(repo):
diff --git a/tests/unit/cli/test_events_cmd.py b/tests/unit/cli/test_events_cmd.py
index 5b2faef46..44edef7d0 100644
--- a/tests/unit/cli/test_events_cmd.py
+++ b/tests/unit/cli/test_events_cmd.py
@@ -74,3 +74,11 @@ def test_formats_and_filters(tmp_path):
assert bad.exit_code != 0
bad_since = runner.invoke(events_command, ["--path", str(root), "--since", "yesterday"])
assert bad_since.exit_code != 0
+
+
+def test_no_events_says_whether_runs_could_be_compared(tmp_path):
+ root = _repo(tmp_path)
+ got = CliRunner().invoke(events_command, ["--path", str(root), "--since", "2099-01-01"])
+ assert got.exit_code == 0, got.output
+ # No snapshot is stored, so no events is not a quiet history.
+ assert "No events yet: 0 component snapshot(s) stored" in got.output
diff --git a/tests/unit/core/test_changes.py b/tests/unit/core/test_changes.py
index b59179322..6e8d6de42 100644
--- a/tests/unit/core/test_changes.py
+++ b/tests/unit/core/test_changes.py
@@ -191,6 +191,12 @@ def test_title_skips_boilerplate_and_trailers():
)
assert change_title("Merged PR 9: Fix it", "", True) == "Fix it"
assert change_title("feat: x (#2)", "body", False) == "feat: x (#2)"
+ # A merge committed without editing keeps git's conflict list in its body.
+ subject = "Merge remote-tracking branch 'origin/x' into main"
+ assert change_title(subject, "# Conflicts:\n#\ta.py\n", True) == subject
+ assert change_title(subject, "Conflicts:\n\ta.py\n", True) == subject
+ # A body line that only starts with "#" is still a title.
+ assert change_title(subject, "#123 Fix foo\n", True) == "#123 Fix foo"
def test_repeated_identity_gets_a_distinct_id_and_keeps_it(tmp_path):
diff --git a/tests/unit/core/test_events.py b/tests/unit/core/test_events.py
index c8f79ea61..7a531fd20 100644
--- a/tests/unit/core/test_events.py
+++ b/tests/unit/core/test_events.py
@@ -303,6 +303,44 @@ def test_owner_key_is_kept_and_digests_are_not_plain_hashes(tmp_path):
assert digest != hashlib.sha256(b"[email protected]").hexdigest()[: len(digest)]
+def test_owner_key_leaves_a_gitignore_that_already_covers_it(tmp_path):
+ import subprocess
+
+ subprocess.run(["git", "init", "-q"], cwd=tmp_path, check=True)
+ (tmp_path / ".gitignore").write_text(".repowise/\n", encoding="utf-8")
+ assert snapshot_mod.owner_key(tmp_path) is not None
+ assert (tmp_path / ".gitignore").read_text(encoding="utf-8") == ".repowise/\n"
+
+
+def test_owner_key_is_still_gitignored_when_only_info_exclude_covers_it(tmp_path):
+ import subprocess
+
+ subprocess.run(["git", "init", "-q"], cwd=tmp_path, check=True)
+ (tmp_path / ".git" / "info").mkdir(parents=True, exist_ok=True)
+ (tmp_path / ".git" / "info" / "exclude").write_text(".repowise/\n", encoding="utf-8")
+ assert snapshot_mod.owner_key(tmp_path) is not None
+ ignored = (tmp_path / ".gitignore").read_text(encoding="utf-8").splitlines()
+ assert ".repowise/events.key" in ignored
+
+
+def test_main_owners_are_digested_under_the_repo_key(tmp_path):
+ key = snapshot_mod.owner_key(tmp_path)
+
+ def resolve(name, email):
+ return email
+
+ resolve.is_bot = lambda person: False
+ rows = {
+ "a.py": {"primary_owner_name": "Ann", "primary_owner_email": "[email protected]"},
+ "b.py": {"primary_owner_name": "Ann", "primary_owner_email": "[email protected]"},
+ "c.py": {"primary_owner_name": "Bob", "primary_owner_email": "[email protected]"},
+ }
+ commits = [{"sha": "s1", "author_name": "Ann", "author_email": "[email protected]"}]
+ out = snapshot_mod._ownership(list(rows), rows, commits, resolve, key, False)
+ assert out["main_owners"] == [snapshot_mod._keyed(key, "[email protected]")]
+ assert (out["owned_files"], out["owner_count"], out["active_main_owners"]) == (3, 2, 1)
+
+
def test_credentials_never_leave_in_the_source_url():
from repowise.core.events.store import _public_url
diff --git a/tests/unit/server/mcp/test_changes_mcp.py b/tests/unit/server/mcp/test_changes_mcp.py
index 6fa23d636..120a19a6c 100644
--- a/tests/unit/server/mcp/test_changes_mcp.py
+++ b/tests/unit/server/mcp/test_changes_mcp.py
@@ -262,6 +262,9 @@ async def test_overview_changes_by_category_week_and_agent_share(setup_mcp, sess
assert block["window"]["until"].startswith("2026-03-15")
assert block["by_category"] == {"feature": 3, "fix": 1}
weeks = {w["week"]: w["changes"] for w in block["by_week"]}
+ # History starts inside the window: earlier weeks are unknown, not zero.
+ assert block["window"]["history_from"].startswith("2026-03-01")
+ assert block["by_week"][0]["week"] == "2026-02-23"
assert weeks["2026-02-23"] == 1 and weeks["2026-03-02"] == 2 and weeks["2026-03-09"] == 1
assert sum(weeks.values()) == 4
prov = block["provenance"]
diff --git a/tests/unit/server/test_chat_views.py b/tests/unit/server/test_chat_views.py
index e1504310b..8c36886bd 100644
--- a/tests/unit/server/test_chat_views.py
+++ b/tests/unit/server/test_chat_views.py
@@ -352,6 +352,10 @@ def test_changes_by_category_and_week_plot_the_source_counts():
week = _build(data, "overview", "get_overview", "changes.by_week")
assert week["chart_type"] == "line"
assert _series(week, "changes") == [3, 1]
+ # A shorter indexed history names where it starts instead of the full window.
+ data["changes"]["window"]["history_from"] = "2026-03-02T09:00:00+00:00"
+ week = _build(data, "overview", "get_overview", "changes.by_week")
+ assert "since 2026-03-02" in week["summary"] and "90 days" not in week["summary"]
def test_changes_provenance_keeps_unknown_as_its_own_band():