Skip to content

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

fix(update): rebuild the knowledge graph on incremental updates (#669) (#702)

Raghav Chamadiya21f031db19da
diff --git a/docs/CLI_REFERENCE.md b/docs/CLI_REFERENCE.md
index a8d3e8ecd..cae5826ae 100644
--- a/docs/CLI_REFERENCE.md
+++ b/docs/CLI_REFERENCE.md
@@ -110,7 +110,12 @@ repowise init . --no-workspace # force single-repo, even
### `repowise update [PATH]`
-Incrementally update wiki pages for files changed since the last sync.
+Incrementally refresh the index for files changed since the last sync: the
+dependency graph, git metadata, health and dead-code findings, and — when the
+graph shape changed — the knowledge graph (layers, guided tour, entry points)
+plus the exported `knowledge-graph.json`. In docs mode it also regenerates the
+affected wiki pages. Index-only updates carry forward the previously generated
+layer names and node summaries, so no LLM call is ever made without docs mode.
**Options:**
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/command.py b/packages/cli/src/repowise/cli/commands/update_cmd/command.py
index f9170d76a..55afe2179 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/command.py
@@ -42,6 +42,7 @@ from repowise.core.reasoning import REASONING_MODES
from .incremental import (
_build_update_vector_store,
_rebuild_graph_and_git,
+ _refresh_knowledge_graph,
_run_partial_analysis,
)
from .mode import _infer_legacy_docs_enabled, _resolve_index_only_mode
@@ -585,6 +586,20 @@ def update_command(
drop_transient_git_signals(list(git_meta_map.values()))
+ # Refresh the knowledge graph (layers/tour/entry points) when the graph
+ # shape changed — previously init-only, so update served a stale
+ # orientation snapshot to CLAUDE.md/get_overview forever (#669). None
+ # means fingerprint-unchanged: the persisted artifact is still current.
+ knowledge_graph_result = _refresh_knowledge_graph(
+ repo_path,
+ parsed_files,
+ graph_builder,
+ repo_structure,
+ git_meta_map,
+ dead_code_report,
+ (state.get("knowledge_graph") or {}).get("fingerprint"),
+ )
+
if index_only:
if emitter is not None:
emitter.stage("persist")
@@ -600,6 +615,7 @@ def update_command(
start,
[fd.path for fd in file_diffs],
file_diffs=file_diffs,
+ knowledge_graph_result=knowledge_graph_result,
)
except Exception as exc:
if emitter is not None:
@@ -867,6 +883,28 @@ def update_command(
flush_cost_tracker(cost_tracker)
+ # LLM re-enrichment of the refreshed KG (layer naming + summary backfill
+ # from this run's regenerated pages), mirroring the init pipeline. Only
+ # runs when the graph shape changed — carry-forward already preserved the
+ # prior names, so an unchanged KG never pays an enrichment call.
+ if knowledge_graph_result is not None:
+ try:
+ from repowise.core.generation.knowledge_graph import enrich_knowledge_graph
+
+ knowledge_graph_result = run_async(
+ enrich_knowledge_graph(
+ kg_skeleton=knowledge_graph_result,
+ llm_client=provider,
+ graph_builder=graph_builder,
+ repo_structure=repo_structure,
+ tech_stack=knowledge_graph_result.project.get("tech_stack", []),
+ generated_pages=generated_pages,
+ reasoning=config.reasoning,
+ )
+ )
+ except Exception as exc:
+ console.print(f"[yellow]Knowledge-graph enrichment skipped: {exc}[/yellow]")
+
# Persist
async def _persist() -> None:
from repowise.cli.helpers import get_db_url_for_repo
@@ -903,6 +941,16 @@ def update_command(
if verbose:
console.print(f"[yellow]Tombstone marking skipped: {exc}[/yellow]")
+ # Refreshed knowledge graph — same writers as the init pipeline
+ # (full-replace layers/tour/curated meta).
+ if knowledge_graph_result is not None:
+ try:
+ from repowise.core.pipeline.persist import persist_kg
+
+ await persist_kg(knowledge_graph_result, session, repo_id)
+ except Exception as exc:
+ console.print(f"[yellow]Knowledge-graph persist skipped: {exc}[/yellow]")
+
# Persist updated git metadata + recompute percentiles
if git_meta_map:
try:
@@ -1095,6 +1143,15 @@ def update_command(
# Update state
from repowise.cli.helpers import config_fingerprint
+ if knowledge_graph_result is not None:
+ try:
+ from repowise.cli.state_persistence import build_kg_state, save_knowledge_graph_json
+
+ save_knowledge_graph_json(repo_path, knowledge_graph_result)
+ state["knowledge_graph"] = build_kg_state(knowledge_graph_result)
+ except Exception as exc:
+ console.print(f"[yellow]Knowledge-graph export skipped: {exc}[/yellow]")
+
state["last_sync_commit"] = head
state["total_pages"] = state.get("total_pages", 0) + len(generated_pages)
state["config_fingerprint"] = config_fingerprint(repo_path)
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/incremental.py b/packages/cli/src/repowise/cli/commands/update_cmd/incremental.py
index 2170d473a..3a72c476e 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/incremental.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/incremental.py
@@ -110,6 +110,37 @@ def _rebuild_graph_and_git(
)
+def _refresh_knowledge_graph(
+ repo_path: Any,
+ parsed_files: list,
+ graph_builder: Any,
+ repo_structure: Any,
+ git_meta_map: dict,
+ dead_code_report: Any,
+ prior_fingerprint: str | None,
+) -> Any | None:
+ """Rebuild the KG skeleton + curation when the graph shape changed.
+
+ Delegates to :mod:`repowise.core.pipeline.incremental`. Returns ``None``
+ when the graph fingerprint is unchanged (artifact already current) or the
+ rebuild failed (keep the prior artifact).
+ """
+ from repowise.core.pipeline.incremental import refresh_knowledge_graph
+
+ return run_async(
+ refresh_knowledge_graph(
+ repo_path,
+ parsed_files,
+ graph_builder,
+ repo_structure,
+ git_meta_map,
+ dead_code_report,
+ prior_fingerprint=prior_fingerprint,
+ log=console.print,
+ )
+ )
+
+
def _run_partial_analysis(
repo_path: Any,
graph_builder: Any,
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 fc924d946..54fa33cab 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
@@ -149,9 +149,10 @@ def _persist_index_only_update(
start: float,
changed_paths: list[str],
file_diffs: list | None = None,
+ knowledge_graph_result: Any | None = None,
) -> None:
- """Persist the index-only update (graph + git + dead-code + health), save
- state, and print the completion line. No LLM regeneration.
+ """Persist the index-only update (graph + git + dead-code + health + KG),
+ save state, and print the completion line. No LLM regeneration.
DB persistence delegates to :mod:`repowise.core.pipeline.incremental`;
state-file updates and console reporting stay here.
@@ -167,15 +168,26 @@ def _persist_index_only_update(
partial_health_report,
changed_paths,
file_diffs=file_diffs,
+ knowledge_graph_result=knowledge_graph_result,
log=console.print,
)
)
from repowise.cli.helpers import config_fingerprint
- save_state(
- repo_path,
- {**state, "last_sync_commit": head, "config_fingerprint": config_fingerprint(repo_path)},
- )
+ new_state = {
+ **state,
+ "last_sync_commit": head,
+ "config_fingerprint": config_fingerprint(repo_path),
+ }
+ if knowledge_graph_result is not None:
+ try:
+ from repowise.cli.state_persistence import build_kg_state, save_knowledge_graph_json
+
+ save_knowledge_graph_json(repo_path, knowledge_graph_result)
+ new_state["knowledge_graph"] = build_kg_state(knowledge_graph_result)
+ except Exception as exc:
+ console.print(f"[yellow]Knowledge-graph export skipped: {exc}[/yellow]")
+ save_state(repo_path, new_state)
elapsed = time.monotonic() - start
from .reporting import show_index_only_completion
diff --git a/packages/cli/src/repowise/cli/state_persistence.py b/packages/cli/src/repowise/cli/state_persistence.py
index 3b487311d..7eeb0434d 100644
--- a/packages/cli/src/repowise/cli/state_persistence.py
+++ b/packages/cli/src/repowise/cli/state_persistence.py
@@ -1,55 +1,13 @@
-"""Shared state.json / knowledge-graph persistence helpers for CLI commands."""
-
-from __future__ import annotations
-
-import logging
-from pathlib import Path
-from typing import Any
-
-
-def build_kg_state(kg: Any) -> dict[str, Any]:
- """Build the ``state.json`` ``knowledge_graph`` summary block for a KG result.
-
- Mirrors the summary the ``init`` / ``update`` flows persist so the web UI and
- subsequent runs can read KG size + fingerprint without loading the full graph.
- """
- return {
- "version": "1.0.0",
- "node_count": len(kg.nodes) if hasattr(kg, "nodes") else 0,
- "layer_count": len(kg.layers) if hasattr(kg, "layers") else 0,
- "tour_steps": len(kg.tour) if hasattr(kg, "tour") else 0,
- "has_summaries": any(n.get("summary") for n in kg.nodes) if hasattr(kg, "nodes") else False,
- "fingerprint": getattr(kg, "fingerprint", ""),
- }
+"""Shared state.json / knowledge-graph persistence helpers for CLI commands.
+The writers moved to :mod:`repowise.core.analysis.knowledge_graph` so the
+core incremental update path (including the workspace updater) can refresh
+the exported artifacts; re-exported here for the existing CLI imports.
+"""
-def save_knowledge_graph_json(repo_path: Path, kg: Any, *, portable: bool = False) -> None:
- """Write ``.repowise/knowledge-graph.json`` for a KG result.
-
- No-op when the result can't serialize itself (``to_dict`` missing), so
- callers only need to guard against a ``None`` knowledge graph.
-
- When ``portable`` is set, write the self-contained, self-validated artifact
- (curated layers + tour + entry points + summaries + a ``meta``/``validation``
- block) instead of the bare ``to_dict`` output. Hard invariant violations are
- logged but the artifact is still emitted, with the failures recorded under
- ``meta.validation`` so a consumer can see them ("repaired, not rejected").
- """
- if not hasattr(kg, "to_dict"):
- return
- import json
-
- if portable:
- from repowise.core.analysis.kg_curation import build_portable_kg
-
- data, validation = build_portable_kg(kg)
- if not validation.ok:
- logging.getLogger(__name__).warning(
- "portable KG failed invariants: %s", "; ".join(validation.errors)
- )
- else:
- data = kg.to_dict()
+from __future__ import annotations
- kg_json_path = repo_path / ".repowise" / "knowledge-graph.json"
- kg_json_path.parent.mkdir(parents=True, exist_ok=True)
- kg_json_path.write_text(json.dumps(data, indent=2), encoding="utf-8")
+from repowise.core.analysis.knowledge_graph import ( # noqa: F401
+ build_kg_state,
+ save_knowledge_graph_json,
+)
diff --git a/packages/core/src/repowise/core/analysis/knowledge_graph.py b/packages/core/src/repowise/core/analysis/knowledge_graph.py
index 573412076..d3815bd71 100644
--- a/packages/core/src/repowise/core/analysis/knowledge_graph.py
+++ b/packages/core/src/repowise/core/analysis/knowledge_graph.py
@@ -387,3 +387,60 @@ def _get_line_count(fi: Any) -> int:
if hasattr(fi, "size_bytes"):
return fi.size_bytes // 40
return 0
+
+
+# ---------------------------------------------------------------------------
+# Export helpers (state.json summary block + knowledge-graph.json artifact)
+# ---------------------------------------------------------------------------
+# Lived in ``repowise.cli.state_persistence`` until the incremental update
+# path (which includes the core workspace updater) started refreshing the KG;
+# core code can't import the CLI, so the writers live here and the CLI module
+# re-exports them.
+
+
+def build_kg_state(kg: Any) -> dict[str, Any]:
+ """Build the ``state.json`` ``knowledge_graph`` summary block for a KG result.
+
+ Mirrors the summary the ``init`` / ``update`` flows persist so the web UI and
+ subsequent runs can read KG size + fingerprint without loading the full graph.
+ """
+ return {
+ "version": "1.0.0",
+ "node_count": len(kg.nodes) if hasattr(kg, "nodes") else 0,
+ "layer_count": len(kg.layers) if hasattr(kg, "layers") else 0,
+ "tour_steps": len(kg.tour) if hasattr(kg, "tour") else 0,
+ "has_summaries": any(n.get("summary") for n in kg.nodes) if hasattr(kg, "nodes") else False,
+ "fingerprint": getattr(kg, "fingerprint", ""),
+ }
+
+
+def save_knowledge_graph_json(repo_path: Path, kg: Any, *, portable: bool = False) -> None:
+ """Write ``.repowise/knowledge-graph.json`` for a KG result.
+
+ No-op when the result can't serialize itself (``to_dict`` missing), so
+ callers only need to guard against a ``None`` knowledge graph.
+
+ When ``portable`` is set, write the self-contained, self-validated artifact
+ (curated layers + tour + entry points + summaries + a ``meta``/``validation``
+ block) instead of the bare ``to_dict`` output. Hard invariant violations are
+ logged but the artifact is still emitted, with the failures recorded under
+ ``meta.validation`` so a consumer can see them ("repaired, not rejected").
+ """
+ if not hasattr(kg, "to_dict"):
+ return
+ import logging
+
+ if portable:
+ from repowise.core.analysis.kg_curation import build_portable_kg
+
+ data, validation = build_portable_kg(kg)
+ if not validation.ok:
+ logging.getLogger(__name__).warning(
+ "portable KG failed invariants: %s", "; ".join(validation.errors)
+ )
+ else:
+ data = kg.to_dict()
+
+ kg_json_path = Path(repo_path) / ".repowise" / "knowledge-graph.json"
+ kg_json_path.parent.mkdir(parents=True, exist_ok=True)
+ kg_json_path.write_text(json.dumps(data, indent=2), encoding="utf-8")
diff --git a/packages/core/src/repowise/core/pipeline/incremental.py b/packages/core/src/repowise/core/pipeline/incremental.py
index be879aae8..87f6204f9 100644
--- a/packages/core/src/repowise/core/pipeline/incremental.py
+++ b/packages/core/src/repowise/core/pipeline/incremental.py
@@ -321,6 +321,138 @@ def run_partial_analysis(
return partial_health_report, dead_code_report
+async def refresh_knowledge_graph(
+ repo_path: Any,
+ parsed_files: list,
+ graph_builder: Any,
+ repo_structure: Any,
+ git_meta_map: dict,
+ dead_code_report: Any,
+ *,
+ prior_fingerprint: str | None,
+ log: LogFn | None = None,
+) -> Any | None:
+ """Rebuild the KG skeleton + curation when the graph shape changed.
+
+ The knowledge graph (layers, tour, entry points, curated node meta) was
+ historically rebuilt only by the full init pipeline, so every incremental
+ ``repowise update`` carried the init-time KG forward verbatim and agents
+ read a stale orientation snapshot (#669). This reruns the deterministic
+ skeleton + curation passes against the freshly rebuilt graph, then carries
+ forward the prior artifact's LLM-enriched layer names and node summaries
+ by stable id — so index-only updates stay LLM-free without regressing
+ enrichment. LLM re-enrichment stays with the caller (docs mode only).
+
+ Returns the refreshed result, or ``None`` when the graph fingerprint is
+ unchanged (the persisted artifact is already current) or the rebuild
+ failed (keep the prior artifact rather than export a broken one).
+ """
+ log = log or _noop_log
+ try:
+ from repowise.core.analysis.knowledge_graph import (
+ KnowledgeGraphResult,
+ build_knowledge_graph_skeleton,
+ compute_kg_fingerprint,
+ should_skip_kg_rebuild,
+ )
+
+ kg_json_path = Path(repo_path) / ".repowise" / "knowledge-graph.json"
+ new_fingerprint = compute_kg_fingerprint(graph_builder)
+ if should_skip_kg_rebuild(prior_fingerprint, new_fingerprint, kg_json_path):
+ return None
+
+ tech_stack: list[dict] = []
+ try:
+ from repowise.core.generation.editor_files.tech_stack import detect_tech_stack
+
+ tech_stack = [
+ {"name": t.name, "version": t.version, "category": t.category}
+ for t in detect_tech_stack(repo_path)
+ ]
+ except Exception:
+ pass # tech stack is contextual metadata, not structural
+
+ prior_kg = KnowledgeGraphResult.from_file(kg_json_path)
+
+ kg = build_knowledge_graph_skeleton(
+ parsed_files=parsed_files,
+ graph_builder=graph_builder,
+ repo_structure=repo_structure,
+ tech_stack=tech_stack,
+ external_systems=[],
+ git_meta_map=git_meta_map,
+ dead_code_report=dead_code_report,
+ repo_path=Path(repo_path),
+ )
+ kg.fingerprint = new_fingerprint
+
+ from repowise.core.analysis.kg_curation import (
+ apply_summary_floor,
+ curate_knowledge_graph,
+ curation_enabled,
+ )
+
+ kg = curate_knowledge_graph(
+ kg,
+ parsed_files=parsed_files,
+ graph_builder=graph_builder,
+ repo_structure=repo_structure,
+ community_info=graph_builder.community_info(),
+ git_meta_map=git_meta_map,
+ enabled=curation_enabled(),
+ # Floor after the prior-artifact carry-forward below so carried
+ # page-derived summaries win over the deterministic floor.
+ defer_summary_floor=True,
+ )
+
+ if prior_kg is not None:
+ _carry_forward_kg_enrichment(kg, prior_kg)
+
+ # Summaries degrade to empty on failure, same as the init-path seam.
+ import contextlib
+
+ with contextlib.suppress(Exception):
+ apply_summary_floor(kg, parsed_files)
+
+ log(
+ f"Knowledge graph refreshed: [cyan]{len(kg.layers)}[/cyan] layers, "
+ f"[cyan]{len(kg.tour)}[/cyan] tour steps"
+ )
+ return kg
+ except Exception as exc:
+ log(f"[yellow]Knowledge-graph refresh skipped: {exc}[/yellow]")
+ return None
+
+
+def _carry_forward_kg_enrichment(kg: Any, prior_kg: Any) -> None:
+ """Adopt the prior artifact's LLM-enriched prose onto the rebuilt KG.
+
+ Matching is by stable id, and only fields the deterministic passes left
+ empty are filled — structural changes always win over stale prose. Layer
+ descriptions exist only after LLM enrichment (curation names layers but
+ leaves descriptions empty), so a non-empty prior description is the
+ signal that the prior name/description pair is the enriched one.
+ """
+ prior_layers = {layer.get("id"): layer for layer in prior_kg.layers or []}
+ for layer in kg.layers or []:
+ prior = prior_layers.get(layer.get("id"))
+ if prior and prior.get("description") and not layer.get("description"):
+ layer["name"] = prior.get("name") or layer.get("name")
+ layer["description"] = prior["description"]
+
+ prior_summaries = {n.get("id"): n["summary"] for n in prior_kg.nodes or [] if n.get("summary")}
+ for node in kg.nodes or []:
+ if not node.get("summary"):
+ prior_summary = prior_summaries.get(node.get("id"))
+ if prior_summary:
+ node["summary"] = prior_summary
+
+ # With curation disabled the skeleton carries no tour and only the LLM
+ # path builds one — keep the prior tour rather than exporting none.
+ if not kg.tour and prior_kg.tour:
+ kg.tour = prior_kg.tour
+
+
async def persist_partial_health(session: Any, repo_id: str, report: Any) -> None:
"""Upsert health findings + metrics for the changed-files subset.
@@ -405,6 +537,7 @@ async def persist_incremental_index(
*,
current_graph_file_paths: set[str] | None = None,
file_diffs: list[Any] | None = None,
+ knowledge_graph_result: Any | None = None,
log: LogFn | None = None,
) -> None:
"""Persist an incremental index refresh (graph + git + dead-code + health).
@@ -438,9 +571,7 @@ async def persist_incremental_index(
try:
from repowise.core.pipeline.persist import _prune_stale_file_rows
- await _prune_stale_file_rows(
- session, repo_id, current_graph_file_paths, set()
- )
+ await _prune_stale_file_rows(session, repo_id, current_graph_file_paths, set())
except Exception as exc:
log(f"[yellow]Stale row prune skipped: {exc}[/yellow]")
@@ -505,5 +636,13 @@ async def persist_incremental_index(
await persist_graph_nodes(session, repo_id, graph_builder)
except Exception as exc:
log(f"[yellow]Graph nodes persist skipped: {exc}[/yellow]")
+
+ if knowledge_graph_result is not None:
+ try:
+ from repowise.core.pipeline.persist import persist_kg
+
+ await persist_kg(knowledge_graph_result, session, repo_id)
+ except Exception as exc:
+ log(f"[yellow]Knowledge-graph persist skipped: {exc}[/yellow]")
finally:
await engine.dispose()
diff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.py
index fe3c8cb1a..2adb2957c 100644
--- a/packages/core/src/repowise/core/pipeline/persist.py
+++ b/packages/core/src/repowise/core/pipeline/persist.py
@@ -685,35 +685,45 @@ async def persist_generation(result: Any, session: Any, repo_id: str) -> None:
# ---- Knowledge graph layers, tour steps & curated meta ------------------
kg = getattr(result, "knowledge_graph_result", None)
if kg is not None:
- from repowise.core.persistence.crud import (
- file_node_meta_from_kg_nodes,
- upsert_kg_layers,
- upsert_kg_node_meta,
- upsert_kg_project_meta,
- upsert_kg_tour_steps,
- )
+ await persist_kg(kg, session, repo_id)
- if hasattr(kg, "layers") and kg.layers:
- await upsert_kg_layers(session, repo_id, kg.layers)
- if hasattr(kg, "tour") and kg.tour:
- await upsert_kg_tour_steps(session, repo_id, kg.tour)
- # Project-level curated meta (ranked entry points from the curation pass).
- project = getattr(kg, "project", None)
- if isinstance(project, dict) and project.get("entry_points"):
- await upsert_kg_project_meta(
- session,
- repo_id,
- entry_points=project["entry_points"],
- entry_candidates=project.get("entry_candidates", []),
- )
+async def persist_kg(kg: Any, session: Any, repo_id: str) -> None:
+ """Persist knowledge-graph layers, tour steps, and curated meta.
+
+ Full-replace semantics, safe to call incrementally — shared by the full
+ pipeline (:func:`persist_generation`) and the incremental update path so
+ a refreshed KG lands through the same writers.
+ """
+ from repowise.core.persistence.crud import (
+ file_node_meta_from_kg_nodes,
+ upsert_kg_layers,
+ upsert_kg_node_meta,
+ upsert_kg_project_meta,
+ upsert_kg_tour_steps,
+ )
+
+ if hasattr(kg, "layers") and kg.layers:
+ await upsert_kg_layers(session, repo_id, kg.layers)
+ if hasattr(kg, "tour") and kg.tour:
+ await upsert_kg_tour_steps(session, repo_id, kg.tour)
+
+ # Project-level curated meta (ranked entry points from the curation pass).
+ project = getattr(kg, "project", None)
+ if isinstance(project, dict) and project.get("entry_points"):
+ await upsert_kg_project_meta(
+ session,
+ repo_id,
+ entry_points=project["entry_points"],
+ entry_candidates=project.get("entry_candidates", []),
+ )
- # Per-node curated meta (type/summary/tags) for file nodes, stored with
- # the "file:" prefix stripped so the architecture view can match its
- # node ids (plain repo-relative paths) directly.
- file_node_meta = file_node_meta_from_kg_nodes(getattr(kg, "nodes", None) or [])
- if file_node_meta:
- await upsert_kg_node_meta(session, repo_id, file_node_meta)
+ # Per-node curated meta (type/summary/tags) for file nodes, stored with
+ # the "file:" prefix stripped so the architecture view can match its
+ # node ids (plain repo-relative paths) directly.
+ file_node_meta = file_node_meta_from_kg_nodes(getattr(kg, "nodes", None) or [])
+ if file_node_meta:
+ await upsert_kg_node_meta(session, repo_id, file_node_meta)
async def persist_pipeline_result(
diff --git a/packages/core/src/repowise/core/workspace/update.py b/packages/core/src/repowise/core/workspace/update.py
index f09f841dc..643181f79 100644
--- a/packages/core/src/repowise/core/workspace/update.py
+++ b/packages/core/src/repowise/core/workspace/update.py
@@ -147,6 +147,10 @@ class RepoUpdateResult:
symbol_count: int = 0
error: str | None = None
first_time_indexed: bool = False # True if this run was a first-time index
+ # state.json "knowledge_graph" summary block when this run refreshed the
+ # KG; None means the persisted block is still current. State-file writes
+ # stay with the caller (_update_one), so the block rides on the result.
+ kg_state: dict[str, Any] | None = None
# ---------------------------------------------------------------------------
@@ -362,6 +366,7 @@ async def _incremental_repo_update(
run_partial_analysis,
)
from ..pipeline.phases.git import drop_transient_git_signals
+
alias = repo_path.name
head = get_head_commit(repo_path) or "HEAD"
@@ -417,6 +422,22 @@ async def _incremental_repo_update(
# object can never leak downstream (mirrors the CLI update path).
drop_transient_git_signals(list(git_meta_map.values()))
+ # Refresh the knowledge graph (layers/tour/entry points) when the graph
+ # shape changed — previously init-only, so workspace member repos served
+ # a stale orientation snapshot forever (#669).
+ from ..pipeline.incremental import refresh_knowledge_graph
+
+ kg = await refresh_knowledge_graph(
+ repo_path,
+ parsed_files,
+ graph_builder,
+ _structure,
+ git_meta_map,
+ dead_code_report,
+ prior_fingerprint=(state.get("knowledge_graph") or {}).get("fingerprint"),
+ log=_log.info,
+ )
+
await persist_incremental_index(
repo_path,
graph_builder,
@@ -425,14 +446,26 @@ async def _incremental_repo_update(
partial_health_report,
[fd.path for fd in file_diffs],
current_graph_file_paths={pf.file_info.path for pf in parsed_files},
+ knowledge_graph_result=kg,
log=_log.info,
)
+ kg_state: dict[str, Any] | None = None
+ if kg is not None:
+ from ..analysis.knowledge_graph import build_kg_state, save_knowledge_graph_json
+
+ try:
+ save_knowledge_graph_json(repo_path, kg)
+ kg_state = build_kg_state(kg)
+ except Exception:
+ _log.warning("knowledge-graph.json export failed for %s", alias, exc_info=True)
+
return RepoUpdateResult(
alias=alias,
updated=True,
file_count=file_count,
symbol_count=sum(len(pf.symbols) for pf in parsed_files),
+ kg_state=kg_state,
)
@@ -516,11 +549,26 @@ async def update_single_repo_index(
await engine.dispose()
+ # Export the pipeline's freshly built KG so the artifact matches the
+ # rows just persisted — the workspace add path already does this; the
+ # update-triggered full index previously skipped it.
+ kg_state: dict[str, Any] | None = None
+ kg = getattr(result, "knowledge_graph_result", None)
+ if kg is not None:
+ from ..analysis.knowledge_graph import build_kg_state, save_knowledge_graph_json
+
+ try:
+ save_knowledge_graph_json(repo_path, kg)
+ kg_state = build_kg_state(kg)
+ except Exception:
+ _log.warning("knowledge-graph.json export failed for %s", alias, exc_info=True)
+
return RepoUpdateResult(
alias=alias,
updated=True,
file_count=result.file_count,
symbol_count=result.symbol_count,
+ kg_state=kg_state,
)
except Exception as exc:
return RepoUpdateResult(
@@ -607,7 +655,8 @@ async def update_workspace(
pass
is_stale, current_head, _commits_behind = check_repo_staleness(
- abs_path, stored_commit,
+ abs_path,
+ stored_commit,
)
if not is_stale:
@@ -667,9 +716,7 @@ async def update_workspace(
)
# Record pending so the running update can roll forward.
with suppress(OSError):
- (path / ".repowise" / ".update.pending").write_text(
- new_head, encoding="utf-8"
- )
+ (path / ".repowise" / ".update.pending").write_text(new_head, encoding="utf-8")
return RepoUpdateResult(
alias=alias,
updated=False,
@@ -698,6 +745,8 @@ async def update_workspace(
with suppress(Exception):
state = _json.loads(state_path.read_text(encoding="utf-8"))
state["last_sync_commit"] = new_head
+ if result.kg_state:
+ state["knowledge_graph"] = result.kg_state
# Mark first-time so downstream tooling (status, doctor) can
# distinguish a never-indexed repo from one that's been
# updated at least once.
diff --git a/tests/unit/pipeline/test_kg_refresh.py b/tests/unit/pipeline/test_kg_refresh.py
new file mode 100644
index 000000000..37606e7f0
--- /dev/null
+++ b/tests/unit/pipeline/test_kg_refresh.py
@@ -0,0 +1,183 @@
+"""Tests for the incremental knowledge-graph refresh (#669).
+
+``repowise update`` must rebuild the KG skeleton + curation when the graph
+shape changed, skip the rebuild when the fingerprint is unchanged, and carry
+forward the prior artifact's LLM-enriched prose instead of paying an LLM call
+on index-only runs.
+"""
+
+from __future__ import annotations
+
+import json
+import sys
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).parent.parent / "analysis"))
+from kg_fixtures import build_repo
+
+from repowise.core.analysis.knowledge_graph import (
+ KnowledgeGraphResult,
+ compute_kg_fingerprint,
+)
+from repowise.core.pipeline.incremental import (
+ _carry_forward_kg_enrichment,
+ refresh_knowledge_graph,
+)
+
+
+def _repo():
+ return build_repo(
+ ["src/a.py", "src/b.py", "src/main.py", "tests/test_a.py"],
+ tests={"tests/test_a.py"},
+ entries={"src/main.py"},
+ edges=[("src/main.py", "src/a.py"), ("src/a.py", "src/b.py")],
+ )
+
+
+def _write_kg_json(repo_path: Path, data: dict) -> Path:
+ kg_path = repo_path / ".repowise" / "knowledge-graph.json"
+ kg_path.parent.mkdir(parents=True, exist_ok=True)
+ kg_path.write_text(json.dumps(data), encoding="utf-8")
+ return kg_path
+
+
+async def test_skips_when_fingerprint_unchanged(tmp_path):
+ repo = _repo()
+ fp = compute_kg_fingerprint(repo.builder)
+ _write_kg_json(tmp_path, {"nodes": [], "layers": [], "tour": []})
+
+ result = await refresh_knowledge_graph(
+ tmp_path,
+ repo.parsed,
+ repo.builder,
+ repo.repo_structure,
+ {},
+ None,
+ prior_fingerprint=fp,
+ )
+
+ assert result is None
+
+
+async def test_rebuilds_when_fingerprint_changed(tmp_path):
+ repo = _repo()
+ _write_kg_json(tmp_path, {"nodes": [], "layers": [], "tour": []})
+
+ result = await refresh_knowledge_graph(
+ tmp_path,
+ repo.parsed,
+ repo.builder,
+ repo.repo_structure,
+ {},
+ None,
+ prior_fingerprint="0000000000000000",
+ )
+
+ assert result is not None
+ assert result.fingerprint == compute_kg_fingerprint(repo.builder)
+ assert result.layers
+ assert any(n["id"] == "file:src/main.py" for n in result.nodes)
+
+
+async def test_rebuilds_when_no_prior_fingerprint(tmp_path):
+ repo = _repo()
+
+ result = await refresh_knowledge_graph(
+ tmp_path,
+ repo.parsed,
+ repo.builder,
+ repo.repo_structure,
+ {},
+ None,
+ prior_fingerprint=None,
+ )
+
+ assert result is not None
+ assert result.layers
+
+
+async def test_prior_summaries_carried_via_artifact(tmp_path):
+ repo = _repo()
+ _write_kg_json(
+ tmp_path,
+ {
+ "nodes": [{"id": "file:src/a.py", "summary": "Rich page-derived summary for a."}],
+ "layers": [],
+ "tour": [],
+ },
+ )
+
+ result = await refresh_knowledge_graph(
+ tmp_path,
+ repo.parsed,
+ repo.builder,
+ repo.repo_structure,
+ {},
+ None,
+ prior_fingerprint=None,
+ )
+
+ assert result is not None
+ node = next(n for n in result.nodes if n["id"] == "file:src/a.py")
+ assert node["summary"] == "Rich page-derived summary for a."
+
+
+def test_carry_forward_layer_names_and_tour():
+ kg = KnowledgeGraphResult(
+ nodes=[{"id": "file:src/a.py", "summary": ""}],
+ layers=[
+ {"id": "layer:core", "name": "core", "description": ""},
+ {"id": "layer:new", "name": "new", "description": ""},
+ ],
+ tour=[],
+ )
+ prior = KnowledgeGraphResult(
+ nodes=[{"id": "file:src/a.py", "summary": "Prior summary."}],
+ layers=[
+ {
+ "id": "layer:core",
+ "name": "Core Engine",
+ "description": "The ingestion and analysis engine.",
+ },
+ # No description → deterministic-only, must NOT be carried.
+ {"id": "layer:new", "name": "Renamed Without Enrichment", "description": ""},
+ {"id": "layer:gone", "name": "Removed", "description": "Stale."},
+ ],
+ tour=[{"step": 1, "nodeId": "file:src/a.py"}],
+ )
+
+ _carry_forward_kg_enrichment(kg, prior)
+
+ core = next(layer for layer in kg.layers if layer["id"] == "layer:core")
+ assert core["name"] == "Core Engine"
+ assert core["description"] == "The ingestion and analysis engine."
+ new = next(layer for layer in kg.layers if layer["id"] == "layer:new")
+ assert new["name"] == "new" # structural rename wins over stale prose
+ assert kg.nodes[0]["summary"] == "Prior summary."
+ assert kg.tour == prior.tour # empty tour adopts the prior one
+
+
+def test_carry_forward_never_overwrites_fresh_fields():
+ kg = KnowledgeGraphResult(
+ nodes=[{"id": "file:src/a.py", "summary": "Fresh summary."}],
+ layers=[{"id": "layer:core", "name": "core", "description": "Fresh description."}],
+ tour=[{"step": 1, "nodeId": "file:src/a.py"}],
+ )
+ prior = KnowledgeGraphResult(
+ nodes=[{"id": "file:src/a.py", "summary": "Old."}],
+ layers=[{"id": "layer:core", "name": "Old Name", "description": "Old."}],
+ tour=[{"step": 1, "nodeId": "file:src/b.py"}],
+ )
+
+ _carry_forward_kg_enrichment(kg, prior)
+
+ assert kg.layers[0]["name"] == "core"
+ assert kg.layers[0]["description"] == "Fresh description."
+ assert kg.nodes[0]["summary"] == "Fresh summary."
+ assert kg.tour[0]["nodeId"] == "file:src/a.py"