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(events): component snapshots per index run and typed events between them (#3799)

Raghav Chamadiya4897a7eb7420
diff --git a/docs/reference/API_REFERENCE.md b/docs/reference/API_REFERENCE.md
index cf27bdb1d..bcdcc5d64 100644
--- a/docs/reference/API_REFERENCE.md
+++ b/docs/reference/API_REFERENCE.md
@@ -505,6 +505,7 @@ one per router area; this table maps an area to the tag to open there.
| Dead-code findings | `dead-code` | `routers/dead_code.py` |
| Change risk, hotspots, ownership, commits, co-changes | `git` | `routers/git.py` |
| Merged changes (Change Records) reconstructed from git | `changes` | `routers/changes.py` |
+| Typed events from consecutive index runs (CloudEvents, pull) | `events` | `routers/events.py` |
| Structural coupling report | `coupling` | `routers/coupling.py` |
| Blast radius for a change | `blast-radius` | `routers/blast_radius.py` |
| Architectural decisions, lanes, lineage, policy settings | `decisions` | `routers/decisions.py` |
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.md
index 7f6e33c49..7f9cf0d1b 100644
--- a/docs/reference/CLI_REFERENCE.md
+++ b/docs/reference/CLI_REFERENCE.md
@@ -40,7 +40,8 @@ Grouped by what you're trying to do, not alphabetically. `PATH` and flag details
[`impacted-tests`](#repowise-impacted-tests-revspec) ·
[`coverage`](#repowise-coverage) ·
[`components`](#repowise-components) ·
-[`changes`](#repowise-changes)
+[`changes`](#repowise-changes) ·
+[`events`](#repowise-events)
**Decisions**
[`decision`](#repowise-decision)
@@ -1620,6 +1621,18 @@ Teams that already run OPA can use the `evidence` object of `repowise check --fo
---
+### `repowise events`
+
+Typed events between consecutive index runs. Each `init` and `update` stores a snapshot of every component (ownership counts, bus factor, hotspots, dead code, governing decisions, provided contracts, test reach, attribution with coverage) under the analyzer and parser stamp it ran with. When an index run and the run right before it share a stamp, what moved is stored as an event. A stamp change starts a new baseline, and so does the first run after one that took no snapshot (events switched off, or the snapshot failed); a run on the commit already snapshotted, including `--working-tree` on it, is skipped. Events are written as CloudEvents JSON lines to `.repowise/events.jsonl` and read back here, oldest first.
+
+```bash
+repowise events [--path PATH] [--since 7d|12h|ISO-DATE] [--kind KIND]... [--limit N] [--format table|json|jsonl]
+```
+
+Kinds: `ownership_shift`, `owner_inactive`, `bus_factor_drop` (critical components), `new_hotspot` (off by default), `contract_added`, `contract_broken`, `decision_stale`, `dead_code_growth`, `test_reach_drop`, `attribution_jump` (regulated components). The `events:` block in `.repowise/config.yaml` sets `enabled`, `retention_days` (365), `compact_after_days` (30; older runs keep one per week), per-kind switches under `kinds`, and the `sinks` to deliver to (`jsonl` by default, `stdout` for CI).
+
+---
+
### `repowise distill <command>`
Run a command and print a compact, reversible rendering of its output. Noise
diff --git a/docs/reference/CONFIG.md b/docs/reference/CONFIG.md
index 3f3d81450..c3213f268 100644
--- a/docs/reference/CONFIG.md
+++ b/docs/reference/CONFIG.md
@@ -17,6 +17,7 @@ The `.repowise/` directory, provider setup, API keys, and what's customizable.
[`policies.yaml`](#repowisepoliciesyaml) ·
[The `security:` block](#the-security-block) ·
[The `attribution:` block](#the-attribution-block) ·
+[The `events:` block](#the-events-block) ·
[The `refactoring:` block](#the-refactoring-block) ·
[The `assertions:` block](#the-assertions-block)
@@ -74,6 +75,8 @@ repo root on first `init`.
├── lancedb/ # Vector search index (LanceDB)
├── omissions/ # Distill omission store + savings ledger (omissions.db)
├── config.yaml # Provider, model, embedder, exclude patterns, distill/mcp/refactoring blocks
+├── events.jsonl # Typed events as CloudEvents JSON lines (the jsonl event sink)
+├── events.key # Random key the owner digests in component snapshots are made with
├── health-rules.json # Per-file code-health marker overrides
├── state.json # Last sync commit, page counts, token usage
├── mcp.json # MCP server configuration
@@ -641,6 +644,19 @@ The same block in `~/.repowise/config.yaml` applies to every repository, and the
`capture: local` records the listed agents' edits as line hashes in `.repowise/attribution/`; `capture: notes` also writes git-ai notes on `refs/notes/ai`. What each level stores, and what leaves the machine, is in [ATTRIBUTION.md](../layers/ATTRIBUTION.md). The same consent lets `repowise attribution backfill --agent claude-code,codex` bind past commits from the transcripts these agents keep on this machine.
+### The `events:` block
+
+```yaml
+events:
+ enabled: true # snapshot components at each index run and diff them
+ retention_days: 365 # older runs and events are dropped
+ compact_after_days: 30 # older runs keep one per ISO week
+ kinds: {new_hotspot: true}
+ sinks: [jsonl] # jsonl (.repowise/events.jsonl), stdout, or a plugin's sink
+```
+
+An index run diffs into typed events against the run right before it when both ran under the same analyzer and parser stamp; a stamp change, or a run in between that took no snapshot, starts a new baseline. Owners are compared as keyed digests made with a random per-repository key in `.repowise/events.key`; a declared owner is named only when it is a group. `repowise doctor` names any value in this block that fell back to its default. Severity follows the component's `repowise.dev/criticality`. `new_hotspot` is off by default; every other kind is on. Read them with `repowise events` or `GET /api/repos/{id}/events`.
+
### The `refactoring:` block
Controls the refactoring-intelligence layer: the structured Extract Class /
diff --git a/packages/api-client/package.json b/packages/api-client/package.json
index c2955b68b..8455fd23a 100644
--- a/packages/api-client/package.json
+++ b/packages/api-client/package.json
@@ -17,6 +17,7 @@
"./cache": "./src/cache.ts",
"./cards": "./src/cards.ts",
"./changes": "./src/changes.ts",
+ "./events": "./src/events.ts",
"./chat": "./src/chat.ts",
"./code-health": "./src/code-health.ts",
"./costs": "./src/costs.ts",
diff --git a/packages/api-client/src/events.ts b/packages/api-client/src/events.ts
new file mode 100644
index 000000000..15c66b608
--- /dev/null
+++ b/packages/api-client/src/events.ts
@@ -0,0 +1,18 @@
+/**
+ * Event endpoint: typed events from consecutive index runs, pulled by time.
+ *
+ * Types come from `@repowise-dev/types/events`, re-exported here so a
+ * consumer needs one import.
+ */
+import { apiGet } from "./client";
+import type { CloudEvent, EventListResponse } from "@repowise-dev/types/events";
+
+export type { CloudEvent, EventListResponse };
+
+/** Stored events, oldest first, from `since` (ISO time) on. */
+export async function listEvents(
+ repoId: string,
+ opts?: { since?: string; kind?: string; limit?: number },
+): Promise<EventListResponse> {
+ return apiGet<EventListResponse>(`/api/repos/${repoId}/events`, opts);
+}
diff --git a/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.py b/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.py
index d50aee902..51b97cb96 100644
--- a/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.py
+++ b/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.py
@@ -276,6 +276,19 @@ def _attribution_notes_check(repo_path: _DoctorPath) -> DoctorCheck | None:
return _check(name, True, f"fetch refspec and notes.rewriteRef set; {push}")
+def _events_config_check(repo_path: _DoctorPath) -> DoctorCheck | None:
+ """The ``events:`` block, when it has values that fell back to defaults."""
+ try:
+ from repowise.core.events.store import load_event_settings
+
+ errors = load_event_settings(repo_path).errors
+ except Exception as exc:
+ return _check("Events config", True, f"could not read it ({exc})")
+ if not errors:
+ return None
+ return _check("Events config", False, "; ".join(errors) + " (defaults used)")
+
+
def _run_repo_checks(
repo_path: _DoctorPath, repair: bool, *, fmt: str = "table"
) -> tuple[bool, list[DoctorCheck]]:
@@ -310,6 +323,9 @@ def _run_repo_checks(
notes_check = _attribution_notes_check(repo_path)
if notes_check is not None:
checks.append(notes_check)
+ events_check = _events_config_check(repo_path)
+ if events_check is not None:
+ checks.append(events_check)
# 3. Database connectable?
db_path = repowise_dir / "wiki.db"
diff --git a/packages/cli/src/repowise/cli/commands/events_cmd.py b/packages/cli/src/repowise/cli/commands/events_cmd.py
new file mode 100644
index 000000000..994982af8
--- /dev/null
+++ b/packages/cli/src/repowise/cli/commands/events_cmd.py
@@ -0,0 +1,91 @@
+"""``repowise events`` - typed events from consecutive index runs.
+
+Each ``repowise init`` or ``update`` snapshots the components; when two runs
+in a row share an analyzer stamp, what moved between them is stored as
+events. This command reads them back, oldest first, as a table, JSON, or
+CloudEvents JSON lines (the shape the ``jsonl`` sink writes).
+"""
+
+from __future__ import annotations
+
+import json
+import re
+from datetime import UTC, datetime, timedelta
+from pathlib import Path
+
+import click
+
+from repowise.cli.helpers import console, repo_index_session, resolve_command_target, run_async
+from repowise.cli.output import emit_json, format_option
+
+_RELATIVE = re.compile(r"^(\d+)([dh])$")
+
+
+def _parse_since(value: str | None) -> datetime | None:
+ """``7d``, ``12h``, or an ISO date or datetime (UTC when no zone is given)."""
+ if not value:
+ return None
+ m = _RELATIVE.match(value.strip())
+ if m:
+ n, unit = int(m.group(1)), m.group(2)
+ return datetime.now(UTC) - (timedelta(days=n) if unit == "d" else timedelta(hours=n))
+ try:
+ parsed = datetime.fromisoformat(value)
+ except ValueError as exc:
+ raise click.BadParameter(f"expected 7d, 12h or an ISO date, got {value!r}") from exc
+ return parsed if parsed.tzinfo else parsed.replace(tzinfo=UTC)
+
+
+async def _read(root: Path, since: datetime | None, kinds: tuple[str, ...], limit: int):
+ from repowise.core.events.store import list_events
+
+ 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)
+
+
[email protected]("--path", "repo", default=None, help="Repo path (defaults to cwd).")
[email protected]("--since", default=None, help="Only events from then on: 7d, 12h or an ISO date.")
[email protected]("--kind", "kinds", multiple=True, help="Only this kind (repeatable).")
[email protected]("--limit", default=200, show_default=True, type=click.IntRange(1, 10000))
+@format_option(choices=("table", "json", "jsonl"))
+def events_command(
+ repo: str | None, since: str | None, kinds: tuple[str, ...], limit: int, fmt: str
+) -> None:
+ """List typed events (new hotspot, bus factor drop, ...) oldest first."""
+ from repowise.core.events.model import KINDS, to_cloudevent
+
+ unknown = [k for k in kinds if k not in KINDS]
+ if unknown:
+ 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:
+ console.print("No index found. Run `repowise init` first.")
+ raise SystemExit(1)
+ if fmt == "json":
+ emit_json({"events": [to_cloudevent(e) for e in events]})
+ return
+ if fmt == "jsonl":
+ for e in events:
+ click.echo(json.dumps(to_cloudevent(e), sort_keys=True))
+ return
+ from rich.markup import escape
+ from rich.table import Table
+
+ 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")
+ table.add_row(
+ e.occurred_at.strftime("%Y-%m-%d %H:%M"),
+ e.kind,
+ escape(e.component or ""),
+ e.severity,
+ escape(evidence[:100]),
+ )
+ console.print(table)
+ console.print(f"[dim]{len(events)} event(s).[/dim]")
diff --git a/packages/cli/src/repowise/cli/main.py b/packages/cli/src/repowise/cli/main.py
index 72dc306c1..7139efc20 100644
--- a/packages/cli/src/repowise/cli/main.py
+++ b/packages/cli/src/repowise/cli/main.py
@@ -74,6 +74,7 @@ _OSS_COMMANDS: tuple[tuple[str, str], ...] = (
("components", "components_cmd:components_group"),
("changes", "changes_cmd:changes_group"),
("check", "check_cmd:check_command"),
+ ("events", "events_cmd:events_command"),
("impacted-tests", "impacted_tests_cmd:impacted_tests_command"),
("search", "search_cmd:search_command"),
("ask", "ask_cmd:ask_command"),
diff --git a/packages/core/alembic/versions/0113_snapshots_events.py b/packages/core/alembic/versions/0113_snapshots_events.py
new file mode 100644
index 000000000..0f5a19d90
--- /dev/null
+++ b/packages/core/alembic/versions/0113_snapshots_events.py
@@ -0,0 +1,85 @@
+"""Component snapshots per index run, and the typed events diffed from them.
+
+``snapshot_runs`` holds one row per index run with the analyzer and parser
+stamp it ran under; ``component_snapshots`` the facts per component of that
+run; ``events`` the typed events two consecutive same-stamp runs produced
+(see ``repowise.core.events``).
+
+Local SQLite stores never run Alembic; ``init_db`` creates the tables there.
+
+Revision ID: 0113
+Revises: 0112
+Create Date: 2026-10-14
+"""
+
+from __future__ import annotations
+
+from collections.abc import Sequence
+
+import sqlalchemy as sa
+from alembic import op
+
+# revision identifiers
+revision: str = "0113"
+down_revision: str | None = "0112"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+
+def upgrade() -> None:
+ op.create_table(
+ "snapshot_runs",
+ sa.Column("id", sa.String(32), primary_key=True),
+ sa.Column(
+ "repository_id",
+ sa.String(32),
+ sa.ForeignKey("repositories.id", ondelete="CASCADE"),
+ nullable=False,
+ ),
+ sa.Column("taken_at", sa.DateTime(timezone=True), nullable=False),
+ sa.Column("commit_sha", sa.String(40), nullable=True),
+ sa.Column("stamp", sa.String(64), nullable=False),
+ sa.Column("compacted", sa.Boolean, nullable=False, server_default=sa.false()),
+ )
+ op.create_index("ix_snapshot_runs_repo_taken", "snapshot_runs", ["repository_id", "taken_at"])
+ op.create_table(
+ "component_snapshots",
+ sa.Column("id", sa.String(32), primary_key=True),
+ sa.Column(
+ "run_id",
+ sa.String(32),
+ sa.ForeignKey("snapshot_runs.id", ondelete="CASCADE"),
+ nullable=False,
+ ),
+ sa.Column("component", sa.String(255), nullable=False),
+ sa.Column("facts_json", sa.Text, nullable=False),
+ sa.UniqueConstraint("run_id", "component", name="uq_component_snapshot"),
+ )
+ op.create_table(
+ "events",
+ sa.Column("id", sa.String(32), primary_key=True),
+ sa.Column(
+ "repository_id",
+ sa.String(32),
+ sa.ForeignKey("repositories.id", ondelete="CASCADE"),
+ nullable=False,
+ ),
+ sa.Column("kind", sa.String(32), nullable=False),
+ sa.Column("component", sa.String(255), nullable=True),
+ sa.Column("severity", sa.String(16), nullable=False),
+ sa.Column("occurred_at", sa.DateTime(timezone=True), nullable=False),
+ sa.Column("commit_sha", sa.String(40), nullable=True),
+ sa.Column("base_commit_sha", sa.String(40), nullable=True),
+ sa.Column("stamp", sa.String(64), nullable=False),
+ sa.Column("payload_json", sa.Text, nullable=False),
+ sa.Column("schema_version", sa.Integer, nullable=False, server_default="1"),
+ )
+ op.create_index("ix_events_repo_occurred", "events", ["repository_id", "occurred_at"])
+
+
+def downgrade() -> None:
+ op.drop_index("ix_events_repo_occurred", table_name="events")
+ op.drop_table("events")
+ op.drop_table("component_snapshots")
+ op.drop_index("ix_snapshot_runs_repo_taken", table_name="snapshot_runs")
+ op.drop_table("snapshot_runs")
diff --git a/packages/core/src/repowise/core/events/__init__.py b/packages/core/src/repowise/core/events/__init__.py
new file mode 100644
index 000000000..232237289
--- /dev/null
+++ b/packages/core/src/repowise/core/events/__init__.py
@@ -0,0 +1,14 @@
+"""Component snapshots per index run, and typed events diffed from them.
+
+Each index run stores component-level facts (:mod:`.snapshot`) under the
+analyzer and parser stamp it ran with. Two consecutive runs with the same
+stamp diff into typed occurrences (:mod:`.diff`), stored as events
+(:mod:`.store`) and handed to the ``event-sink`` seam (:mod:`.sinks`) in
+their CloudEvents form (:mod:`.model`).
+"""
+
+from __future__ import annotations
+
+from repowise.core.events.model import KINDS, EngineEvent, EventKind, to_cloudevent
+
+__all__ = ["KINDS", "EngineEvent", "EventKind", "to_cloudevent"]
diff --git a/packages/core/src/repowise/core/events/diff.py b/packages/core/src/repowise/core/events/diff.py
new file mode 100644
index 000000000..c11b09a90
--- /dev/null
+++ b/packages/core/src/repowise/core/events/diff.py
@@ -0,0 +1,224 @@
+"""Typed occurrences between two consecutive same-stamp component snapshots.
+
+Pure: two ``{component: facts}`` maps in, ``(kind, component, subject,
+evidence)`` tuples out. A component diffs only when it exists in both runs
+with the same definition (paths, root, source), so a re-drawn component
+never reads as its facts moving. Every rule prefers a miss over a false
+hit: it needs a measured basis on both sides and a size floor.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Iterator, Mapping
+from typing import Any
+
+#: Criticality levels a "critical component" rule applies to.
+CRITICAL_LEVELS = frozenset({"high", "critical"})
+#: Component tags that make attribution moves worth an event.
+REGULATED_TAGS = frozenset({"regulated", "pci", "cra-product"})
+
+#: Below this many owned files ownership figures are anecdotes.
+MIN_OWNED_FILES = 5
+#: Main-owner sets this dissimilar (Jaccard) count as a shift.
+OWNERSHIP_SHIFT_JACCARD = 0.5
+#: Dead code must grow by both of these to count.
+DEAD_CODE_MIN_FINDINGS = 5
+DEAD_CODE_MIN_RATIO = 0.25
+#: Test reach must fall by this share, over at least this many production files.
+TEST_REACH_MIN_DROP = 0.10
+TEST_REACH_MIN_FILES = 5
+#: Measured line coverage must fall by this many points.
+LINE_COVERAGE_MIN_DROP = 5.0
+#: Agent share must move by this much, over at least this many commits per run.
+ATTRIBUTION_MIN_DELTA = 0.20
+ATTRIBUTION_MIN_COMMITS = 10
+
+Occurrence = tuple[str, str, str, dict[str, Any]]
+
+
+def diff_snapshots(
+ previous: Mapping[str, Mapping[str, Any]], current: Mapping[str, Mapping[str, Any]]
+) -> list[Occurrence]:
+ """Every occurrence between *previous* and *current*, in a stable order."""
+ out: list[Occurrence] = []
+ for name in sorted(current):
+ before, after = previous.get(name), current[name]
+ if before is None or before.get("definition") != after.get("definition"):
+ continue
+ for rule in _RULES:
+ out.extend((kind, name, subject, ev) for kind, subject, ev in rule(before, after))
+ return out
+
+
+def _get(facts: Mapping[str, Any], key: str) -> dict[str, Any]:
+ value = facts.get(key)
+ return value if isinstance(value, dict) else {}
+
+
+def _same_key(before: Mapping[str, Any], after: Mapping[str, Any]) -> bool:
+ """Owner digests compare only when both runs used the same digest key."""
+ return bool(before.get("key_id")) and before.get("key_id") == after.get("key_id")
+
+
+def _ownership(before: Mapping[str, Any], after: Mapping[str, Any]) -> Iterator[tuple]:
+ if not _same_key(before, after):
+ return
+ was, now = before.get("declared_owner_key"), after.get("declared_owner_key")
+ if was and now and was != now:
+ ev: dict[str, Any] = {"basis": "declared"}
+ # Group refs are named; any other owner is reported as changed, unnamed.
+ if before.get("declared_owner"):
+ ev["previous_owner"] = before["declared_owner"]
+ if after.get("declared_owner"):
+ ev["owner"] = after["declared_owner"]
+ yield "ownership_shift", "declared", ev
+ return
+ a, b = _get(before, "ownership"), _get(after, "ownership")
+ if min(a.get("owned_files", 0), b.get("owned_files", 0)) < MIN_OWNED_FILES:
+ return
+ old, new = set(a.get("main_owners") or ()), set(b.get("main_owners") or ())
+ if old and new and len(old & new) / len(old | new) < OWNERSHIP_SHIFT_JACCARD:
+ yield "ownership_shift", "observed", {
+ "basis": "observed",
+ "main_owners_before": len(old),
+ "main_owners_after": len(new),
+ "main_owners_kept": len(old & new),
+ "owned_files": b["owned_files"],
+ }
+
+
+def _owner_inactive(before: Mapping[str, Any], after: Mapping[str, Any]) -> Iterator[tuple]:
+ a, b = _get(before, "ownership"), _get(after, "ownership")
+ if not _same_key(before, after) or not b.get("main_owners") or b.get("recent_capped"):
+ return
+ if b.get("owned_files", 0) < MIN_OWNED_FILES or a.get("main_owners") != b.get("main_owners"):
+ return
+ # Others still change it: a quiet component is stable, not abandoned.
+ if b.get("recent_commits", 0) == 0:
+ return
+ if a.get("active_main_owners", 0) > 0 and b.get("active_main_owners") == 0:
+ yield "owner_inactive", "", {
+ "basis": "observed",
+ "main_owners": len(b.get("main_owners") or ()),
+ "window_days": b.get("window_days"),
+ "recent_commits": b.get("recent_commits"),
+ }
+
+
+def _bus_factor(before: Mapping[str, Any], after: Mapping[str, Any]) -> Iterator[tuple]:
+ if after.get("criticality") not in CRITICAL_LEVELS:
+ return
+ a, b = _get(before, "bus_factor"), _get(after, "bus_factor")
+ if a.get("basis") != "measured" or b.get("basis") != "measured":
+ return
+ if b["value"] < a["value"]:
+ yield "bus_factor_drop", "", {
+ "basis": "measured",
+ "previous": a["value"],
+ "value": b["value"],
+ "owned_files": b.get("owned_files"),
+ }
+
+
+def _hotspots(before: Mapping[str, Any], after: Mapping[str, Any]) -> Iterator[tuple]:
+ old = set(before.get("hotspots") or ())
+ new = sorted(set(after.get("hotspots") or ()) - old)
+ if new:
+ yield "new_hotspot", ",".join(new), {
+ "basis": "measured",
+ "files": new,
+ "hotspots_before": len(old),
+ "hotspots_after": len(after.get("hotspots") or ()),
+ }
+
+
+def _contracts(before: Mapping[str, Any], after: Mapping[str, Any]) -> Iterator[tuple]:
+ a, b = _get(before, "contracts"), _get(after, "contracts")
+ if a.get("basis") != "measured" or b.get("basis") != "measured":
+ return
+ old, new = a.get("provided") or {}, b.get("provided") or {}
+ for cid in sorted(set(new) - set(old)):
+ yield "contract_added", cid, {"basis": "measured", "contract_id": cid}
+ for cid in sorted(set(old) - set(new)):
+ if old[cid] > 0: # gone with nobody reading it is a removal, not a break
+ yield "contract_broken", cid, {
+ "basis": "measured",
+ "contract_id": cid,
+ "consumers": old[cid],
+ }
+
+
+def _decisions(before: Mapping[str, Any], after: Mapping[str, Any]) -> Iterator[tuple]:
+ old = set(_get(before, "decisions").get("stale") or ())
+ for did in sorted(set(_get(after, "decisions").get("stale") or ()) - old):
+ yield "decision_stale", did, {"basis": "measured", "decision_id": did}
+
+
+def _dead_code(before: Mapping[str, Any], after: Mapping[str, Any]) -> Iterator[tuple]:
+ a, b = _get(before, "dead_code"), _get(after, "dead_code")
+ if "findings" not in a or "findings" not in b:
+ return
+ grew = b["findings"] - a["findings"]
+ if grew >= DEAD_CODE_MIN_FINDINGS and grew >= DEAD_CODE_MIN_RATIO * max(a["findings"], 1):
+ yield "dead_code_growth", "", {
+ "basis": b.get("basis"),
+ "previous_findings": a["findings"],
+ "findings": b["findings"],
+ "previous_lines": a.get("lines"),
+ "lines": b.get("lines"),
+ }
+
+
+def _test_reach(before: Mapping[str, Any], after: Mapping[str, Any]) -> Iterator[tuple]:
+ a, b = _get(before, "test_reach"), _get(after, "test_reach")
+ if "share" not in a or "share" not in b:
+ return
+ if min(a["production_files"], b["production_files"]) < TEST_REACH_MIN_FILES:
+ return
+ ev: dict[str, Any] = {}
+ if round(a["share"] - b["share"], 3) >= TEST_REACH_MIN_DROP:
+ ev.update(
+ basis=b.get("basis"),
+ previous_share=a["share"],
+ share=b["share"],
+ production_files=b["production_files"],
+ )
+ la, lb = a.get("line_coverage") or {}, b.get("line_coverage") or {}
+ if "pct" in la and "pct" in lb and round(la["pct"] - lb["pct"], 3) >= LINE_COVERAGE_MIN_DROP:
+ ev["line_coverage"] = {"basis": "measured", "previous_pct": la["pct"], "pct": lb["pct"]}
+ if ev:
+ yield "test_reach_drop", "", ev
+
+
+def _attribution(before: Mapping[str, Any], after: Mapping[str, Any]) -> Iterator[tuple]:
+ if not REGULATED_TAGS & set(after.get("tags") or ()):
+ return
+ a, b = _get(before, "attribution"), _get(after, "attribution")
+ if a.get("agent_share") is None or b.get("agent_share") is None:
+ return
+ if a.get("recent_capped") or b.get("recent_capped"):
+ return
+ if min(a.get("commits", 0), b.get("commits", 0)) < ATTRIBUTION_MIN_COMMITS:
+ return
+ if round(abs(b["agent_share"] - a["agent_share"]), 3) >= ATTRIBUTION_MIN_DELTA:
+ yield "attribution_jump", "", {
+ "basis": "measured",
+ "previous_agent_share": a["agent_share"],
+ "agent_share": b["agent_share"],
+ "coverage": b.get("coverage"),
+ "commits": b.get("commits"),
+ "window_days": b.get("window_days"),
+ }
+
+
+_RULES = (
+ _ownership,
+ _owner_inactive,
+ _bus_factor,
+ _hotspots,
+ _contracts,
+ _decisions,
+ _dead_code,
+ _test_reach,
+ _attribution,
+)
diff --git a/packages/core/src/repowise/core/events/model.py b/packages/core/src/repowise/core/events/model.py
new file mode 100644
index 000000000..a4bbd68e1
--- /dev/null
+++ b/packages/core/src/repowise/core/events/model.py
@@ -0,0 +1,117 @@
+"""The internal event shape, the kinds, and their CloudEvents wire form.
+
+An :class:`EngineEvent` is what the engine stores and hands to sinks. On the
+wire it becomes a CloudEvents 1.0.2 structured JSON event: ``type`` is a
+CDEvents type where CDEvents defines one for the occurrence, else a
+``dev.repowise.<subject>.<predicate>.<version>`` string in the same versioned
+shape; ``data`` carries OTel ``vcs.*`` attribute names for the revision facts.
+No kind here has a CDEvents counterpart (CDEvents v0.5.1 covers repository,
+branch, change, build, test, deploy, incident and ticket occurrences).
+"""
+
+from __future__ import annotations
+
+import hashlib
+from collections.abc import Mapping
+from dataclasses import dataclass, field
+from datetime import datetime
+from typing import Any
+
+#: Bumped when an event's ``evidence`` shape changes meaning.
+EVENT_SCHEMA_VERSION = 1
+CLOUDEVENTS_SPECVERSION = "1.0"
+
+
+@dataclass(frozen=True)
+class EventKind:
+ name: str
+ type: str
+ #: Off by default when the replay found it noisy; config turns it on.
+ default_on: bool
+ summary: str
+
+
+def _kind(name: str, subject: str, predicate: str, on: bool, summary: str) -> EventKind:
+ return EventKind(name, f"dev.repowise.{subject}.{predicate}.0.1.0", on, summary)
+
+
+KINDS: dict[str, EventKind] = {
+ k.name: k
+ for k in (
+ _kind("ownership_shift", "ownership", "shifted", True, "declared owner changed"),
+ _kind("owner_inactive", "owner", "inactive", True, "main owners stopped changing it"),
+ _kind("bus_factor_drop", "busfactor", "dropped", True, "bus factor fell"),
+ _kind("new_hotspot", "hotspot", "added", False, "files became hotspots"),
+ _kind("contract_added", "contract", "added", True, "a provided contract appeared"),
+ _kind("contract_broken", "contract", "broken", True, "a contract with consumers disappeared"),
+ _kind("decision_stale", "decision", "stale", True, "a governing decision went stale"),
+ _kind("dead_code_growth", "deadcode", "grew", True, "dead-code findings grew"),
+ _kind("test_reach_drop", "testreach", "dropped", True, "test reach fell"),
+ _kind("attribution_jump", "attribution", "jumped", True, "agent share moved sharply"),
+ )
+}
+
+#: Component criticality to event severity; a component with none is ``info``.
+SEVERITY_BY_CRITICALITY = {
+ "critical": "critical",
+ "high": "high",
+ "medium": "medium",
+ "low": "low",
+}
+
+
+def severity_for(criticality: str | None) -> str:
+ return SEVERITY_BY_CRITICALITY.get(criticality or "", "info")
+
+
+@dataclass(frozen=True)
+class EngineEvent:
+ id: str
+ kind: str
+ repo_id: str
+ component: str | None
+ severity: str
+ occurred_at: datetime
+ evidence: Mapping[str, Any]
+ stamp: str
+ commit_sha: str | None = None
+ base_commit_sha: str | None = None
+ #: CloudEvents ``source``: the repository URL when known, else its path.
+ source: str = ""
+ #: Revision facts as OTel ``vcs.*`` names (``vcs.change.id`` and such).
+ vcs: Mapping[str, Any] = field(default_factory=dict)
+ schema: int = EVENT_SCHEMA_VERSION
+
+
+def event_id(*parts: str | None) -> str:
+ """A stable id for one occurrence, so re-delivery stays idempotent."""
+ raw = "\x1f".join(p or "" for p in parts)
+ return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:32]
+
+
+def to_cloudevent(event: EngineEvent) -> dict[str, Any]:
+ """The CloudEvents 1.0.2 structured JSON form of *event*."""
+ kind = KINDS.get(event.kind)
+ data: dict[str, Any] = {
+ **event.vcs,
+ "vcs.ref.head.revision": event.commit_sha,
+ "vcs.ref.base.revision": event.base_commit_sha,
+ "repowise.kind": event.kind,
+ "repowise.component": event.component,
+ "repowise.severity": event.severity,
+ "repowise.stamp": event.stamp,
+ "repowise.schema": event.schema,
+ "evidence": dict(event.evidence),
+ }
+ out: dict[str, Any] = {
+ "specversion": CLOUDEVENTS_SPECVERSION,
+ "id": event.id,
+ "source": event.source or f"/repos/{event.repo_id}",
+ "type": kind.type if kind else f"dev.repowise.{event.kind}.0.1.0",
+ "time": event.occurred_at.isoformat().replace("+00:00", "Z"),
+ "datacontenttype": "application/json",
+ "data": {k: v for k, v in data.items() if v is not None},
+ }
+ if event.component:
+ out["subject"] = f"component:{event.component}"
+ return out
diff --git a/packages/core/src/repowise/core/events/sinks.py b/packages/core/src/repowise/core/events/sinks.py
new file mode 100644
index 000000000..d33f66b20
--- /dev/null
+++ b/packages/core/src/repowise/core/events/sinks.py
@@ -0,0 +1,60 @@
+"""Where events go after they are stored: the ``event-sink`` seam.
+
+OSS ships two local sinks and no network delivery: ``jsonl`` appends each
+event as one CloudEvents JSON line to ``.repowise/events.jsonl`` (the
+default), and ``stdout`` prints the same lines for CI. A plugin registers
+another sink (a webhook, a chat app, a SIEM) under ``SeamRegistry("event-sink")``
+and a repo names the sinks it wants under ``events.sinks`` in
+``.repowise/config.yaml``. Event ids are stable, so a consumer dedupes a
+re-delivered event by ``id``; a webhook sink signs with Standard Webhooks.
+"""
+
+from __future__ import annotations
+
+import json
+import sys
+from collections.abc import Sequence
+from pathlib import Path
+from typing import Protocol
+
+from repowise.core.registry.plugins import SeamRegistry
+
+from .model import EngineEvent, to_cloudevent
+
+EVENTS_FILE = "events.jsonl"
+
+
+class EventSink(Protocol):
+ async def deliver(self, events: Sequence[EngineEvent], *, repo_root: Path) -> None:
+ """Deliver *events*, at least once; raising leaves them in the store only."""
+ ...
+
+
+def _lines(events: Sequence[EngineEvent]) -> str:
+ return "".join(json.dumps(to_cloudevent(e), sort_keys=True) + "\n" for e in events)
+
+
+class JsonlSink:
+ """Appends to one local file. Ceiling: the file is never rotated or trimmed
+ (retention applies to the store only); a consumer that needs a bounded file
+ truncates it after reading, or reads the pull API instead."""
+
+ async def deliver(self, events: Sequence[EngineEvent], *, repo_root: Path) -> None:
+ path = Path(repo_root) / ".repowise" / EVENTS_FILE
+ path.parent.mkdir(parents=True, exist_ok=True)
+ with path.open("a", encoding="utf-8", newline="\n") as fh:
+ fh.write(_lines(events))
+
+
+class StdoutSink:
+ async def deliver(self, events: Sequence[EngineEvent], *, repo_root: Path) -> None:
+ sys.stdout.write(_lines(events))
+ sys.stdout.flush()
+
+
+event_sinks: SeamRegistry[EventSink] = SeamRegistry("event-sink")
+event_sinks.register("jsonl", JsonlSink(), default=True)
+event_sinks.register("stdout", StdoutSink())
+
+
+__all__ = ["EVENTS_FILE", "EventSink", "JsonlSink", "StdoutSink", "event_sinks"]
diff --git a/packages/core/src/repowise/core/events/snapshot.py b/packages/core/src/repowise/core/events/snapshot.py
new file mode 100644
index 000000000..85ab5489a
--- /dev/null
+++ b/packages/core/src/repowise/core/events/snapshot.py
@@ -0,0 +1,341 @@
+"""Component facts for one index run, read from the stores that run left behind.
+
+The figures reuse the component rollups (:func:`component_rollups`) and add
+what a diff needs on top: the full hotspot set, observed ownership as opaque
+digests, governing decisions with their staleness, the provided contract set,
+and the agent share of recent commits with its coverage. Nothing here names a
+person: owners are counted, and the main-owner set is kept only as HMAC digests
+under a per-repository random key (``.repowise/events.key``), which is all a
+set comparison between two runs needs. A digest cannot be checked against a
+guessed email without the key. A declared owner is named only when it is a
+group ref.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import hmac
+import json
+import logging
+import secrets
+from collections import Counter
+from datetime import timedelta
+from pathlib import Path
+from typing import Any
+
+from sqlalchemy import func, select
+
+logger = logging.getLogger(__name__)
+
+#: Bumped when a fact's definition changes; part of the stamp.
+SNAPSHOT_FACTS_VERSION = 1
+#: Window for "recent" activity and attribution, back from the newest indexed commit.
+RECENT_DAYS = 90
+#: A governing decision at or above this staleness counts as stale
+#: (the threshold ``get_stale_decisions`` uses).
+STALE_THRESHOLD = 0.5
+#: Ceiling on ``(file, commit)`` rows read for the recent window, newest first.
+#: Past it the window is partial and says so (``recent_capped``); the rules
+#: that read recent activity skip it. Upgrade path: aggregate per component in SQL.
+MAX_RECENT_ROWS = 200_000
+#: Per-repository key the owner digests are made with.
+OWNER_KEY_FILE = "events.key"
+
+
+def current_stamp() -> str:
+ """The analyzer and parser versions facts are computed under, as one string."""
+ from repowise.core.analysis.health.engine import HEALTH_ANALYZER_VERSION
+ from repowise.core.ingestion.git_indexer._constants import GIT_HISTORY_VERSION
+ from repowise.core.upgrade.version import PARSER_SCHEMA_VERSION
+ from repowise.core.workspace.contracts import CONTRACTS_VERSION
+
+ return (
+ f"h{HEALTH_ANALYZER_VERSION}.p{PARSER_SCHEMA_VERSION}.g{GIT_HISTORY_VERSION}"
+ f".c{CONTRACTS_VERSION}.s{SNAPSHOT_FACTS_VERSION}"
+ )
+
+
+def _digest(text: str) -> str:
+ return hashlib.sha256(text.encode("utf-8")).hexdigest()[:12]
+
+
+def owner_key(repo_root: Path) -> bytes | None:
+ """The repository's digest key, made on first use; ``None`` when it cannot
+ be read or written. A new key gets a new id, so the next diff of owner
+ sets is skipped rather than reading every owner as replaced."""
+ from repowise.core.repo_config import write_private_file
+
+ path = Path(repo_root) / ".repowise" / OWNER_KEY_FILE
+ try:
+ if path.is_file():
+ key = bytes.fromhex(path.read_text(encoding="ascii").strip())
+ if len(key) >= 16:
+ return key
+ key = secrets.token_bytes(32)
+ write_private_file(
+ repo_root, OWNER_KEY_FILE, key.hex(), comment="repowise owner-digest key (local)"
+ )
+ return key
+ except (OSError, ValueError) as exc:
+ logger.warning("owner-digest key unavailable, owner sets not kept: %s", exc)
+ return None
+
+
+def _keyed(key: bytes, text: str) -> str:
+ return hmac.new(key, text.encode("utf-8"), hashlib.sha256).hexdigest()[:16]
+
+
+async def collect_facts(
+ session: Any,
+ repository_id: str,
+ repo_root: Path,
+ *,
+ head_commit: str | None,
+ attribution: bool,
+) -> dict[str, dict[str, Any]]:
+ """Facts per component name for the repository's current index."""
+ from repowise.core.components.store import (
+ component_rollups,
+ load_repo_components,
+ workspace_services,
+ )
+
+ found = await load_repo_components(
+ session, repository_id, repo_root, services=workspace_services(repo_root)
+ )
+ files = {name: paths for name, paths in found.resolved.files.items() if paths}
+ if not files:
+ return {}
+ rollups = await component_rollups(session, repository_id, files, found.test_files)
+ git_rows = await _git_rows(session, repository_id)
+ recent = await _recent_commit_files(session, repository_id)
+ capped = len(recent) >= MAX_RECENT_ROWS
+ key = owner_key(repo_root)
+ key_id = _digest(key.hex()) if key else None
+ governing, stale = await _decisions(session, repository_id)
+ contracts = _provided_contracts(repo_root, head_commit)
+
+ from repowise.core.analysis.owners import people_resolver
+ from repowise.core.components.catalog import owner_group_name
+
+ resolve = people_resolver(git_rows.values(), recent)
+ recent_by_file: dict[str, list[dict[str, Any]]] = {}
+ for row in recent:
+ recent_by_file.setdefault(row["file_path"], []).append(row)
+
+ out: dict[str, dict[str, Any]] = {}
+ for comp in found.resolved.components:
+ paths = files.get(comp.name)
+ if not paths:
+ continue
+ rolled = rollups.get(comp.name, {})
+ commits = {r["sha"]: r for p in paths for r in recent_by_file.get(p, ())}
+ facts: dict[str, Any] = {
+ "definition": _digest(json.dumps([sorted(comp.paths), comp.root, comp.source])),
+ "criticality": comp.criticality,
+ "tags": sorted(comp.tags),
+ # Named only as a group; any other owner ref is compared by digest.
+ "declared_owner": owner_group_name(comp.owner),
+ "declared_owner_key": _keyed(key, comp.owner) if key and comp.owner else None,
+ "key_id": key_id,
+ "file_count": len(paths),
+ "health": rolled.get("health"),
+ "bus_factor": rolled.get("bus_factor"),
+ "test_reach": rolled.get("test_reach"),
+ "dead_code": rolled.get("dead_code"),
+ "hotspots": sorted(p for p in paths if git_rows.get(p, {}).get("is_hotspot")),
+ "ownership": _ownership(paths, git_rows, commits.values(), resolve, key, capped),
+ "decisions": _component_decisions(paths, governing, stale),
+ "contracts": _component_contracts(paths, contracts),
+ }
+ if attribution:
+ facts["attribution"] = _attribution(commits.values(), capped)
+ out[comp.name] = facts
+ return out
+
+
+async def _git_rows(session: Any, repository_id: str) -> dict[str, dict[str, Any]]:
+ from repowise.core.persistence.crud import code_file_rows
+ from repowise.core.persistence.models import GitMetadata
+
+ rows = await session.execute(
+ select(
+ GitMetadata.file_path,
+ GitMetadata.is_hotspot,
+ GitMetadata.primary_owner_name,
+ GitMetadata.primary_owner_email,
+ GitMetadata.top_authors_json,
+ ).where(code_file_rows(repository_id))
+ )
+ return {r.file_path: dict(r._mapping) for r in rows}
+
+
+async def _recent_commit_files(session: Any, repository_id: str) -> list[dict[str, Any]]:
+ """``(file, commit)`` rows of the window before the newest indexed commit.
+
+ Anchored on that commit, not the clock, so a snapshot of an old checkout
+ reads the activity around it.
+ """
+ from repowise.core.persistence.models import GitCommit, GitCommitFile
+
+ newest = await session.scalar(
+ select(func.max(GitCommit.committed_at)).where(GitCommit.repository_id == repository_id)
+ )
+ if newest is None:
+ return []
+ rows = await session.execute(
+ select(
+ GitCommitFile.file_path,
+ GitCommit.sha,
+ GitCommit.author_name,
+ GitCommit.author_email,
+ GitCommit.attribution,
+ GitCommit.agent_name,
+ )
+ .join(
+ GitCommit,
+ (GitCommit.repository_id == GitCommitFile.repository_id)
+ & (GitCommit.sha == GitCommitFile.sha),
+ )
+ .where(
+ GitCommitFile.repository_id == repository_id,
+ GitCommit.committed_at >= newest - timedelta(days=RECENT_DAYS),
+ )
+ .order_by(GitCommit.committed_at.desc())
+ .limit(MAX_RECENT_ROWS)
+ )
+ return [dict(r._mapping) for r in rows]
+
+
+async def _decisions(
+ session: Any, repository_id: str
+) -> tuple[dict[str, list[tuple[str, str]]], set[str]]:
+ from repowise.core.persistence.crud.authority import governing_decisions_by_file
+ from repowise.core.persistence.models import DecisionRecord
+
+ governing = await governing_decisions_by_file(session, repository_id)
+ ids = {d for pairs in governing.values() for d, _ in pairs}
+ if not ids:
+ return governing, set()
+ stale = await session.scalars(
+ select(DecisionRecord.id).where(
+ DecisionRecord.repository_id == repository_id,
+ DecisionRecord.id.in_(sorted(ids)),
+ DecisionRecord.staleness_score >= STALE_THRESHOLD,
+ )
+ )
+ return governing, set(stale)
+
+
+def _provided_contracts(repo_root: Path, head_commit: str | None) -> dict[str, dict[str, int]] | None:
+ """``{file: {contract_id: consumer links}}`` for this repo's provided contracts.
+
+ ``None`` outside a workspace, or when the workspace's contracts were not
+ extracted at this repo's current commit: an older extraction would read as
+ contracts appearing and disappearing.
+ """
+ from repowise.core.workspace.config import WorkspaceConfig, find_workspace_root
+ from repowise.core.workspace.contracts import load_contract_store
+
+ ws_root = find_workspace_root(repo_root)
+ if ws_root is None or not head_commit:
+ return None
+ try:
+ config = WorkspaceConfig.load(ws_root)
+ except Exception:
+ return None
+ root = repo_root.resolve()
+ alias = next((r.alias for r in config.repos if (ws_root / r.path).resolve() == root), None)
+ store = load_contract_store(ws_root) if alias else None
+ if store is None or store.repo_provenance.get(alias, {}).get("head") != head_commit:
+ return None
+ consumers = Counter(
+ (lk.provider_file, lk.contract_id)
+ for lk in store.contract_links
+ if lk.provider_repo == alias and lk.consumer_repo != alias
+ )
+ out: dict[str, dict[str, int]] = {}
+ for c in store.rows_for_repo(alias):
+ if c.role == "provider":
+ out.setdefault(c.file_path, {})[c.contract_id] = consumers[(c.file_path, c.contract_id)]
+ return out
+
+
+def _ownership(
+ paths: list[str],
+ git_rows: dict[str, dict[str, Any]],
+ commits: Any,
+ resolve: Any,
+ key: bytes | None,
+ capped: bool,
+) -> dict[str, Any]:
+ """Observed ownership as counts and opaque digests of the main owners.
+
+ Main owners are the fewest primary owners who together own over half the
+ owned files (the bus-factor set). Digests let two runs compare the set
+ without storing who is in it.
+ """
+ owners: Counter[str] = Counter()
+ for p in paths:
+ row = git_rows.get(p)
+ 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
+ owned = sum(owners.values())
+ main: list[str] = []
+ held = 0
+ for key, count in sorted(owners.items(), key=lambda kv: (-kv[1], kv[0])):
+ if held * 2 > owned:
+ break
+ main.append(key)
+ held += count
+ recent_authors = {resolve(c["author_name"], c["author_email"]) for c in commits}
+ return {
+ "owned_files": owned,
+ "owner_count": len(owners),
+ # Without a key there is nothing safe to compare, so no set is kept.
+ "main_owners": sorted(_keyed(key, k) for k in main) if key else None,
+ "active_main_owners": sum(1 for k in main if k in recent_authors),
+ "recent_commits": len({c["sha"] for c in commits}),
+ "recent_capped": capped,
+ "window_days": RECENT_DAYS,
+ }
+
+
+def _component_decisions(
+ paths: list[str], governing: dict[str, list[tuple[str, str]]], stale: set[str]
+) -> dict[str, Any]:
+ ids = sorted({d for p in paths for d, _ in governing.get(p, ())})
+ return {"governing": len(ids), "stale": [d for d in ids if d in stale]}
+
+
+def _component_contracts(
+ paths: list[str], contracts: dict[str, dict[str, int]] | None
+) -> dict[str, Any]:
+ if contracts is None:
+ return {"basis": "unavailable"}
+ provided: dict[str, int] = {}
+ for p in paths:
+ for cid, n in contracts.get(p, {}).items():
+ provided[cid] = provided.get(cid, 0) + n
+ return {"basis": "measured", "provided": dict(sorted(provided.items()))}
+
+
+def _attribution(commits: Any, capped: bool) -> dict[str, Any]:
+ from repowise.core.attribution import AGENT, HUMAN_ATTESTED, attribution_share, commit_label
+
+ labels = Counter(commit_label(c["attribution"], c["agent_name"]) for c in commits)
+ share = attribution_share(labels[AGENT], labels[HUMAN_ATTESTED], sum(labels.values()))
+ return {
+ "window_days": RECENT_DAYS,
+ "commits": share.total,
+ "agent": share.agent,
+ "human_attested": share.human_attested,
+ "coverage": None if share.coverage is None else round(share.coverage, 3),
+ "agent_share": None if share.agent_share is None else round(share.agent_share, 3),
+ "suppressed_reason": share.suppressed_reason,
+ "recent_capped": capped,
+ }
diff --git a/packages/core/src/repowise/core/events/store.py b/packages/core/src/repowise/core/events/store.py
new file mode 100644
index 000000000..90f1dbd7a
--- /dev/null
+++ b/packages/core/src/repowise/core/events/store.py
@@ -0,0 +1,416 @@
+"""Record a run's snapshot, diff it into events, keep history bounded, read events.
+
+:func:`record_snapshot` runs once per index run, after every store is final.
+It snapshots the components, and when the newest stored run is the index run
+just before this one and carries the same stamp, it stores the typed
+occurrences between the two and hands them to the configured sinks. A stamp
+change (a new analyzer, parser, git-history or contract-extraction version)
+starts a fresh baseline instead: figures computed under different rules are
+not comparable, so their difference is not an event.
+
+An index run that takes no snapshot (events switched off, or the snapshot
+failed) leaves a gap marker, so the next snapshot is a baseline rather than a
+diff across runs nobody saw.
+
+Settings, under ``events:`` in ``.repowise/config.yaml``::
+
+ events:
+ enabled: true # snapshots and events at all
+ retention_days: 365 # runs and events older than this are dropped
+ compact_after_days: 30 # older runs keep one per ISO week
+ kinds: {new_hotspot: true}
+ sinks: [jsonl, stdout] # names in the event-sink seam
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+from collections.abc import Iterable, Sequence
+from dataclasses import dataclass
+from datetime import UTC, datetime, timedelta
+from pathlib import Path
+from typing import Any
+
+from sqlalchemy import delete, select
+
+from .diff import diff_snapshots
+from .model import EVENT_SCHEMA_VERSION, KINDS, EngineEvent, event_id, severity_for
+
+logger = logging.getLogger(__name__)
+
+#: Stamp prefix of a gap marker: an index run with no snapshot.
+GAP_STAMP = "gap:"
+
+
+@dataclass(frozen=True)
+class EventSettings:
+ enabled: bool = True
+ retention_days: int = 365
+ compact_after_days: int = 30
+ kinds: frozenset[str] = frozenset(k.name for k in KINDS.values() if k.default_on)
+ sinks: tuple[str, ...] = ()
+ #: What was wrong in the block; each wrong value kept its default.
+ errors: tuple[str, ...] = ()
+
+
+_KEYS = frozenset({"enabled", "retention_days", "compact_after_days", "kinds", "sinks"})
+
+
+def load_event_settings(repo_root: Path | str) -> EventSettings:
+ """The repo's ``events:`` settings; a missing or invalid value keeps its
+ default and is named in ``errors``."""
+ from repowise.core.repo_config import load_repo_config
+
+ try:
+ raw = load_repo_config(repo_root).get("events")
+ except Exception:
+ raw = None
+ if raw is None:
+ return EventSettings()
+ if not isinstance(raw, dict):
+ return EventSettings(errors=("events: expected a mapping",))
+ base = EventSettings()
+ errors = [f"events.{k}: unknown key" for k in sorted(set(raw) - _KEYS, key=str)]
+ enabled = raw.get("enabled", True)
+ if not isinstance(enabled, bool):
+ errors.append("events.enabled: expected true or false")
+ enabled = True
+ kinds = set(base.kinds)
+ raw_kinds = raw.get("kinds") or {}
+ if not isinstance(raw_kinds, dict):
+ errors.append("events.kinds: expected a mapping of kind to true or false")
+ raw_kinds = {}
+ for name, on in raw_kinds.items():
+ if name not in KINDS:
+ errors.append(f"events.kinds.{name}: unknown kind; known: {', '.join(sorted(KINDS))}")
+ elif not isinstance(on, bool):
+ errors.append(f"events.kinds.{name}: expected true or false")
+ else:
+ (kinds.add if on else kinds.discard)(name)
+ sinks = raw.get("sinks")
+ if sinks is not None and not isinstance(sinks, list):
+ errors.append("events.sinks: expected a list of sink names")
+ return EventSettings(
+ enabled=enabled,
+ retention_days=_positive(raw, "retention_days", base.retention_days, errors),
+ compact_after_days=_positive(raw, "compact_after_days", base.compact_after_days, errors),
+ kinds=frozenset(kinds),
+ sinks=tuple(str(s) for s in sinks) if isinstance(sinks, list) else (),
+ errors=tuple(errors),
+ )
+
+
+def _positive(raw: dict, key: str, default: int, errors: list[str]) -> int:
+ value = raw.get(key)
+ if value is None:
+ return default
+ if isinstance(value, int) and not isinstance(value, bool) and value > 0:
+ return value
+ errors.append(f"events.{key}: expected a positive whole number of days")
+ return default
+
+
+def _aware(value: datetime) -> datetime:
+ return value if value.tzinfo else value.replace(tzinfo=UTC)
+
+
+def _public_url(url: str | None) -> str:
+ """*url* without credentials, so a token in a remote URL never leaves."""
+ from urllib.parse import urlsplit, urlunsplit
+
+ if not url:
+ return ""
+ try:
+ parts = urlsplit(url)
+ except ValueError:
+ return ""
+ if "@" in parts.netloc:
+ parts = parts._replace(netloc=parts.netloc.rsplit("@", 1)[1])
+ return urlunsplit(parts)
+
+
+async def record_snapshot(
+ session: Any, repository_id: str, *, now: datetime | None = None
+) -> list[EngineEvent]:
+ """Snapshot the repository's components and return the events stored for it.
+
+ A run at the commit and stamp of the newest run is skipped (an update that
+ found nothing to do, or ``--working-tree`` on the same commit: uncommitted
+ work is not history).
+
+ Ceiling: sinks are called before the caller commits, because this runs
+ inside the index run's session. An event id is keyed on the previous run,
+ so a retry after a failed commit re-delivers the same id and a consumer
+ dedupes on it. Upgrade path: a per-sink cursor read after commit.
+ """
+ from repowise.core.attribution import attribution_enabled
+ from repowise.core.persistence.models import ComponentSnapshot, Repository, SnapshotRun
+
+ from .snapshot import collect_facts, current_stamp
+
+ repo = await session.get(Repository, repository_id)
+ if repo is None or not repo.local_path:
+ return []
+ root = Path(repo.local_path)
+ settings = load_event_settings(root)
+ for error in settings.errors:
+ logger.warning("%s (kept the default)", error)
+ if not settings.enabled:
+ await record_gap(session, repository_id, "disabled", now=now)
+ return []
+ stamp = current_stamp()
+ head = repo.head_commit
+ previous = await _newest_run(session, repository_id)
+ if previous is not None and head and previous.commit_sha == head and previous.stamp == stamp:
+ return []
+
+ facts = await collect_facts(
+ session, repository_id, root, head_commit=head, attribution=attribution_enabled(root)
+ )
+ taken_at = now or datetime.now(UTC)
+ run = SnapshotRun(repository_id=repository_id, taken_at=taken_at, commit_sha=head, stamp=stamp)
+ session.add(run)
+ await session.flush()
+ session.add_all(
+ ComponentSnapshot(run_id=run.id, component=name, facts_json=json.dumps(f, sort_keys=True))
+ for name, f in facts.items()
+ )
+
+ events: list[EngineEvent] = []
+ # A gap marker's stamp never equals a real one, so a run after it is a baseline.
+ if previous is not None and previous.stamp == stamp:
+ before = await _run_facts(session, previous.id)
+ events = await _store_events(
+ session, repo, run, previous, before, facts, settings, taken_at
+ )
+ await compact(session, repository_id, settings, now=taken_at)
+ await session.flush()
+ if events:
+ await _deliver(events, settings, root)
+ return events
+
+
+async def _newest_run(session: Any, repository_id: str) -> Any:
+ from repowise.core.persistence.models import SnapshotRun
+
+ return await session.scalar(
+ select(SnapshotRun)
+ .where(SnapshotRun.repository_id == repository_id)
+ .order_by(SnapshotRun.taken_at.desc(), SnapshotRun.id.desc())
+ .limit(1)
+ )
+
+
+async def record_gap(
+ session: Any, repository_id: str, reason: str, *, now: datetime | None = None
+) -> None:
+ """Mark an index run that took no snapshot, so the next one is a baseline."""
+ from repowise.core.persistence.models import SnapshotRun
+
+ newest = await _newest_run(session, repository_id)
+ if newest is None or newest.stamp.startswith(GAP_STAMP):
+ return # nothing to diff against yet, or the gap is already marked
+ session.add(
+ SnapshotRun(
+ repository_id=repository_id,
+ taken_at=now or datetime.now(UTC),
+ commit_sha=None,
+ stamp=f"{GAP_STAMP}{reason}"[:64],
+ )
+ )
+ await session.flush()
+
+
+async def _run_facts(session: Any, run_id: str) -> dict[str, dict[str, Any]]:
+ from repowise.core.persistence.models import ComponentSnapshot
+
+ rows = await session.execute(
+ select(ComponentSnapshot.component, ComponentSnapshot.facts_json).where(
+ ComponentSnapshot.run_id == run_id
+ )
+ )
+ return {name: json.loads(raw) for name, raw in rows}
+
+
+async def _store_events(
+ session: Any,
+ repo: Any,
+ run: Any,
+ previous: Any,
+ before: dict[str, dict[str, Any]],
+ after: dict[str, dict[str, Any]],
+ settings: EventSettings,
+ taken_at: datetime,
+) -> list[EngineEvent]:
+ from repowise.core.persistence.models import Change, EngineEventRecord
+
+ occurrences = [o for o in diff_snapshots(before, after) if o[0] in settings.kinds]
+ if not occurrences:
+ return []
+ url = _public_url(repo.url)
+ vcs: dict[str, Any] = {}
+ if url:
+ vcs["vcs.repository.url.full"] = url
+ if run.commit_sha:
+ change_id = await session.scalar(
+ select(Change.change_id).where(
+ Change.repository_id == repo.id, Change.head_sha == run.commit_sha
+ )
+ )
+ if change_id:
+ vcs["vcs.change.id"] = change_id
+ events = [
+ EngineEvent(
+ # Keyed on the previous run, not only the commits: a pair seen
+ # again (A to B, back to A, to B) or a run with no commit is a new
+ # occurrence, while a retry of the same run keeps its id.
+ id=event_id(
+ repo.id, previous.id, previous.commit_sha, run.commit_sha, kind, component, subject
+ ),
+ kind=kind,
+ repo_id=repo.id,
+ component=component,
+ severity=severity_for(after[component].get("criticality")),
+ occurred_at=taken_at,
+ evidence=evidence,
+ stamp=run.stamp,
+ commit_sha=run.commit_sha,
+ base_commit_sha=previous.commit_sha,
+ source=url,
+ vcs=vcs,
+ )
+ for kind, component, subject, evidence in occurrences
+ ]
+ seen = set(
+ await session.scalars(
+ select(EngineEventRecord.id).where(EngineEventRecord.id.in_([e.id for e in events]))
+ )
+ )
+ events = [e for e in events if e.id not in seen]
+ session.add_all(
+ EngineEventRecord(
+ id=e.id,
+ repository_id=e.repo_id,
+ kind=e.kind,
+ component=e.component,
+ severity=e.severity,
+ occurred_at=e.occurred_at,
+ commit_sha=e.commit_sha,
+ base_commit_sha=e.base_commit_sha,
+ stamp=e.stamp,
+ payload_json=json.dumps(
+ {"evidence": dict(e.evidence), "vcs": dict(e.vcs), "source": e.source},
+ sort_keys=True,
+ ),
+ schema_version=e.schema,
+ )
+ for e in events
+ )
+ return events
+
+
+async def _deliver(events: Sequence[EngineEvent], settings: EventSettings, root: Path) -> None:
+ from .sinks import event_sinks
+
+ for name in settings.sinks or (event_sinks.default or "jsonl",):
+ try:
+ await event_sinks.get(name).deliver(events, repo_root=root)
+ except Exception as exc: # the store keeps them; `repowise events` replays
+ logger.warning("event sink %s failed: %s", name, exc)
+
+
+async def compact(
+ session: Any, repository_id: str, settings: EventSettings, *, now: datetime
+) -> None:
+ """Drop runs and events past retention; keep one run per ISO week past
+ ``compact_after_days``, and no gap markers there. The newest run is always
+ kept: the next diff reads it."""
+ from repowise.core.persistence.models import ComponentSnapshot, EngineEventRecord, SnapshotRun
+
+ now = _aware(now)
+ drop_before = now - timedelta(days=settings.retention_days)
+ weekly_before = now - timedelta(days=settings.compact_after_days)
+ newest = await _newest_run(session, repository_id)
+ runs = (
+ await session.execute(
+ select(SnapshotRun.id, SnapshotRun.taken_at, SnapshotRun.stamp)
+ .where(
+ SnapshotRun.repository_id == repository_id,
+ SnapshotRun.taken_at < weekly_before,
+ )
+ .order_by(SnapshotRun.taken_at.desc(), SnapshotRun.id.desc())
+ )
+ ).all()
+ doomed: list[str] = []
+ kept_weeks: dict[tuple[int, int], str] = {}
+ for run_id, taken_at, stamp in runs:
+ if newest is not None and run_id == newest.id:
+ continue
+ taken_at = _aware(taken_at)
+ week = taken_at.isocalendar()[:2]
+ if taken_at < drop_before or stamp.startswith(GAP_STAMP) or week in kept_weeks:
+ doomed.append(run_id)
+ else:
+ kept_weeks[week] = run_id # newest first, so the week's last run
+ if kept_weeks:
+ await _mark_compacted(session, kept_weeks.values())
+ for i in range(0, len(doomed), 500):
+ chunk = doomed[i : i + 500]
+ await session.execute(delete(ComponentSnapshot).where(ComponentSnapshot.run_id.in_(chunk)))
+ await session.execute(delete(SnapshotRun).where(SnapshotRun.id.in_(chunk)))
+ await session.execute(
+ delete(EngineEventRecord).where(
+ EngineEventRecord.repository_id == repository_id,
+ EngineEventRecord.occurred_at < drop_before,
+ )
+ )
+
+
+async def _mark_compacted(session: Any, run_ids: Iterable[str]) -> None:
+ from sqlalchemy import update
+
+ from repowise.core.persistence.models import SnapshotRun
+
+ await session.execute(
+ update(SnapshotRun).where(SnapshotRun.id.in_(list(run_ids))).values(compacted=True)
+ )
+
+
+def event_from_row(row: Any) -> EngineEvent:
+ payload = json.loads(row.payload_json or "{}")
+ return EngineEvent(
+ id=row.id,
+ kind=row.kind,
+ repo_id=row.repository_id,
+ component=row.component,
+ severity=row.severity,
+ occurred_at=_aware(row.occurred_at),
+ evidence=payload.get("evidence") or {},
+ stamp=row.stamp,
+ commit_sha=row.commit_sha,
+ base_commit_sha=row.base_commit_sha,
+ source=payload.get("source") or "",
+ vcs=payload.get("vcs") or {},
+ schema=row.schema_version or EVENT_SCHEMA_VERSION,
+ )
+
+
+async def list_events(
+ session: Any,
+ repository_id: str,
+ *,
+ since: datetime | None = None,
+ kinds: Sequence[str] = (),
+ limit: int = 200,
+) -> list[EngineEvent]:
+ """Stored events, oldest first, from *since* on."""
+ from repowise.core.persistence.models import EngineEventRecord
+
+ query = select(EngineEventRecord).where(EngineEventRecord.repository_id == repository_id)
+ if since is not None:
+ query = query.where(EngineEventRecord.occurred_at >= since)
+ if kinds:
+ query = query.where(EngineEventRecord.kind.in_(list(kinds)))
+ query = query.order_by(EngineEventRecord.occurred_at, EngineEventRecord.id).limit(limit)
+ return [event_from_row(r) for r in await session.scalars(query)]
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/actions.py b/packages/core/src/repowise/core/persistence/crud/analysis/actions.py
index 5ae13a6bb..1a500b1c8 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/actions.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/actions.py
@@ -508,7 +508,8 @@ async def write_actions_snapshot(session: AsyncSession, repo_id: str) -> bool:
async def write_read_snapshots(session: AsyncSession, repo_id: str) -> None:
- """Store the Fix first queue, then the actions view that quotes its head.
+ """Store the Fix first queue, then the actions view that quotes its head,
+ then the run's component snapshot (:mod:`repowise.core.events`).
For a writer whose stores are final for this run, on the session that
wrote them or a later one. Best-effort, each in its own savepoint: a view
@@ -529,6 +530,21 @@ async def write_read_snapshots(session: AsyncSession, repo_id: str) -> None:
# kind that failed may have left an older row, which the commit drops.
if written:
await mark_current(session)
+ # The run's component snapshot and its events read the same final stores.
+ try:
+ from repowise.core.events.store import record_snapshot
+
+ async with session.begin_nested():
+ await record_snapshot(session, repo_id)
+ except Exception as exc: # history skips a run; the index is unaffected
+ logger.warning("component snapshot not written: %s", exc)
+ try: # so the next snapshot is a baseline, not a diff across the gap
+ from repowise.core.events.store import record_gap
+
+ async with session.begin_nested():
+ await record_gap(session, repo_id, "failed")
+ except Exception as gap_exc:
+ logger.warning("component snapshot gap not recorded: %s", gap_exc)
def _view(ruled: dict[str, Any], states: dict[str, ActionStateRecord], now: datetime) -> dict:
diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.py
index 4503c5153..4bac8c82c 100644
--- a/packages/core/src/repowise/core/persistence/models.py
+++ b/packages/core/src/repowise/core/persistence/models.py
@@ -2508,6 +2508,69 @@ class HealthSnapshot(Base):
doc_drift_count: Mapped[int | None] = mapped_column(Integer, nullable=True)
+class SnapshotRun(Base):
+ """One index run's component snapshot (see :mod:`repowise.core.events`).
+
+ ``stamp`` joins the analyzer and parser versions the facts were computed
+ under; a run is only diffed against a predecessor with the same stamp.
+ ``compacted`` marks a run kept as its week's representative.
+ """
+
+ __tablename__ = "snapshot_runs"
+ __table_args__ = (Index("ix_snapshot_runs_repo_taken", "repository_id", "taken_at"),)
+
+ id: Mapped[str] = mapped_column(String(32), primary_key=True, default=_new_uuid)
+ repository_id: Mapped[str] = mapped_column(
+ String(32), ForeignKey("repositories.id", ondelete="CASCADE"), nullable=False
+ )
+ taken_at: Mapped[datetime] = mapped_column(
+ DateTime(timezone=True), nullable=False, default=_now_utc
+ )
+ commit_sha: Mapped[str | None] = mapped_column(String(40), nullable=True)
+ stamp: Mapped[str] = mapped_column(String(64), nullable=False)
+ compacted: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
+
+
+class ComponentSnapshot(Base):
+ """One component's facts at one :class:`SnapshotRun`, as versioned JSON."""
+
+ __tablename__ = "component_snapshots"
+ __table_args__ = (UniqueConstraint("run_id", "component", name="uq_component_snapshot"),)
+
+ id: Mapped[str] = mapped_column(String(32), primary_key=True, default=_new_uuid)
+ run_id: Mapped[str] = mapped_column(
+ String(32), ForeignKey("snapshot_runs.id", ondelete="CASCADE"), nullable=False
+ )
+ component: Mapped[str] = mapped_column(String(255), nullable=False)
+ facts_json: Mapped[str] = mapped_column(Text, nullable=False, default="{}")
+
+
+class EngineEventRecord(Base):
+ """A typed event from two consecutive same-stamp snapshot runs.
+
+ ``id`` is derived from the commit pair, kind, component and subject, so a
+ re-delivered event keeps its id. Events outlive the runs they came from.
+ """
+
+ __tablename__ = "events"
+ __table_args__ = (Index("ix_events_repo_occurred", "repository_id", "occurred_at"),)
+
+ id: Mapped[str] = mapped_column(String(32), primary_key=True)
+ repository_id: Mapped[str] = mapped_column(
+ String(32), ForeignKey("repositories.id", ondelete="CASCADE"), nullable=False
+ )
+ kind: Mapped[str] = mapped_column(String(32), nullable=False)
+ component: Mapped[str | None] = mapped_column(String(255), nullable=True)
+ severity: Mapped[str] = mapped_column(String(16), nullable=False)
+ occurred_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
+ commit_sha: Mapped[str | None] = mapped_column(String(40), nullable=True)
+ base_commit_sha: Mapped[str | None] = mapped_column(String(40), nullable=True)
+ stamp: Mapped[str] = mapped_column(String(64), nullable=False)
+ # {"evidence", "vcs", "source"}: what the wire form needs beyond the columns.
+ payload_json: Mapped[str] = mapped_column(Text, nullable=False, default="{}")
+ schema_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1)
+
+
class CoverageFile(Base):
"""Per-file coverage data, overwritten on each --coverage run."""
diff --git a/packages/core/src/repowise/core/persistence/read_snapshots.py b/packages/core/src/repowise/core/persistence/read_snapshots.py
index d4e64c953..8de2e80d8 100644
--- a/packages/core/src/repowise/core/persistence/read_snapshots.py
+++ b/packages/core/src/repowise/core/persistence/read_snapshots.py
@@ -54,8 +54,10 @@ UNRELATED_TABLES = frozenset(
"action_states",
"answer_cache",
"chat_messages",
+ "component_snapshots",
"conversations",
"doc_drift_references",
+ "events",
"external_systems",
"generation_jobs",
"git_commit_health_deltas",
@@ -71,6 +73,7 @@ UNRELATED_TABLES = frozenset(
"read_snapshots",
"refactoring_summaries",
"repositories",
+ "snapshot_runs",
"webhook_events",
"wiki_page_versions",
"wiki_pages",
diff --git a/packages/core/src/repowise/core/repo_config.py b/packages/core/src/repowise/core/repo_config.py
index 68f24399d..e90bfd598 100644
--- a/packages/core/src/repowise/core/repo_config.py
+++ b/packages/core/src/repowise/core/repo_config.py
@@ -40,7 +40,7 @@ CONFIG_DEPENDENCY_KEYS: dict[str, frozenset[str]] = {
# Agent-surface preferences. init records `hooks` and `editor_files` after
# it fingerprints the config, so leaving them in "other" turned the first
# update after every init into a full rebuild.
- "state_only": frozenset({"distill", "editor_files", "hooks", "mcp"}),
+ "state_only": frozenset({"distill", "editor_files", "events", "hooks", "mcp"}),
}
@@ -338,23 +338,39 @@ def save_repo_env_key(
elif not found:
existing_lines.append(f"{env_var}={value}")
- # Ignore rule first, secret second. If the .gitignore write fails (a
- # read-only checkout, a root-owned file) this raises before the key is on
- # disk, rather than after. The failure then costs the user a saved key
- # instead of leaving a committable one behind.
- if ensure_gitignored and value is not None:
- _ensure_env_gitignored(repo_path)
-
- env_dir.mkdir(parents=True, exist_ok=True)
- env_file.write_text("\n".join(existing_lines) + "\n", encoding="utf-8")
- # The file holds API keys; keep it owner-only where the OS honours it
- # (best-effort: a no-op on Windows).
+ write_private_file(
+ repo_path,
+ ".env",
+ "\n".join(existing_lines) + "\n",
+ comment="repowise API keys (local)",
+ ignore=ensure_gitignored and value is not None,
+ )
+
+
+def write_private_file(
+ repo_path: Path | str, name: str, text: str, *, comment: str, ignore: bool = True
+) -> Path:
+ """Write a secret ``.repowise/<name>``: git-ignored first, owner-only after.
+
+ Some repositories commit ``.repowise/`` for its shared config, so a secret
+ there needs its own ignore rule. Ignore rule first, secret second: if the
+ .gitignore write fails (a read-only checkout, a root-owned file) this
+ raises before the secret is on disk rather than after, which costs the
+ caller a saved secret instead of leaving a committable one behind.
+ """
+ if ignore:
+ _ensure_gitignored(repo_path, f".repowise/{name}", comment)
+ path = get_repowise_dir(repo_path) / name
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(text, encoding="utf-8")
+ # Owner-only where the OS honours it (best-effort: a no-op on Windows).
try:
import os
- os.chmod(env_file, 0o600)
+ os.chmod(path, 0o600)
except OSError:
pass
+ return path
def ensure_manifest_tracked(repo_path: Path | str) -> bool:
@@ -399,10 +415,9 @@ def ensure_manifest_tracked(repo_path: Path | str) -> bool:
return True
-def _ensure_env_gitignored(repo_path: Path | str) -> None:
- """Add ``.repowise/.env`` to the repo's ``.gitignore`` if not already listed."""
+def _ensure_gitignored(repo_path: Path | str, pattern: str, comment: str) -> None:
+ """Add *pattern* to the repo's ``.gitignore`` if not already listed."""
gitignore = Path(repo_path) / ".gitignore"
- pattern = ".repowise/.env"
if gitignore.exists():
content = gitignore.read_text(encoding="utf-8")
@@ -412,10 +427,7 @@ def _ensure_env_gitignored(repo_path: Path | str) -> None:
return
if not content.endswith("\n"):
content += "\n"
- content += f"\n# repowise API keys (local)\n{pattern}\n"
+ content += f"\n# {comment}\n{pattern}\n"
gitignore.write_text(content, encoding="utf-8")
else:
- gitignore.write_text(
- f"# repowise API keys (local)\n{pattern}\n",
- encoding="utf-8",
- )
+ gitignore.write_text(f"# {comment}\n{pattern}\n", encoding="utf-8")
diff --git a/packages/server/src/repowise/server/app.py b/packages/server/src/repowise/server/app.py
index 05a904e6f..fe0ec5ff4 100644
--- a/packages/server/src/repowise/server/app.py
+++ b/packages/server/src/repowise/server/app.py
@@ -51,6 +51,7 @@ from repowise.server.routers import (
decisions,
doc_drift,
episodes,
+ events,
external_systems,
feedback,
files,
@@ -367,6 +368,7 @@ _ROUTERS = (
webhooks,
git,
changes,
+ events,
dead_code,
doc_drift,
code_health,
diff --git a/packages/server/src/repowise/server/routers/events.py b/packages/server/src/repowise/server/routers/events.py
new file mode 100644
index 000000000..b03ec14db
--- /dev/null
+++ b/packages/server/src/repowise/server/routers/events.py
@@ -0,0 +1,40 @@
+"""/api/repos/{repo_id}/events — typed events from consecutive index runs (pull)."""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime
+
+from fastapi import APIRouter, Depends, HTTPException, Query
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from repowise.core.events.model import KINDS, to_cloudevent
+from repowise.core.events.store import list_events
+from repowise.core.persistence import crud
+from repowise.server.deps import get_db_session, verify_api_key
+from repowise.server.schemas.events import CloudEvent, EventListResponse
+
+router = APIRouter(
+ prefix="/api/repos",
+ tags=["events"],
+ dependencies=[Depends(verify_api_key)],
+)
+
+
[email protected]("/{repo_id}/events", response_model=EventListResponse)
+async def get_events(
+ repo_id: str,
+ since: datetime | None = Query(None, description="Only events at or after this time"),
+ kind: list[str] = Query(default_factory=list, description="Only these kinds"),
+ limit: int = Query(200, ge=1, le=1000),
+ session: AsyncSession = Depends(get_db_session),
+) -> EventListResponse:
+ """Stored events, oldest first, as CloudEvents."""
+ if await crud.get_repository(session, repo_id) is None:
+ raise HTTPException(status_code=404, detail="Repository not found")
+ unknown = [k for k in kind if k not in KINDS]
+ if unknown:
+ raise HTTPException(status_code=422, detail=f"Unknown event kind(s): {unknown}")
+ if since is not None and since.tzinfo is None:
+ since = since.replace(tzinfo=UTC)
+ events = await list_events(session, repo_id, since=since, kinds=kind, limit=limit)
+ return EventListResponse(events=[CloudEvent(**to_cloudevent(e)) for e in events])
diff --git a/packages/server/src/repowise/server/schemas/events.py b/packages/server/src/repowise/server/schemas/events.py
new file mode 100644
index 000000000..954201eed
--- /dev/null
+++ b/packages/server/src/repowise/server/schemas/events.py
@@ -0,0 +1,28 @@
+"""Engine event response models: CloudEvents 1.0.2 structured JSON.
+
+``data`` mirrors ``repowise.core.events.model.to_cloudevent``: OTel ``vcs.*``
+names for the revisions, ``repowise.*`` for kind, component, severity and
+stamp, and ``evidence`` with the figures that moved.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from pydantic import BaseModel
+
+
+class CloudEvent(BaseModel):
+ specversion: str
+ id: str
+ source: str
+ type: str
+ time: str
+ datacontenttype: str
+ #: ``component:<name>``; absent for a repository-wide event.
+ subject: str | None = None
+ data: dict[str, Any]
+
+
+class EventListResponse(BaseModel):
+ events: list[CloudEvent]
diff --git a/packages/types/package.json b/packages/types/package.json
index d5b2ead91..e32309b1a 100644
--- a/packages/types/package.json
+++ b/packages/types/package.json
@@ -20,6 +20,7 @@
"./chat": "./src/chat.ts",
"./cards": "./src/cards.ts",
"./changes": "./src/changes.ts",
+ "./events": "./src/events.ts",
"./views": "./src/views.ts",
"./workspace": "./src/workspace.ts",
"./blast-radius": "./src/blast-radius.ts",
diff --git a/packages/types/src/events.ts b/packages/types/src/events.ts
new file mode 100644
index 000000000..463d86c34
--- /dev/null
+++ b/packages/types/src/events.ts
@@ -0,0 +1,10 @@
+/**
+ * Engine events: what moved in a component between two consecutive index
+ * runs under the same analyzer stamp, as CloudEvents 1.0.2 structured JSON.
+ *
+ * Generated from the server's response models
+ * (`packages/server/src/repowise/server/schemas/events.py`). `type` is a
+ * versioned `dev.repowise.*` string; `data` carries OTel `vcs.*` names for
+ * the revisions and `repowise.*` keys for kind, component, severity and stamp.
+ */
+export type { CloudEvent, EventListResponse } from "./generated/http.js";
diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.ts
index f76900619..49dba64be 100644
--- a/packages/types/src/generated/http.ts
+++ b/packages/types/src/generated/http.ts
@@ -698,6 +698,17 @@ export interface ClaudeMdResponse {
sections?: string[];
}
+export interface CloudEvent {
+ specversion: string;
+ id: string;
+ source: string;
+ type: string;
+ time: string;
+ datacontenttype: string;
+ subject?: string | null;
+ data: Record<string, unknown>;
+}
+
/**
* Files that historically change together with one file.
*
@@ -1569,6 +1580,10 @@ export interface EpisodeSummary {
still_true?: string | null;
}
+export interface EventListResponse {
+ events: CloudEvent[];
+}
+
/** One checklist row: what was found, whether it needs a look, how it is known. */
export interface EvidenceItem {
kind: string;
diff --git a/packages/types/src/index.ts b/packages/types/src/index.ts
index 5382d0484..7773875be 100644
--- a/packages/types/src/index.ts
+++ b/packages/types/src/index.ts
@@ -20,6 +20,7 @@ export * from "./symbols.js";
export * from "./chat.js";
export * from "./cards.js";
export * from "./changes.js";
+export * from "./events.js";
export * from "./views.js";
export * from "./workspace.js";
export * from "./blast-radius.js";
diff --git a/packages/ui/vitest.config.ts b/packages/ui/vitest.config.ts
index f801647e1..e09133501 100644
--- a/packages/ui/vitest.config.ts
+++ b/packages/ui/vitest.config.ts
@@ -33,6 +33,7 @@ export default defineConfig({
"@repowise-dev/types/chat": path.resolve(__dirname, "../types/src/chat.ts"),
"@repowise-dev/types/cards": path.resolve(__dirname, "../types/src/cards.ts"),
"@repowise-dev/types/changes": path.resolve(__dirname, "../types/src/changes.ts"),
+ "@repowise-dev/types/events": path.resolve(__dirname, "../types/src/events.ts"),
"@repowise-dev/types/views": path.resolve(__dirname, "../types/src/views.ts"),
"@repowise-dev/types/workspace": path.resolve(__dirname, "../types/src/workspace.ts"),
"@repowise-dev/types/blast-radius": path.resolve(__dirname, "../types/src/blast-radius.ts"),
diff --git a/tests/unit/cli/test_events_cmd.py b/tests/unit/cli/test_events_cmd.py
new file mode 100644
index 000000000..5b2faef46
--- /dev/null
+++ b/tests/unit/cli/test_events_cmd.py
@@ -0,0 +1,76 @@
+"""`repowise events` against a real local index."""
+
+from __future__ import annotations
+
+import json
+from datetime import UTC, datetime, timedelta
+from pathlib import Path
+
+from click.testing import CliRunner
+
+from repowise.cli.commands.events_cmd import events_command
+from repowise.cli.helpers import run_async
+
+
+async def _store(repo_path: Path) -> None:
+ from repowise.core.persistence import (
+ create_engine,
+ create_session_factory,
+ get_session,
+ init_db,
+ upsert_repository,
+ )
+ from repowise.core.persistence.models import EngineEventRecord
+
+ (repo_path / ".repowise").mkdir(exist_ok=True)
+ engine = create_engine(f"sqlite+aiosqlite:///{(repo_path / '.repowise' / 'wiki.db').as_posix()}")
+ try:
+ await init_db(engine)
+ async with get_session(create_session_factory(engine)) as session:
+ repo = await upsert_repository(session, name="repo", local_path=str(repo_path))
+ now = datetime.now(UTC)
+ for i, (kind, age) in enumerate((("dead_code_growth", 30), ("test_reach_drop", 1))):
+ session.add(
+ EngineEventRecord(
+ id=f"{i:032d}",
+ repository_id=repo.id,
+ kind=kind,
+ component="api",
+ severity="info",
+ occurred_at=now - timedelta(days=age),
+ stamp="s",
+ payload_json=json.dumps({"evidence": {"basis": "inferred", "share": 0.4}}),
+ )
+ )
+ finally:
+ await engine.dispose()
+
+
+def _repo(tmp_path: Path) -> Path:
+ root = tmp_path / "repo"
+ (root / ".git").mkdir(parents=True)
+ run_async(_store(root))
+ return root
+
+
+def test_formats_and_filters(tmp_path):
+ root = _repo(tmp_path)
+ runner = CliRunner()
+
+ got = runner.invoke(events_command, ["--path", str(root), "--format", "json"])
+ assert got.exit_code == 0, got.output
+ kinds = [e["data"]["repowise.kind"] for e in json.loads(got.output)["events"]]
+ assert kinds == ["dead_code_growth", "test_reach_drop"]
+
+ recent = runner.invoke(events_command, ["--path", str(root), "--since", "7d", "--format", "jsonl"])
+ lines = [json.loads(line) for line in recent.output.splitlines() if line.strip()]
+ assert [e["id"] for e in lines] == [f"{1:032d}"]
+
+ table = runner.invoke(events_command, ["--path", str(root), "--kind", "dead_code_growth"])
+ assert table.exit_code == 0 and "dead_code_growth" in table.output
+ assert "test_reach_drop" not in table.output
+
+ bad = runner.invoke(events_command, ["--path", str(root), "--kind", "nope"])
+ assert bad.exit_code != 0
+ bad_since = runner.invoke(events_command, ["--path", str(root), "--since", "yesterday"])
+ assert bad_since.exit_code != 0
diff --git a/tests/unit/cli/test_lazy_commands.py b/tests/unit/cli/test_lazy_commands.py
index 18dcb7c63..1b2e2477b 100644
--- a/tests/unit/cli/test_lazy_commands.py
+++ b/tests/unit/cli/test_lazy_commands.py
@@ -36,7 +36,7 @@ _EXPECTED_NAMES = frozenset(
"agents", "ask", "attribution", "augment", "changes", "check", "components", "config", "context", "corrections",
"costs", "coverage",
"dead-code", "decision", "delete", "distill", "doc-drift", "doctor",
- "expand",
+ "events", "expand",
"export", "generate", "generate-claude-md", "health", "hook",
"impacted-tests", "init", "login", "logout", "mcp", "next", "overlap", "plugins",
"publish", "reindex",
diff --git a/tests/unit/core/test_events.py b/tests/unit/core/test_events.py
new file mode 100644
index 000000000..c8f79ea61
--- /dev/null
+++ b/tests/unit/core/test_events.py
@@ -0,0 +1,521 @@
+"""Component snapshots and events: diff rules, the stamp guard, compaction, the wire form."""
+
+from __future__ import annotations
+
+import json
+from datetime import UTC, datetime, timedelta
+from pathlib import Path
+
+import pytest
+
+from repowise.core.events import diff as diff_mod
+from repowise.core.events import snapshot as snapshot_mod
+from repowise.core.events.diff import diff_snapshots
+from repowise.core.events.model import KINDS, EngineEvent, event_id, to_cloudevent
+from repowise.core.events.store import EventSettings, load_event_settings
+
+
+def _facts(**over):
+ base = {
+ "definition": "d1",
+ "criticality": None,
+ "tags": [],
+ "declared_owner": None,
+ "declared_owner_key": None,
+ "key_id": "k1",
+ "file_count": 20,
+ "bus_factor": {"basis": "measured", "value": 2, "owned_files": 20},
+ "test_reach": {"basis": "inferred", "share": 0.6, "production_files": 15},
+ "dead_code": {"basis": "inferred", "findings": 10, "lines": 100},
+ "hotspots": ["a.py"],
+ "ownership": {
+ "owned_files": 20,
+ "owner_count": 3,
+ "main_owners": ["aaa", "bbb"],
+ "active_main_owners": 2,
+ "recent_commits": 5,
+ "window_days": 90,
+ },
+ "decisions": {"governing": 1, "stale": []},
+ "contracts": {"basis": "measured", "provided": {"http::GET::/a": 2}},
+ "attribution": {"commits": 20, "agent_share": 0.1, "coverage": 0.5, "window_days": 90},
+ }
+ for key, value in over.items():
+ if isinstance(value, dict) and isinstance(base.get(key), dict):
+ base[key] = {**base[key], **value}
+ else:
+ base[key] = value
+ return base
+
+
+def _kinds(before, after):
+ return [(k, s) for k, _c, s, _e in diff_snapshots({"c": before}, {"c": after})]
+
+
+# ---------------------------------------------------------------------------
+# Diff rules
+# ---------------------------------------------------------------------------
+
+
+def test_identical_snapshots_produce_nothing():
+ assert diff_snapshots({"c": _facts()}, {"c": _facts()}) == []
+
+
+def test_a_redrawn_or_new_component_is_not_diffed():
+ assert diff_snapshots({"c": _facts()}, {"c": _facts(definition="d2", hotspots=["x"])}) == []
+ assert diff_snapshots({}, {"c": _facts(hotspots=["x"])}) == []
+
+
+def test_declared_owner_change_is_a_shift():
+ found = diff_snapshots(
+ {"c": _facts(declared_owner="team-a", declared_owner_key="x1")},
+ {"c": _facts(declared_owner="team-b", declared_owner_key="x2")},
+ )
+ assert [(k, s) for k, _, s, _ in found] == [("ownership_shift", "declared")]
+ assert found[0][3] == {"basis": "declared", "previous_owner": "team-a", "owner": "team-b"}
+
+
+def test_an_owner_that_is_not_a_group_is_never_named():
+ # declared_owner is None for a user ref: only its keyed digest moved.
+ found = diff_snapshots(
+ {"c": _facts(declared_owner="team-a", declared_owner_key="x1")},
+ {"c": _facts(declared_owner=None, declared_owner_key="x2")},
+ )
+ assert found[0][3] == {"basis": "declared", "previous_owner": "team-a"}
+
+
+def test_owner_digests_under_another_key_are_not_compared():
+ after = _facts(key_id="k2", ownership={"main_owners": ["ccc", "ddd"], "active_main_owners": 0})
+ assert _kinds(_facts(), after) == []
+ renamed = _facts(key_id="k2", declared_owner_key="x2")
+ assert _kinds(_facts(declared_owner_key="x1"), renamed) == []
+
+
+def test_a_capped_recent_window_does_not_drive_activity_or_attribution():
+ reg = {"tags": ["pci"]}
+ capped = {"agent_share": 0.5, "recent_capped": True}
+ assert _kinds(_facts(**reg), _facts(**reg, attribution=capped)) == []
+ gone = {"active_main_owners": 0, "recent_capped": True}
+ assert _kinds(_facts(), _facts(ownership=gone)) == []
+
+
+def test_observed_owner_turnover_needs_enough_owned_files():
+ after = {"main_owners": ["ccc", "ddd"]}
+ assert _kinds(_facts(), _facts(ownership=after)) == [("ownership_shift", "observed")]
+ small = {"owned_files": diff_mod.MIN_OWNED_FILES - 1}
+ assert _kinds(_facts(ownership=small), _facts(ownership={**after, **small})) == []
+ # A set that grew around the same owners is not a shift.
+ grew = {"main_owners": ["aaa", "bbb", "ccc"]}
+ assert _kinds(_facts(), _facts(ownership=grew)) == []
+
+
+def test_owner_inactive_only_while_others_still_change_it():
+ gone = {"active_main_owners": 0}
+ assert _kinds(_facts(), _facts(ownership=gone)) == [("owner_inactive", "")]
+ quiet = {"active_main_owners": 0, "recent_commits": 0}
+ assert _kinds(_facts(), _facts(ownership=quiet)) == []
+
+
+def test_bus_factor_drop_only_on_a_critical_component_with_measured_figures():
+ drop = {"value": 1}
+ assert _kinds(_facts(), _facts(bus_factor=drop)) == []
+ crit = {"criticality": "critical"}
+ assert _kinds(_facts(**crit), _facts(**crit, bus_factor=drop)) == [("bus_factor_drop", "")]
+ inferred = {"basis": "inferred", "value": 1}
+ assert _kinds(_facts(**crit), _facts(**crit, bus_factor=inferred)) == []
+
+
+def test_new_hotspots_name_the_files():
+ found = diff_snapshots({"c": _facts()}, {"c": _facts(hotspots=["a.py", "b.py"])})
+ assert found[0][0] == "new_hotspot" and found[0][3]["files"] == ["b.py"]
+ assert _kinds(_facts(hotspots=["a.py", "b.py"]), _facts()) == []
+
+
+def test_contracts_added_and_broken_only_with_consumers():
+ after = _facts(contracts={"provided": {"http::GET::/b": 0}})
+ assert _kinds(_facts(), after) == [
+ ("contract_added", "http::GET::/b"),
+ ("contract_broken", "http::GET::/a"),
+ ]
+ unread = _facts(contracts={"provided": {"http::GET::/a": 0}})
+ assert _kinds(unread, _facts(contracts={"provided": {}})) == []
+ unknown = _facts(contracts={"basis": "unavailable"})
+ assert _kinds(unknown, after) == [] and _kinds(after, unknown) == []
+
+
+def test_a_decision_turning_stale_is_one_event():
+ assert _kinds(_facts(), _facts(decisions={"stale": ["d9"]})) == [("decision_stale", "d9")]
+ assert _kinds(_facts(decisions={"stale": ["d9"]}), _facts(decisions={"stale": ["d9"]})) == []
+
+
+def test_dead_code_growth_needs_both_floors():
+ assert _kinds(_facts(), _facts(dead_code={"findings": 15})) == [("dead_code_growth", "")]
+ assert _kinds(_facts(), _facts(dead_code={"findings": 14})) == [] # +4
+ big = {"findings": 100}
+ assert _kinds(_facts(dead_code=big), _facts(dead_code={"findings": 120})) == [] # +20%
+
+
+def test_test_reach_drop_by_share_or_measured_coverage():
+ assert _kinds(_facts(), _facts(test_reach={"share": 0.5})) == [("test_reach_drop", "")]
+ assert _kinds(_facts(), _facts(test_reach={"share": 0.55})) == []
+ cov = {"line_coverage": {"pct": 80.0}}
+ fell = {"line_coverage": {"pct": 70.0}}
+ found = diff_snapshots({"c": _facts(test_reach=cov)}, {"c": _facts(test_reach=fell)})
+ assert found[0][3] == {"line_coverage": {"basis": "measured", "previous_pct": 80.0, "pct": 70.0}}
+
+
+def test_attribution_jump_only_on_regulated_components_with_coverage():
+ up = {"agent_share": 0.5}
+ assert _kinds(_facts(), _facts(attribution=up)) == []
+ reg = {"tags": ["pci"]}
+ assert _kinds(_facts(**reg), _facts(**reg, attribution=up)) == [("attribution_jump", "")]
+ withheld = {"agent_share": None}
+ assert _kinds(_facts(**reg), _facts(**reg, attribution=withheld)) == []
+ few = {"commits": 3, "agent_share": 0.9}
+ assert _kinds(_facts(**reg), _facts(**reg, attribution=few)) == []
+
+
+# ---------------------------------------------------------------------------
+# Wire form and settings
+# ---------------------------------------------------------------------------
+
+
+def _event(**over) -> EngineEvent:
+ fields = {
+ "id": event_id("r", "a", "b", "new_hotspot", "core", "x.py"),
+ "kind": "new_hotspot",
+ "repo_id": "r1",
+ "component": "core",
+ "severity": "critical",
+ "occurred_at": datetime(2026, 10, 1, 12, tzinfo=UTC),
+ "evidence": {"files": ["x.py"]},
+ "stamp": "h40.p8",
+ "commit_sha": "b" * 40,
+ "base_commit_sha": "a" * 40,
+ "source": "https://example.com/acme/app",
+ "vcs": {"vcs.change.id": "pr-12"},
+ }
+ fields.update(over)
+ return EngineEvent(**fields)
+
+
+def test_cloudevents_envelope_shape():
+ ce = to_cloudevent(_event())
+ assert set(ce) == {
+ "specversion",
+ "id",
+ "source",
+ "type",
+ "time",
+ "datacontenttype",
+ "subject",
+ "data",
+ }
+ assert ce["specversion"] == "1.0"
+ assert ce["type"] == "dev.repowise.hotspot.added.0.1.0"
+ assert ce["time"] == "2026-10-01T12:00:00Z"
+ assert ce["subject"] == "component:core"
+ assert ce["source"] == "https://example.com/acme/app"
+ data = ce["data"]
+ assert data["vcs.change.id"] == "pr-12"
+ assert data["vcs.ref.head.revision"] == "b" * 40
+ assert data["vcs.ref.base.revision"] == "a" * 40
+ assert data["repowise.stamp"] == "h40.p8" and data["evidence"] == {"files": ["x.py"]}
+
+
+def test_envelope_without_component_or_url():
+ ce = to_cloudevent(_event(component=None, source="", vcs={}, base_commit_sha=None))
+ assert "subject" not in ce
+ assert ce["source"] == "/repos/r1"
+ assert "vcs.ref.base.revision" not in ce["data"]
+
+
+def test_every_kind_has_a_versioned_type():
+ for kind in KINDS.values():
+ assert kind.type.startswith("dev.repowise.") and kind.type.endswith(".0.1.0")
+
+
+def test_event_ids_are_stable():
+ assert event_id("r", "a", "b", "k") == event_id("r", "a", "b", "k")
+ assert event_id("r", "a", "b", "k") != event_id("r", "a", "c", "k")
+ assert len(event_id("x")) == 32
+
+
+def test_settings_defaults_and_overrides(tmp_path):
+ assert load_event_settings(tmp_path) == EventSettings()
+ assert "new_hotspot" not in EventSettings().kinds
+ (tmp_path / ".repowise").mkdir()
+ (tmp_path / ".repowise" / "config.yaml").write_text(
+ "events:\n retention_days: 30\n compact_after_days: -1\n"
+ " kinds: {new_hotspot: true, dead_code_growth: false, bogus: true}\n"
+ " sinks: [stdout]\n",
+ encoding="utf-8",
+ )
+ s = load_event_settings(tmp_path)
+ assert s.retention_days == 30 and s.compact_after_days == 30
+ assert "new_hotspot" in s.kinds and "dead_code_growth" not in s.kinds
+ assert "bogus" not in s.kinds and s.sinks == ("stdout",)
+ assert [e.split(":")[0] for e in s.errors] == [
+ "events.kinds.bogus",
+ "events.compact_after_days",
+ ]
+
+
+def test_settings_name_every_wrong_value(tmp_path):
+ (tmp_path / ".repowise").mkdir()
+ (tmp_path / ".repowise" / "config.yaml").write_text(
+ "events:\n enabled: maybe\n retention_days: '30'\n kinds: [new_hotspot]\n"
+ " sinks: jsonl\n colour: red\n",
+ encoding="utf-8",
+ )
+ s = load_event_settings(tmp_path)
+ assert s.enabled is True and s.retention_days == 365 and s.sinks == ()
+ assert sorted(e.split(":")[0] for e in s.errors) == [
+ "events.colour",
+ "events.enabled",
+ "events.kinds",
+ "events.retention_days",
+ "events.sinks",
+ ]
+
+
+def test_doctor_reports_a_wrong_events_block(tmp_path):
+ from repowise.cli.commands.doctor_cmd.repo_checks import _events_config_check
+
+ assert _events_config_check(tmp_path) is None
+ (tmp_path / ".repowise").mkdir()
+ (tmp_path / ".repowise" / "config.yaml").write_text(
+ "events:\n kinds: {nope: true}\n", encoding="utf-8"
+ )
+ check = _events_config_check(tmp_path)
+ assert check is not None and not check.ok and "events.kinds.nope" in check.detail
+
+
+def test_owner_key_is_kept_and_digests_are_not_plain_hashes(tmp_path):
+ import hashlib
+
+ key = snapshot_mod.owner_key(tmp_path)
+ assert key is not None and snapshot_mod.owner_key(tmp_path) == key
+ # Some repos commit .repowise/: the key gets its own ignore rule.
+ ignored = (tmp_path / ".gitignore").read_text(encoding="utf-8").splitlines()
+ assert ".repowise/events.key" in ignored
+ digest = snapshot_mod._keyed(key, "[email protected]")
+ assert digest != hashlib.sha256(b"[email protected]").hexdigest()[: len(digest)]
+
+
+def test_credentials_never_leave_in_the_source_url():
+ from repowise.core.events.store import _public_url
+
+ assert _public_url("https://user:[email protected]/a/b.git") == "https://github.com/a/b.git"
+ assert _public_url("https://github.com/a/b") == "https://github.com/a/b"
+ assert _public_url(None) == ""
+
+
+# ---------------------------------------------------------------------------
+# Store: stamp guard, sinks, compaction
+# ---------------------------------------------------------------------------
+
+
+async def repo_db(tmp_path: Path):
+ from repowise.core.persistence import (
+ create_engine,
+ create_session_factory,
+ init_db,
+ upsert_repository,
+ )
+ from repowise.core.persistence.database import get_session
+
+ root = tmp_path / "repo"
+ (root / ".repowise").mkdir(parents=True)
+ (root / ".repowise" / "config.yaml").write_text(
+ "events:\n kinds: {new_hotspot: true}\n", encoding="utf-8"
+ )
+ engine = create_engine(f"sqlite+aiosqlite:///{(tmp_path / 'wiki.db').as_posix()}")
+ await init_db(engine)
+ factory = create_session_factory(engine)
+ async with get_session(factory) as session:
+ repo = await upsert_repository(session, name="repo", local_path=str(root))
+ repo_id = repo.id
+ yield factory, repo_id, root
+ await engine.dispose()
+
+
+async def _run(factory, repo_id, *, head, facts, monkeypatch, stamp="s1", now=None):
+ from repowise.core.events.store import record_snapshot
+ from repowise.core.persistence.database import get_session
+ from repowise.core.persistence.models import Repository
+
+ async def _collect(*_a, **_k):
+ return facts
+
+ monkeypatch.setattr(snapshot_mod, "collect_facts", _collect)
+ monkeypatch.setattr(snapshot_mod, "current_stamp", lambda: stamp)
+ async with get_session(factory) as session:
+ (await session.get(Repository, repo_id)).head_commit = head
+ return await record_snapshot(session, repo_id, now=now)
+
+
+async def test_same_stamp_runs_diff_and_reach_the_jsonl_sink(repo_db, monkeypatch):
+ from repowise.core.events.store import list_events
+ from repowise.core.persistence.database import get_session
+
+ factory, repo_id, root = repo_db
+ assert await _run(factory, repo_id, head="a" * 40, facts={"c": _facts()}, monkeypatch=monkeypatch) == []
+ after = {"c": _facts(hotspots=["a.py", "b.py"])}
+ events = await _run(factory, repo_id, head="b" * 40, facts=after, monkeypatch=monkeypatch)
+ assert [e.kind for e in events] == ["new_hotspot"]
+ assert events[0].base_commit_sha == "a" * 40 and events[0].severity == "info"
+
+ lines = (root / ".repowise" / "events.jsonl").read_text(encoding="utf-8").splitlines()
+ assert [json.loads(line)["id"] for line in lines] == [events[0].id]
+
+ # The same commit and stamp again is an update with nothing to do.
+ assert await _run(factory, repo_id, head="b" * 40, facts=after, monkeypatch=monkeypatch) == []
+ async with get_session(factory) as session:
+ stored = await list_events(session, repo_id)
+ assert [e.id for e in stored] == [events[0].id]
+ assert stored[0].evidence["files"] == ["b.py"]
+ assert await list_events(session, repo_id, kinds=["owner_inactive"]) == []
+
+
+async def test_a_run_without_a_snapshot_breaks_the_chain(repo_db, monkeypatch):
+ from repowise.core.events.store import record_gap
+ from repowise.core.persistence.database import get_session
+
+ factory, repo_id, root = repo_db
+ cfg = root / ".repowise" / "config.yaml"
+ on = "events:\n kinds: {new_hotspot: true}\n"
+ hot = {"c": _facts(hotspots=["a.py", "b.py"])}
+ await _run(factory, repo_id, head="a" * 40, facts={"c": _facts()}, monkeypatch=monkeypatch)
+ cfg.write_text("events:\n enabled: false\n", encoding="utf-8")
+ await _run(factory, repo_id, head="b" * 40, facts=hot, monkeypatch=monkeypatch)
+ cfg.write_text(on, encoding="utf-8")
+ assert await _run(factory, repo_id, head="c" * 40, facts=hot, monkeypatch=monkeypatch) == []
+
+ # A failed snapshot leaves the same marker.
+ async with get_session(factory) as session:
+ await record_gap(session, repo_id, "failed")
+ hotter = {"c": _facts(hotspots=["a.py", "b.py", "c.py"])}
+ assert await _run(factory, repo_id, head="d" * 40, facts=hotter, monkeypatch=monkeypatch) == []
+ more = {"c": _facts(hotspots=["a.py", "b.py", "c.py", "d.py"])}
+ events = await _run(factory, repo_id, head="e" * 40, facts=more, monkeypatch=monkeypatch)
+ assert [e.evidence["files"] for e in events] == [["d.py"]]
+
+
+async def test_a_commit_pair_seen_again_is_a_new_event(repo_db, monkeypatch):
+ factory, repo_id, _ = repo_db
+ quiet, hot = {"c": _facts()}, {"c": _facts(hotspots=["a.py", "b.py"])}
+ ids = []
+ for head, facts in (("a", quiet), ("b", hot), ("a", quiet), ("b", hot)):
+ events = await _run(factory, repo_id, head=head * 40, facts=facts, monkeypatch=monkeypatch)
+ ids += [e.id for e in events]
+ assert len(ids) == 2 and len(set(ids)) == 2
+
+ # Runs with no commit at all still diff, each as its own occurrence.
+ hotter = {"c": _facts(hotspots=["a.py", "b.py", "c.py"])}
+ await _run(factory, repo_id, head=None, facts=hot, monkeypatch=monkeypatch)
+ first = await _run(factory, repo_id, head=None, facts=hotter, monkeypatch=monkeypatch)
+ await _run(factory, repo_id, head=None, facts=hot, monkeypatch=monkeypatch)
+ second = await _run(factory, repo_id, head=None, facts=hotter, monkeypatch=monkeypatch)
+ assert len(first) == len(second) == 1 and first[0].id != second[0].id
+
+
+async def test_a_stamp_change_starts_a_new_baseline(repo_db, monkeypatch):
+ factory, repo_id, _ = repo_db
+ await _run(factory, repo_id, head="a" * 40, facts={"c": _facts()}, monkeypatch=monkeypatch)
+ moved = {"c": _facts(hotspots=["a.py", "b.py"], dead_code={"findings": 50})}
+ assert (
+ await _run(factory, repo_id, head="b" * 40, facts=moved, monkeypatch=monkeypatch, stamp="s2")
+ == []
+ )
+ # Against the new baseline the same facts are quiet.
+ assert (
+ await _run(factory, repo_id, head="c" * 40, facts=moved, monkeypatch=monkeypatch, stamp="s2")
+ == []
+ )
+
+
+async def test_disabled_kinds_and_disabled_events_store_nothing(repo_db, monkeypatch):
+ factory, repo_id, root = repo_db
+ (root / ".repowise" / "config.yaml").write_text("events:\n enabled: false\n", encoding="utf-8")
+ assert await _run(factory, repo_id, head="a" * 40, facts={"c": _facts()}, monkeypatch=monkeypatch) == []
+ (root / ".repowise" / "config.yaml").write_text("", encoding="utf-8")
+ await _run(factory, repo_id, head="a" * 40, facts={"c": _facts()}, monkeypatch=monkeypatch)
+ after = {"c": _facts(hotspots=["a.py", "b.py"])} # new_hotspot is off by default
+ assert await _run(factory, repo_id, head="b" * 40, facts=after, monkeypatch=monkeypatch) == []
+
+
+async def test_compaction_keeps_one_run_per_week_and_drops_past_retention(repo_db, monkeypatch):
+ from sqlalchemy import select
+
+ from repowise.core.events.store import compact
+ from repowise.core.persistence.database import get_session
+ from repowise.core.persistence.models import (
+ ComponentSnapshot,
+ EngineEventRecord,
+ SnapshotRun,
+ )
+
+ factory, repo_id, _ = repo_db
+ now = datetime(2026, 10, 14, tzinfo=UTC) # a Wednesday
+ days = [0, 1, 40, 41, 42, 50, 400]
+ async with get_session(factory) as session:
+ for d in days:
+ run = SnapshotRun(
+ repository_id=repo_id, taken_at=now - timedelta(days=d), commit_sha=f"{d}", stamp="s"
+ )
+ session.add(run)
+ await session.flush()
+ session.add(ComponentSnapshot(run_id=run.id, component="c", facts_json="{}"))
+ for d in (10, 400):
+ session.add(
+ EngineEventRecord(
+ id=f"e{d}",
+ repository_id=repo_id,
+ kind="new_hotspot",
+ severity="info",
+ occurred_at=now - timedelta(days=d),
+ stamp="s",
+ )
+ )
+ await session.flush()
+ await compact(
+ session, repo_id, EventSettings(retention_days=365, compact_after_days=30), now=now
+ )
+ async with get_session(factory) as session:
+ kept = {
+ r.commit_sha: r.compacted for r in (await session.scalars(select(SnapshotRun))).all()
+ }
+ # 40/41/42 days back share an ISO week (Sep 2-4); 50 is the week before.
+ assert kept == {"0": False, "1": False, "40": True, "50": True}
+ assert len((await session.scalars(select(ComponentSnapshot))).all()) == 4
+ assert [e.id for e in (await session.scalars(select(EngineEventRecord))).all()] == ["e10"]
+
+
+async def test_a_failing_sink_leaves_the_event_stored(repo_db, monkeypatch):
+ from repowise.core.events.sinks import event_sinks
+ from repowise.core.events.store import list_events
+ from repowise.core.persistence.database import get_session
+
+ class Broken:
+ async def deliver(self, events, *, repo_root):
+ raise OSError("down")
+
+ factory, repo_id, root = repo_db
+ event_sinks.register("broken-test", Broken())
+ (root / ".repowise" / "config.yaml").write_text(
+ "events:\n kinds: {new_hotspot: true}\n sinks: [broken-test]\n", encoding="utf-8"
+ )
+ await _run(factory, repo_id, head="a" * 40, facts={"c": _facts()}, monkeypatch=monkeypatch)
+ after = {"c": _facts(hotspots=["a.py", "b.py"])}
+ events = await _run(factory, repo_id, head="b" * 40, facts=after, monkeypatch=monkeypatch)
+ async with get_session(factory) as session:
+ assert [e.id for e in await list_events(session, repo_id)] == [events[0].id]
diff --git a/tests/unit/persistence/test_models.py b/tests/unit/persistence/test_models.py
index c18254770..736bc66b2 100644
--- a/tests/unit/persistence/test_models.py
+++ b/tests/unit/persistence/test_models.py
@@ -327,6 +327,9 @@ def test_base_includes_all_models():
"health_findings",
"health_file_metrics",
"health_snapshots",
+ "snapshot_runs",
+ "component_snapshots",
+ "events",
"refactoring_suggestions",
"refactoring_opportunities",
"refactoring_summaries",
diff --git a/tests/unit/server/conftest.py b/tests/unit/server/conftest.py
index c8cc4385f..feec1ab6c 100644
--- a/tests/unit/server/conftest.py
+++ b/tests/unit/server/conftest.py
@@ -37,6 +37,7 @@ def _create_test_app():
decisions,
doc_drift,
episodes,
+ events,
external_systems,
files,
git,
@@ -91,6 +92,7 @@ def _create_test_app():
app.include_router(webhooks.router)
app.include_router(git.router)
app.include_router(changes.router)
+ app.include_router(events.router)
app.include_router(files.router)
app.include_router(dead_code.router)
app.include_router(doc_drift.router)
diff --git a/tests/unit/server/test_events_routes.py b/tests/unit/server/test_events_routes.py
new file mode 100644
index 000000000..f80a40944
--- /dev/null
+++ b/tests/unit/server/test_events_routes.py
@@ -0,0 +1,60 @@
+"""GET /api/repos/{id}/events: stored events as CloudEvents, filtered by time and kind."""
+
+from __future__ import annotations
+
+import json
+from datetime import UTC, datetime
+
+import pytest
+from httpx import AsyncClient
+
+from repowise.core.persistence.database import get_session
+from repowise.core.persistence.models import EngineEventRecord
+from tests.unit.server.conftest import create_test_repo
+
+
+async def _seed(app, repo_id: str) -> None:
+ async with get_session(app.state.session_factory) as session:
+ for i, kind in enumerate(("new_hotspot", "dead_code_growth"), start=1):
+ session.add(
+ EngineEventRecord(
+ id=f"{i:032d}",
+ repository_id=repo_id,
+ kind=kind,
+ component="core",
+ severity="high",
+ occurred_at=datetime(2026, 10, i, tzinfo=UTC),
+ commit_sha="b" * 40,
+ base_commit_sha="a" * 40,
+ stamp="h40.p8",
+ payload_json=json.dumps(
+ {"evidence": {"n": i}, "vcs": {"vcs.change.id": "pr-7"}, "source": ""}
+ ),
+ )
+ )
+
+
+async def test_events_are_cloudevents_oldest_first(client: AsyncClient, app) -> None:
+ repo = await create_test_repo(client)
+ await _seed(app, repo["id"])
+ url = f"/api/repos/{repo['id']}/events"
+
+ events = (await client.get(url)).json()["events"]
+ assert [e["type"] for e in events] == [
+ "dev.repowise.hotspot.added.0.1.0",
+ "dev.repowise.deadcode.grew.0.1.0",
+ ]
+ first = events[0]
+ assert first["specversion"] == "1.0" and first["subject"] == "component:core"
+ assert first["source"] == f"/repos/{repo['id']}"
+ assert first["data"]["vcs.change.id"] == "pr-7"
+ assert first["data"]["vcs.ref.head.revision"] == "b" * 40
+ assert first["data"]["evidence"] == {"n": 1}
+
+ later = (await client.get(url, params={"since": "2026-10-02T00:00:00"})).json()["events"]
+ assert [e["id"] for e in later] == [f"{2:032d}"]
+ only = (await client.get(url, params={"kind": "new_hotspot"})).json()["events"]
+ assert [e["id"] for e in only] == [f"{1:032d}"]
+ assert (await client.get(url, params={"kind": "nope"})).status_code == 422
+ assert (await client.get("/api/repos/nope/events")).status_code == 404