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(update): refresh external systems (C4 L1) on manifest change (#921)

Raghav Chamadiya6713ece5d3c6
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
index e6085d7c0..8a1d324da 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
@@ -586,6 +586,16 @@ async def _persist_full_update_async(
except Exception as exc:
_skip("Graph edges persist", exc)
+ # Refresh external systems (C4 L1) when a manifest changed — the
+ # docs-mode persister mirrors the incremental one, which does the
+ # same. Gated + no LLM inside the shared core helper.
+ try:
+ from repowise.core.pipeline.incremental import refresh_external_systems
+
+ await refresh_external_systems(session, repo_id, repo_path, file_diffs)
+ except Exception as exc:
+ _skip("External systems refresh", exc)
+
# Record a GenerationJob so the web UI "last synced" timestamp updates.
try:
from datetime import UTC as _UTC
diff --git a/packages/core/src/repowise/core/ingestion/external_systems/__init__.py b/packages/core/src/repowise/core/ingestion/external_systems/__init__.py
index 61f8ace33..d2c07ddd3 100644
--- a/packages/core/src/repowise/core/ingestion/external_systems/__init__.py
+++ b/packages/core/src/repowise/core/ingestion/external_systems/__init__.py
@@ -25,6 +25,7 @@ __all__ = [
"ExternalSystemRecord",
"ManifestParser",
"extract_external_systems",
+ "is_manifest_path",
]
_PARSERS: tuple[ModuleType, ...] = (npm, pypi, cargo, go, nuget, maven, cmake, bazel)
@@ -34,6 +35,7 @@ _FILENAME_PARSERS: dict[str, ModuleType] = {
fname: parser for parser in _PARSERS for fname in parser.filenames
}
+
# Filename patterns that match by predicate (pypi requirements*.txt, nuget *.csproj)
def _matches_pattern(filename: str) -> ModuleType | None:
lower = filename.lower()
@@ -51,6 +53,16 @@ def _parser_for(path: Path) -> ModuleType | None:
return _matches_pattern(path.name)
+def is_manifest_path(path: Path | str) -> bool:
+ """True if ``path``'s filename is a recognised dependency manifest.
+
+ Reuses the exact parser dispatch extraction uses, so the update path's
+ "did a manifest change?" gate can never drift from the set of files the
+ extractor actually parses. Only the basename matters.
+ """
+ return _parser_for(Path(path)) is not None
+
+
def extract_external_systems(
repo_root: Path,
manifest_paths: Iterable[Path] | None = None,
diff --git a/packages/core/src/repowise/core/persistence/crud/external_systems.py b/packages/core/src/repowise/core/persistence/crud/external_systems.py
index c7d7c742f..f69ddb355 100644
--- a/packages/core/src/repowise/core/persistence/crud/external_systems.py
+++ b/packages/core/src/repowise/core/persistence/crud/external_systems.py
@@ -70,6 +70,36 @@ async def bulk_upsert_external_systems(
return id_map
+async def replace_external_systems(
+ session: AsyncSession,
+ repository_id: str,
+ systems: list[dict],
+) -> dict[tuple[str, str], int]:
+ """Reconcile a repository's external systems to exactly *systems*.
+
+ Like :func:`bulk_upsert_external_systems`, but also DELETES rows whose
+ ``(name, declared_in)`` key is absent from *systems* — so a dependency
+ dropped from a manifest stops being served (the plain upsert leaks it
+ forever). The ``graph_nodes.external_system_id`` FK is ``ON DELETE SET
+ NULL``, so a deleted row's links clear automatically; callers re-link from
+ the returned id_map. Returns ``(name, declared_in)`` → row ``id`` for the
+ surviving set (same shape as :func:`bulk_upsert_external_systems`).
+
+ Intended for the incremental update path, which re-extracts the whole repo
+ (a complete set) whenever a manifest changed. The full-init path stays on
+ the pure upsert — it delete-then-inserts elsewhere.
+ """
+ fresh_keys = {(s.get("name", ""), s.get("declared_in", "")) for s in systems if s.get("name")}
+ result = await session.execute(
+ select(ExternalSystem).where(ExternalSystem.repository_id == repository_id)
+ )
+ for row in result.scalars():
+ if (row.name, row.declared_in) not in fresh_keys:
+ await session.delete(row)
+ await session.flush()
+ return await bulk_upsert_external_systems(session, repository_id, systems)
+
+
async def link_graph_nodes_to_external_systems(
session: AsyncSession,
repository_id: str,
diff --git a/packages/core/src/repowise/core/pipeline/incremental.py b/packages/core/src/repowise/core/pipeline/incremental.py
index 3a665e91f..ddd7827ed 100644
--- a/packages/core/src/repowise/core/pipeline/incremental.py
+++ b/packages/core/src/repowise/core/pipeline/incremental.py
@@ -579,6 +579,72 @@ async def persist_incremental_commits(session: Any, repo_id: str, repo_path: Any
)
+async def refresh_external_systems(
+ session: Any,
+ repo_id: str,
+ repo_path: Any,
+ file_diffs: list,
+ *,
+ log: LogFn | None = None,
+) -> bool:
+ """Re-extract + reconcile external systems (C4 L1) when a manifest changed.
+
+ The incremental path historically never refreshed the ``external_systems``
+ table, so the C4 architecture panel served the init-time dependency list
+ until the next full re-index. Extraction is a bounded repo walk (no LLM, no
+ network), so it is gated on an actual dependency-manifest change in this
+ update's diff — the common no-manifest update pays nothing.
+
+ When a manifest did change, the *whole* repo is re-extracted: it's cheap,
+ and only a complete set supports a clean reconcile that also drops deps
+ removed from a manifest. The table is then replaced (removed deps pruned)
+ and ``external:{name}`` graph nodes re-linked so a brand-new dependency's
+ node isn't left with a NULL FK.
+
+ Ceiling: re-extraction walks the repo (depth ≤ 4) rather than parsing only
+ the changed manifests — fine because it runs only on a manifest change and
+ a partial parse can't see cross-manifest removals. Returns ``True`` when a
+ refresh actually ran.
+ """
+ log = log or _noop_log
+ from repowise.core.ingestion.external_systems import is_manifest_path
+
+ if not any(is_manifest_path(fd.path) for fd in file_diffs or []):
+ return False
+
+ from repowise.core.ingestion.external_systems import extract_external_systems
+
+ records = await asyncio.to_thread(extract_external_systems, Path(repo_path))
+ systems = [
+ {
+ "name": r.name,
+ "display_name": r.display_name,
+ "ecosystem": r.ecosystem,
+ "category": r.category,
+ "io_kind": r.io_kind,
+ "version": r.version,
+ "declared_in": r.declared_in,
+ "is_dev_dep": r.is_dev_dep,
+ }
+ for r in records
+ ]
+
+ from repowise.core.persistence.crud import (
+ link_graph_nodes_to_external_systems,
+ replace_external_systems,
+ )
+
+ id_map = await replace_external_systems(session, repo_id, systems)
+ # Collapse multi-manifest duplicates: any id for a given name works (the
+ # C4 renderer only needs name/category/ecosystem, stable across rows).
+ name_to_id: dict[str, int] = {}
+ for (name, _declared_in), sys_id in id_map.items():
+ name_to_id.setdefault(name, sys_id)
+ await link_graph_nodes_to_external_systems(session, repo_id, name_to_id)
+ log(f"External systems refreshed: [cyan]{len(systems)}[/cyan] deps")
+ return True
+
+
async def persist_incremental_index(
repo_path: Any,
graph_builder: Any,
@@ -753,6 +819,15 @@ async def persist_incremental_index(
except Exception as exc:
_skip("Knowledge-graph persist", exc)
+ # Refresh external systems (C4 L1) when a dependency manifest
+ # changed — otherwise the architecture panel serves the init-time
+ # dep list forever. Gated + no LLM (see refresh_external_systems).
+ if file_diffs:
+ try:
+ await refresh_external_systems(session, repo_id, repo_path, file_diffs, log=log)
+ except Exception as exc:
+ _skip("External systems refresh", exc)
+
# One-shot drain of proposals from the removed code_comment
# harvest (#751). Runs on the index-only path too, because the
# post-commit hook's updates never reach the full decision
diff --git a/tests/unit/persistence/test_incremental_external_systems.py b/tests/unit/persistence/test_incremental_external_systems.py
new file mode 100644
index 000000000..a61c1ec06
--- /dev/null
+++ b/tests/unit/persistence/test_incremental_external_systems.py
@@ -0,0 +1,69 @@
+"""Incremental updates must refresh ``external_systems`` (C4 L1) on manifest change.
+
+The incremental update path historically never re-extracted external systems, so
+the C4 architecture panel served the init-time dependency list until a full
+re-index. These tests drive the real ``refresh_external_systems`` helper over a
+repo whose ``package.json`` changes and assert: a manifest change re-extracts and
+reconciles the table (added deps appear, removed deps pruned), and a change that
+touches no manifest is a no-op that never re-extracts.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+from repowise.core.persistence.crud import list_external_systems
+from repowise.core.pipeline.incremental import refresh_external_systems
+from tests.unit.persistence.helpers import insert_repo
+
+
+def _diff(path: str):
+ """Minimal stand-in for a FileDiff — the helper only reads ``.path``."""
+ return SimpleNamespace(path=path, status="modified")
+
+
+async def _names(session, repo_id: str) -> set[str]:
+ return {s.name for s in await list_external_systems(session, repo_id)}
+
+
+async def test_manifest_change_reextracts_and_reconciles(async_session, tmp_path):
+ repo = await insert_repo(async_session)
+
+ # v1: two runtime deps.
+ (tmp_path / "package.json").write_text(
+ '{"dependencies": {"react": "^18.0.0", "lodash": "^4.0.0"}}'
+ )
+ ran = await refresh_external_systems(async_session, repo.id, tmp_path, [_diff("package.json")])
+ await async_session.commit()
+ assert ran is True
+ assert await _names(async_session, repo.id) == {"react", "lodash"}
+
+ # v2: lodash dropped, axios added. A manifest changed, so re-extract runs;
+ # the reconcile must add axios AND prune the now-removed lodash.
+ (tmp_path / "package.json").write_text(
+ '{"dependencies": {"react": "^18.0.0", "axios": "^1.0.0"}}'
+ )
+ ran = await refresh_external_systems(async_session, repo.id, tmp_path, [_diff("package.json")])
+ await async_session.commit()
+ assert ran is True
+ assert await _names(async_session, repo.id) == {"react", "axios"}
+
+
+async def test_non_manifest_change_is_a_noop(async_session, tmp_path):
+ """A diff with no dependency manifest never re-extracts (the perf guard)."""
+ repo = await insert_repo(async_session)
+
+ (tmp_path / "package.json").write_text('{"dependencies": {"react": "^18.0.0"}}')
+ assert await refresh_external_systems(async_session, repo.id, tmp_path, [_diff("package.json")])
+ await async_session.commit()
+ assert await _names(async_session, repo.id) == {"react"}
+
+ # Edit the manifest on disk but hand the helper a source-only diff: the gate
+ # must skip extraction entirely, leaving the init-time rows untouched.
+ (tmp_path / "package.json").write_text(
+ '{"dependencies": {"react": "^18.0.0", "vue": "^3.0.0"}}'
+ )
+ ran = await refresh_external_systems(async_session, repo.id, tmp_path, [_diff("src/index.ts")])
+ await async_session.commit()
+ assert ran is False
+ assert await _names(async_session, repo.id) == {"react"} # vue never picked up