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.

refactor(workspace): split workspace update into an update package (#4038)

Raghav Chamadiyacfb9e65815bb
diff --git a/packages/core/src/repowise/core/workspace/update.py b/packages/core/src/repowise/core/workspace/update.py
deleted file mode 100644
index 7cb9dd45e..000000000
--- a/packages/core/src/repowise/core/workspace/update.py
+++ /dev/null
@@ -1,1681 +0,0 @@
-"""Workspace-level update orchestration.
-
-Handles staleness detection, parallel multi-repo updates, and cross-repo
-analysis hooks (Phase 3).
-"""
-
-from __future__ import annotations
-
-import asyncio
-import json as _json
-import logging
-import sqlite3
-import subprocess
-import time
-from collections.abc import Awaitable, Callable
-from contextlib import suppress
-from dataclasses import dataclass
-from datetime import UTC, datetime
-from pathlib import Path
-from typing import TYPE_CHECKING, Any, NamedTuple
-
-if TYPE_CHECKING:
- from repowise.core.workspace.contracts import ContractStore
- from repowise.core.workspace.cross_repo import CrossRepoOverlay
- from repowise.core.workspace.extractors.service_boundary import ServiceBoundary
- from repowise.core.workspace.repo_index import WorkspaceIndex
- from repowise.core.workspace.system_graph import SystemGraph
-
-# Per-repo update lock — the shared single-flight guard (one implementation
-# for the CLI update command and this workspace updater, which used to carry
-# a hand-synced copy). ``update_single_repo_index`` calls these directly,
-# bypassing the CLI lock acquisition in update_cmd, so workspace updates are
-# themselves single-flight per repo.
-from repowise.core.update_lock import (
- lock_age_seconds as _lock_age_seconds,
-)
-from repowise.core.update_lock import (
- release_update_lock as _release_lock,
-)
-from repowise.core.update_lock import (
- release_workspace_lock as _release_workspace_lock,
-)
-from repowise.core.update_lock import (
- try_acquire_update_lock as _try_acquire_lock,
-)
-from repowise.core.update_lock import (
- update_workspace_lock as _try_acquire_workspace_lock,
-)
-
-from ..docs_mode import docs_mode_state_fields
-from ..ingestion.change_detector import has_working_tree_changes
-from ..ingestion.git_indexer import (
- GIT_HISTORY_VERSION,
- GIT_HISTORY_VERSION_KEY,
- git_history_stale,
-)
-from ..ingestion.git_indexer._constants import _DEFAULT_COMMIT_LIMIT
-from ..pipeline.phase_timing import PhaseTimingRecorder
-from .config import RepoEntry, WorkspaceConfig
-
-_log = logging.getLogger("repowise.workspace.update")
-
-
-async def _merged_repo_excludes(
- repo_path: Path,
- extra_exclude_patterns: list[str] | None = None,
-) -> list[str]:
- """Merge config.yaml excludes with the persisted repo settings' excludes.
-
- Local SQLite indexes store ``settings_json`` in the repo-local
- ``wiki.db``, read directly since this call is on the hot per-update path
- and a raw sqlite3 read is cheaper than opening an engine for one row.
- When a shared database is configured, that DB is the source of truth
- instead — reading only ``config.yaml`` there would silently drop every
- pattern the user added through the shared repository's settings, so
- every workspace update would run with a narrower exclude set than the
- repo was actually indexed with.
- """
- from ..repo_config import load_repo_config
-
- patterns: list[str] = list(load_repo_config(repo_path).get("exclude_patterns") or [])
-
- from ..persistence.database import get_configured_db_url
-
- configured_url = get_configured_db_url()
- settings_json: str | None = None
-
- if configured_url is None:
- db_path = repo_path / ".repowise" / "wiki.db"
- if db_path.is_file():
- try:
- with sqlite3.connect(str(db_path)) as conn:
- row = conn.execute("SELECT settings_json FROM repositories LIMIT 1").fetchone()
- if row and row[0]:
- settings_json = row[0]
- except Exception:
- pass
- else:
- from ..persistence import (
- create_engine,
- create_session_factory,
- get_session,
- init_db,
- )
- from ..persistence.crud import get_repository_by_path
-
- try:
- engine = create_engine(configured_url)
- try:
- await init_db(engine)
- sf = create_session_factory(engine)
- async with get_session(sf) as session:
- repo = await get_repository_by_path(session, str(repo_path))
- if repo is not None and repo.settings_json:
- settings_json = repo.settings_json
- finally:
- await engine.dispose()
- except Exception:
- pass
-
- if settings_json:
- try:
- settings = _json.loads(settings_json)
- if isinstance(settings, dict):
- for value in settings.get("exclude_patterns") or []:
- if isinstance(value, str) and value not in patterns:
- patterns.append(value)
- except Exception:
- pass
-
- for pattern in extra_exclude_patterns or []:
- if pattern not in patterns:
- patterns.append(pattern)
- return patterns
-
-
-# ---------------------------------------------------------------------------
-# Data models
-# ---------------------------------------------------------------------------
-
-
-@dataclass
-class RepoUpdateResult:
- """Result of updating a single repo within a workspace."""
-
- alias: str
- updated: bool # True if an update was performed
- skipped_reason: str | None = None # "up_to_date", "missing_directory", etc.
- # How long the winning update had held the lock, when this repo deferred to
- # one. Carried on the result because the caller reports the deferral and
- # the age is the part that tells a slow update apart from a wedged one.
- lock_age_seconds: float | None = None
- file_count: int = 0
- 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
- # Repo-relative paths this run indexed from the working tree rather than
- # from a commit. Persisted as state.json "working_tree_paths" so the next
- # run can tell which of them have since been reverted or deleted — working
- # tree state has no ``last_sync_commit`` to diff against. None on the
- # commit-anchored path, which leaves the stored list alone.
- working_tree_paths: list[str] | None = None
- phase_timings: dict[str, float] | None = None
- # True when this run walked the whole git history and persisted every row,
- # so the caller stamps ``git_history_version``.
- git_history_refreshed: bool = False
-
-
-# ---------------------------------------------------------------------------
-# Staleness detection
-# ---------------------------------------------------------------------------
-
-
-def get_head_commit(repo_path: Path) -> str | None:
- """Return the current HEAD commit SHA via git, or ``None``."""
- try:
- result = subprocess.run(
- ["git", "rev-parse", "HEAD"],
- cwd=str(repo_path),
- capture_output=True,
- text=True,
- timeout=10,
- )
- if result.returncode == 0:
- return result.stdout.strip()
- except Exception:
- pass
- return None
-
-
-def count_commits_between(repo_path: Path, base: str, head: str) -> int:
- """Return the number of commits between *base* and *head*, or 0 on error."""
- try:
- result = subprocess.run(
- ["git", "rev-list", "--count", f"{base}..{head}"],
- cwd=str(repo_path),
- capture_output=True,
- text=True,
- timeout=10,
- )
- if result.returncode == 0:
- return int(result.stdout.strip())
- except Exception:
- pass
- return 0
-
-
-def commit_exists(repo_path: Path, sha: str) -> bool:
- """Return True when *sha* resolves to a commit in *repo_path*.
-
- The incremental path must verify this itself: ``ChangeDetector`` returns
- an **empty** diff for unresolvable refs, which would masquerade as "no
- changes" and let the caller bump ``last_sync_commit`` past commits that
- were never indexed (e.g. after a rebase or an aggressive ``git gc``).
- """
- try:
- result = subprocess.run(
- ["git", "cat-file", "-e", f"{sha}^{{commit}}"],
- cwd=str(repo_path),
- capture_output=True,
- timeout=10,
- )
- return result.returncode == 0
- except Exception:
- return False
-
-
-def clear_stale_update_pending(repo_path: Path, indexed_head: str | None) -> None:
- """Drop ``.repowise/.update.pending`` once the index has caught up to it.
-
- The core in-flight bail (:func:`_update_one`) records the latest HEAD in
- this marker, mirroring the CLI's ``write_update_pending``. The update that
- holds the lock calls this on success: the marker is kept only when it
- points to a commit strictly *ahead* of ``indexed_head`` (a newer commit not
- yet indexed). Equal, ancestor, and no-longer-resolvable commits (rebased or
- gc'd away) are cleared, so a bailed core update never leaves the marker
- behind forever — the symmetric half of the CLI ``consume_update_pending``
- fix.
- """
- pending_path = repo_path / ".repowise" / ".update.pending"
- try:
- pending_head = pending_path.read_text(encoding="utf-8").strip()
- except OSError:
- return
- if pending_head and indexed_head and pending_head != indexed_head:
- try:
- # indexed_head is an ancestor of pending_head => strictly ahead,
- # keep it. Non-zero (incl. unresolvable pending) => safe to clear.
- ahead = subprocess.run(
- ["git", "merge-base", "--is-ancestor", indexed_head, pending_head],
- cwd=str(repo_path),
- capture_output=True,
- timeout=10,
- )
- if ahead.returncode == 0:
- return
- except Exception:
- pass
- with suppress(OSError):
- pending_path.unlink(missing_ok=True)
-
-
-def read_repo_state(repo_path: Path) -> dict[str, Any]:
- """Return the parsed ``<repo>/.repowise/state.json``, or ``{}``."""
- state_path = repo_path / ".repowise" / "state.json"
- if not state_path.is_file():
- return {}
- try:
- data = _json.loads(state_path.read_text(encoding="utf-8"))
- return data if isinstance(data, dict) else {}
- except Exception:
- return {}
-
-
-def read_state_commit(repo_path: Path) -> str | None:
- """Return ``last_sync_commit`` from ``<repo>/.repowise/state.json`` or None."""
- sha = read_repo_state(repo_path).get("last_sync_commit")
- return str(sha) if sha else None
-
-
-class IndexedCommit(NamedTuple):
- """The commit an index describes, or why it cannot be named."""
-
- sha: str | None
- problem: str | None = None
-
-
-def resolve_indexed_commit(repo_path: Path | None, row_commit: str | None) -> IndexedCommit:
- """The commit the index describes, from ``state.json`` and the repository row.
-
- Every update writes both from one captured head, so they normally agree.
- When one is an ancestor of the other (an update interrupted between the
- two writes, or a row an older build left behind), the index describes the
- older: the files between them then count as changed since the index was
- built, which over-selects rather than misses. Two commits neither of which
- contains the other (a rebase, a restored backup), or a sha git cannot
- read, leave the commit unknown.
- """
- state = read_state_commit(repo_path) if repo_path is not None else None
- if not state or not row_commit or state == row_commit:
- return IndexedCommit(state or row_commit)
- older = _older_commit(str(repo_path), state, row_commit)
- if older is not None:
- return IndexedCommit(older)
- return IndexedCommit(
- None,
- f"The index records two commits ({state[:7]} in state.json, {row_commit[:7]} "
- "in its database) and neither contains the other, so what it describes is "
- "unknown; run `repowise update`.",
- )
-
-
-# (repo_path, a, b) -> the older commit, or None when neither contains the
-# other. Only definite answers: a timeout or an unknown sha is asked again.
-_ancestry_cache: dict[tuple[str, str, str], str | None] = {}
-_ANCESTRY_CACHE_MAX = 32
-
-
-def _older_commit(repo_path: str, a: str, b: str) -> str | None:
- """The one of *a*, *b* that is an ancestor of the other, else ``None``.
-
- Cached because the freshness envelope asks on every response while the two
- stamps disagree. Ancestry between two known shas never changes, and the
- next update makes the stamps equal, which ends the asking.
- """
- from ..git_refs import is_ancestor
-
- key = (repo_path, a, b)
- if key in _ancestry_cache:
- return _ancestry_cache[key]
- a_first = is_ancestor(repo_path, a, b)
- b_first = None if a_first else is_ancestor(repo_path, b, a)
- older = a if a_first else b if b_first else None
- if older is not None or (a_first is False and b_first is False):
- if len(_ancestry_cache) >= _ANCESTRY_CACHE_MAX:
- _ancestry_cache.clear()
- _ancestry_cache[key] = older
- return older
-
-
-def sync_workspace_state_from_disk(
- workspace_root: Path,
- ws_config: WorkspaceConfig,
- *,
- save_if_changed: bool = True,
-) -> list[str]:
- """Refresh ``WorkspaceConfig`` entries from each repo's on-disk
- ``state.json``.
-
- A child repo can be updated outside the workspace orchestrator (the
- user runs ``repowise update`` inside the child dir directly), which
- drifts ``RepoEntry.last_commit_at_index`` away from the actual
- ``state.json`` value. Call this before any workspace-level decision
- that reads from ``ws_config`` so we never act on stale info.
-
- Returns the list of aliases that changed.
- """
- changed: list[str] = []
- for entry in ws_config.repos:
- abs_path = (workspace_root / entry.path).resolve()
- if not abs_path.is_dir():
- continue
- disk_commit = read_state_commit(abs_path)
- if disk_commit is not None and disk_commit != entry.last_commit_at_index:
- entry.last_commit_at_index = disk_commit
- changed.append(entry.alias)
- if changed and save_if_changed:
- try:
- ws_config.save(workspace_root)
- except Exception:
- # Saving is best-effort — the in-memory sync still happened.
- _log.warning("Could not persist synced workspace config", exc_info=True)
- return changed
-
-
-def check_repo_staleness(
- repo_path: Path,
- last_commit: str | None,
-) -> tuple[bool, str | None, int]:
- """Check if a repo has new commits since *last_commit*.
-
- Returns ``(is_stale, current_head, commits_behind)``.
- """
- current_head = get_head_commit(repo_path)
- if current_head is None:
- return False, None, 0
-
- if last_commit is None:
- # Never indexed — treat as stale
- return True, current_head, 0
-
- if current_head == last_commit:
- # Same reconciliation as the single-repo update: a page can be stale
- # with HEAD unmoved, and only an update clears it.
- try:
- from repowise.core.persistence import load_stale_structural_file_paths
-
- if load_stale_structural_file_paths(repo_path):
- return True, current_head, 0
- except Exception:
- _log.debug("stale page probe failed for %s", repo_path, exc_info=True)
- return False, current_head, 0
-
- behind = count_commits_between(repo_path, last_commit, current_head)
- return True, current_head, behind
-
-
-def restamp_changed_sync_commit(repo_path: Path, previous: str | None, current: str | None) -> None:
- """Move the repository row to a ``last_sync_commit`` a state write just changed.
-
- The CLI and server state writers call this (the workspace updater awaits
- :func:`reconcile_repo_head_commit` itself), so a path that advances the
- sync commit leaves the row on the same commit, whatever HEAD its persist
- step read (a pull during a long run moves it). An unchanged commit is left
- alone: the "up to date" paths stamp it themselves. The state file is
- already written, so a failure here is logged, not raised.
- """
- if not current or current == previous:
- return
-
- try:
- asyncio.get_running_loop()
- except RuntimeError:
- pass
- else:
- # Ceiling: callers must be off-loop; skipped here, the resolver still
- # reads the ancestor pair this leaves correctly.
- _log.warning("Skipped the repository row restamp for %s: called on an event loop", repo_path)
- return
- try:
- asyncio.run(reconcile_repo_head_commit(repo_path, current))
- except Exception:
- _log.warning("Could not restamp the repository row for %s", repo_path, exc_info=True)
-
-
-async def reconcile_repo_head_commit(repo_path: Path, head: str | None) -> None:
- """Advance the DB freshness for *repo_path* after a sync-check to *head*.
-
- The "up to date" skip and the no-relevant-changes incremental path bump
- ``state.json``'s ``last_sync_commit`` but never re-run the DB persistence
- that stamps the ``repositories`` row. The server reads both the indexed
- commit (``/api/repos``, MCP ``_meta``) and the "indexed at" time (the health
- overview's ``last_indexed_at`` fallback) from that row, not from
- ``state.json`` — so an un-reconciled row keeps the "index behind checkout"
- signal stuck and the freshness timestamp frozen at the last full index even
- after a successful update.
-
- Stamps ``head_commit`` only on drift (avoids needless churn), but always
- advances ``updated_at`` so the freshness time reflects the latest
- sync-check — a routine ``repowise update`` that finds nothing to do still
- counts as "verified current now". Creates the row when it is missing from
- an existing store (self-heals a corrupt/blank store — the policy the CLI's
- ``stamp_head_commit``, now a thin wrapper over this, always had); still a
- no-op when no store exists at all, so a stamp can never conjure an empty
- database. A configured database counts as existing: it is shared, and the
- repo-local file it replaces is absent by design, so gating on the file
- alone skipped every stamp under one.
-
- This is the single head-commit stamper for both update paths — the CLI
- fast paths and the workspace updater used to run two implementations with
- different creation semantics.
- """
- from ..persistence.database import has_db_store, resolve_db_url
-
- if not head or not has_db_store(repo_path):
- return
-
- from ..persistence import (
- create_engine,
- create_session_factory,
- get_session,
- init_db,
- upsert_repository,
- )
- from ..persistence.crud import get_repository_by_path
-
- url = resolve_db_url(repo_path)
- engine = create_engine(url)
- try:
- await init_db(engine)
- sf = create_session_factory(engine)
- async with get_session(sf) as session:
- repo = await get_repository_by_path(session, str(repo_path))
- if repo is None:
- await upsert_repository(
- session,
- name=repo_path.name,
- local_path=str(repo_path),
- head_commit=head,
- )
- else:
- if repo.head_commit != head:
- repo.head_commit = head
- repo.updated_at = datetime.now(UTC)
- await session.flush()
- finally:
- await engine.dispose()
-
-
-# ---------------------------------------------------------------------------
-# Single-repo update (index-only)
-# ---------------------------------------------------------------------------
-
-
-async def _incremental_repo_update(
- repo_path: Path,
- *,
- state: dict[str, Any],
- base_ref: str,
- exclude_patterns: list[str] | None = None,
- include_working_tree: bool = False,
- force_full_git: bool = False,
-) -> RepoUpdateResult | None:
- """Refresh an already-indexed repo through the incremental update path.
-
- Mirrors the single-repo ``repowise update --index-only`` flow: diff
- ``base_ref..HEAD``, rebuild the graph (parse-cache backed), re-index git
- metadata for the changed files only, run partial health/dead-code
- analysis, and upsert the results. Deletions and renames are handled the
- same way the single-repo path handles them — stale rows are pruned
- against the rebuilt graph and pages for removed files are tombstoned —
- instead of the old bail-out to a full re-index. State-file updates stay
- with the caller (``update_workspace``'s ``_update_one``).
-
- Raises on failure — the caller falls back to the full pipeline.
- """
- from ..ingestion.change_detector import ChangeDetector, merge_file_diffs
- from ..pipeline.incremental import (
- DocDriftUpdate,
- persist_incremental_index,
- rebuild_graph_and_git,
- run_doc_drift_partial,
- run_partial_analysis,
- )
- from ..pipeline.phases.git import drop_transient_git_signals
-
- alias = repo_path.name
- head = get_head_commit(repo_path) or "HEAD"
-
- detector = ChangeDetector(repo_path)
- working_tree_diffs: list = []
- working_tree_paths: list[str] | None = None
- if include_working_tree:
- working_tree_diffs = detector.get_working_tree_changes()
- dirty = {fd.path for fd in working_tree_diffs}
- # Re-diff anything the last run indexed from the working tree that no
- # longer diverges from HEAD, so a reverted edit or a deleted untracked
- # file stops being served. See ``stale_working_tree_diffs``.
- working_tree_diffs += detector.stale_working_tree_diffs(
- state.get("working_tree_paths") or [], dirty
- )
- working_tree_paths = sorted(dirty)
-
- file_diffs = merge_file_diffs(
- detector.get_changed_files(base_ref, head),
- working_tree_diffs,
- )
- if not file_diffs and not force_full_git:
- # New commits but nothing the index cares about changed (merge/empty
- # commits, or every change excluded). Report success so the caller
- # bumps ``last_sync_commit`` instead of re-diffing forever.
- return RepoUpdateResult(alias=alias, updated=True, working_tree_paths=working_tree_paths)
-
- # Per-repo config, like the single-repo update path. The workspace-level
- # ``exclude_patterns`` (when provided) apply on top.
- from ..repo_config import load_repo_config
-
- cfg = load_repo_config(repo_path)
- merged_excludes = await _merged_repo_excludes(repo_path, exclude_patterns)
-
- # Decay-only rows for idle files the anchor advance recovered (#728);
- # persisted alongside the changed rows, kept out of git_meta_map so partial
- # health's repo-wide aggregates are unaffected (mirrors the CLI path).
- git_decay_map: dict[str, dict] = {}
- full_git_summaries: list[Any] = []
- (
- parsed_files,
- source_map,
- graph_builder,
- _structure,
- file_count,
- git_meta_map,
- ) = await rebuild_graph_and_git(
- repo_path,
- file_diffs,
- cfg,
- merged_excludes,
- git_tier=state.get("git_tier"),
- include_submodules=bool(state.get("include_submodules", False)),
- include_nested_repos=bool(state.get("include_nested_repos", False)),
- idle_decay_sink=git_decay_map,
- force_full_git=force_full_git,
- git_summary_sink=full_git_summaries,
- log=_log.info,
- )
-
- # Stored per-file git fields for the dead-code analyzer. ``git_meta_map``
- # covers the changed files only, so every other file would be scored
- # against an empty dict — which reads as "no commits in 90 days" and puts
- # the whole repo on the 0.7 / safe-to-delete rung of the confidence ladder.
- from ..pipeline.incremental import (
- load_stored_coverage_map,
- load_stored_function_mod_p80,
- load_stored_git_meta,
- load_stored_performance_callers,
- )
-
- stored_git_meta = await load_stored_git_meta(repo_path, log=_log.info)
- # Repo-wide p80 from the persisted blame rollup, so the partial health
- # pass scores the Function Hotspot gate against the full repo instead of
- # this run's changed-files subset (issue #1484).
- stored_function_mod_p80 = await load_stored_function_mod_p80(repo_path, log=_log.info)
- performance_changed_paths = {diff.path for diff in file_diffs}
- performance_changed_paths.update(
- diff.old_path for diff in file_diffs if getattr(diff, "old_path", None)
- )
- stored_performance_callers = await load_stored_performance_callers(
- repo_path, performance_changed_paths, log=_log.info
- )
- # Preserve coverage across an incremental health re-score: without a
- # coverage_map the changed files are re-scored as if no coverage existed
- # and their stored line_coverage_pct is nulled (issue #1739).
- stored_coverage_map = await load_stored_coverage_map(repo_path, log=_log.info)
-
- partial_health_report, dead_code_report = run_partial_analysis(
- repo_path,
- graph_builder,
- git_meta_map,
- parsed_files,
- file_diffs,
- source_map=source_map,
- stored_git_meta=stored_git_meta,
- stored_performance_callers=stored_performance_callers,
- repo_function_mod_p80=stored_function_mod_p80,
- coverage_map=stored_coverage_map,
- log=_log.info,
- )
- doc_drift_report = run_doc_drift_partial(
- graph_builder,
- source_map,
- repo_path=repo_path,
- log=_log.info,
- update=DocDriftUpdate.from_file_diffs(base_ref, file_diffs),
- )
-
- # Partial health has consumed the per-file ``BlameIndex``; drop it before
- # the metadata reaches persistence so the transient, non-serializable
- # 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,
- )
-
- # A full walk is stamped only when its rows reached the store.
- failed_steps: list[str] = []
- await persist_incremental_index(
- repo_path,
- graph_builder,
- git_meta_map,
- dead_code_report,
- partial_health_report,
- [fd.path for fd in file_diffs],
- doc_drift_report=doc_drift_report,
- current_graph_file_paths={pf.file_info.path for pf in parsed_files},
- # Tombstones pages for deleted/renamed paths, mirroring the single-repo
- # path — without this a page for a removed file misleads retrieval
- # until the next full regeneration.
- file_diffs=file_diffs,
- knowledge_graph_result=kg,
- parsed_files=parsed_files,
- source_map=source_map,
- git_decay_map=git_decay_map,
- full_git_summary=full_git_summaries[0] if full_git_summaries else None,
- failed_steps=failed_steps,
- 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,
- working_tree_paths=working_tree_paths,
- git_history_refreshed=bool(full_git_summaries) and "Git persist" not in failed_steps,
- )
-
-
-async def _has_persisted_repo_index(repo_path: Path) -> bool:
- """Return whether this repo has persisted index data.
-
- Local SQLite indexes are identified by their repo-local wiki.db.
- When a shared database is configured, the repository row is the source
- of truth instead; a repo-local wiki.db is not expected to exist.
- """
- from ..persistence.database import get_configured_db_url
-
- if get_configured_db_url() is None:
- return (repo_path / ".repowise" / "wiki.db").is_file()
-
- from ..persistence import (
- create_engine,
- create_session_factory,
- get_session,
- init_db,
- )
- from ..persistence.crud import get_repository_by_path
-
- engine = create_engine(get_configured_db_url())
- try:
- await init_db(engine)
- sf = create_session_factory(engine)
- async with get_session(sf) as session:
- return await get_repository_by_path(session, str(repo_path)) is not None
- finally:
- await engine.dispose()
-
-
-async def update_single_repo_index(
- repo_path: Path,
- *,
- commit_depth: int = _DEFAULT_COMMIT_LIMIT,
- exclude_patterns: list[str] | None = None,
- include_working_tree: bool = False,
- progress: Any | None = None,
-) -> RepoUpdateResult:
- """Refresh the index for a single repo.
-
- Already-indexed repos (a persisted ``last_sync_commit`` whose commit
- still resolves, plus an existing ``wiki.db``) go through the incremental
- update path — changed-files diff, partial analysis, upsert persistence.
- Never-indexed repos, config changes (``config.yaml`` / health-rules
- fingerprint drift, which invalidates every persisted score), and any
- incremental failure run the full ingestion pipeline instead (index-only —
- no wiki pages).
- """
- from ..repo_config import (
- changed_config_dependencies,
- config_dependency_fingerprints,
- config_fingerprint,
- load_repo_config,
- )
-
- alias = repo_path.name
- state = read_repo_state(repo_path)
- base_ref = state.get("last_sync_commit")
- merged_excludes = await _merged_repo_excludes(repo_path, exclude_patterns)
- repo_config = load_repo_config(repo_path)
- repo_commit_depth = int(repo_config.get("commit_limit", commit_depth))
- repo_follow_renames = bool(repo_config.get("follow_renames", False))
-
- # Config drift check, mirroring the single-repo update path: a changed
- # config.yaml / health-rules.json invalidates persisted health scores and
- # exclude handling, so the incremental (changed-files-only) path must not
- # run. The full pipeline below re-derives everything under the new config;
- # _update_one stamps the new fingerprint into state.json afterwards.
- # A missing stored fingerprint (legacy state) is NOT drift — same as the
- # single-repo path, which only stamps it — so legacy repos don't pay a
- # surprise full re-index.
- stored_fp = state.get("config_fingerprint")
- config_changed = stored_fp is not None and stored_fp != config_fingerprint(repo_path)
- current_dependency_fps = config_dependency_fingerprints(repo_path, config=repo_config)
- changed_dependencies = (
- changed_config_dependencies(
- state.get("config_dependency_fingerprints"), current_dependency_fps
- )
- if config_changed
- else set()
- )
- # Workspace indexing has no generation layer. Only settings that affect
- # its persisted graph/history/health stores require a full re-index;
- # formatting, distill/MCP, and generation-only edits are state updates.
- requires_full_reindex = config_changed and (
- changed_dependencies is None
- or bool((changed_dependencies or set()) - {"state_only", "generation"})
- )
- require_git_success = requires_full_reindex and (
- changed_dependencies is None
- or bool({"traversal", "git_history", "other"} & (changed_dependencies or set()))
- )
- require_health_success = requires_full_reindex and (
- changed_dependencies is None
- or bool(
- {"traversal", "git_history", "health", "other"}
- & (changed_dependencies or set())
- )
- )
- has_persisted_index = await _has_persisted_repo_index(repo_path)
- if requires_full_reindex and has_persisted_index:
- _log.info(
- "workspace_update: %s config fingerprint drifted — full re-index "
- "so health scores reflect the new config",
- alias,
- )
-
- if (
- not requires_full_reindex
- and base_ref
- and has_persisted_index
- and commit_exists(repo_path, str(base_ref))
- ):
- try:
- incremental_result = await _incremental_repo_update(
- repo_path,
- state=state,
- base_ref=str(base_ref),
- exclude_patterns=exclude_patterns,
- include_working_tree=include_working_tree,
- force_full_git=git_history_stale(state),
- )
- if incremental_result is not None:
- return incremental_result
- except Exception:
- _log.warning(
- "Incremental update failed for %s — falling back to the full pipeline",
- repo_path,
- exc_info=True,
- )
-
- try:
- from ..pipeline.full_index import index_repo_full
-
- result = await index_repo_full(
- repo_path,
- commit_depth=repo_commit_depth,
- exclude_patterns=merged_excludes,
- include_submodules=bool(state.get("include_submodules", False)),
- include_nested_repos=bool(state.get("include_nested_repos", False)),
- follow_renames=repo_follow_renames,
- require_git_success=require_git_success,
- require_health_success=require_health_success,
- progress=progress,
- )
-
- # index_repo_full already exported knowledge-graph.json; build the
- # state.json summary block so _update_one stamps it too.
- 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
-
- kg_state = build_kg_state(kg)
-
- return RepoUpdateResult(
- alias=alias,
- updated=True,
- file_count=result.file_count,
- symbol_count=result.symbol_count,
- kg_state=kg_state,
- git_history_refreshed=getattr(result, "git_summary", None) is not None,
- )
- except Exception as exc:
- return RepoUpdateResult(
- alias=alias,
- updated=False,
- error=str(exc),
- )
-
-
-# ---------------------------------------------------------------------------
-# Workspace update orchestration
-# ---------------------------------------------------------------------------
-
-_MAX_CONCURRENT_UPDATES = 4
-
-
-class _StaleRepo(NamedTuple):
- """A workspace member selected for this update pass."""
-
- alias: str
- path: Path
- new_head: str
- first_time: bool
-
-
-@dataclass
-class _RepoUpdatePass:
- """What every per-repo update in one workspace pass shares."""
-
- ws_config: WorkspaceConfig
- semaphore: asyncio.Semaphore
- commit_depth: int
- exclude_patterns: list[str] | None
- include_working_tree: bool
- on_repo_start: Callable[[str], None] | None
- on_repo_done: Callable[[RepoUpdateResult], None] | None
-
-
-async def update_workspace(
- workspace_root: Path,
- ws_config: WorkspaceConfig,
- *,
- repo_filter: str | None = None,
- only_aliases: set[str] | None = None,
- run_hooks: bool = True,
- dry_run: bool = False,
- commit_depth: int = _DEFAULT_COMMIT_LIMIT,
- exclude_patterns: list[str] | None = None,
- include_working_tree: bool = False,
- on_repo_start: Callable[[str], None] | None = None,
- on_repo_done: Callable[[RepoUpdateResult], None] | None = None,
-) -> list[RepoUpdateResult]:
- """Update stale repos in the workspace (index-only).
-
- Args:
- workspace_root: Path to the workspace root directory.
- ws_config: Loaded workspace configuration.
- repo_filter: If set, only update this repo alias.
- only_aliases: If set, restrict the run to this subset of aliases (on
- top of ``repo_filter``). The CLI uses this to hand the fast
- index-only path just the repos it isn't updating via the
- single-repo docs path, so the two orchestrators never touch the
- same repo in one workspace run.
- run_hooks: When False, skip the cross-repo analysis hooks at the end.
- The CLI sets this so it can run them once over the union of
- index-only and docs repos, instead of on a partial set here.
- dry_run: If True, detect staleness but don't actually update.
- commit_depth: Max commits to analyze per file.
- exclude_patterns: Gitignore-style patterns to exclude.
- include_working_tree: Count uncommitted work as staleness, and index
- it. Off for every commit-anchored caller (hooks, webhooks, a
- manual sync); ``repowise watch --workspace`` sets it, because a
- repo it is watching normally has no new commits at all.
- on_repo_start: Called with alias when a repo update begins.
- on_repo_done: Called with result when a repo update finishes.
-
- Returns:
- List of :class:`RepoUpdateResult` for each repo.
- """
- results: list[RepoUpdateResult] = []
- entries = _entries_for_run(ws_config, repo_filter, only_aliases)
-
- # Sync ``last_commit_at_index`` from each repo's state.json so the
- # workspace config doesn't drift when a child repo is updated outside the
- # workspace orchestrator (e.g. ``repowise update`` run inside the child
- # dir directly).
- sync_workspace_state_from_disk(workspace_root, ws_config)
-
- stale_repos = await _select_stale_repos(workspace_root, entries, include_working_tree, results)
- if dry_run or not stale_repos:
- return results
-
- # Workspace-level single-flight guard. The per-repo lock below only
- # stops two updates racing on the *same* repo's index; it does not stop
- # N post-commit-hook ``repowise update`` invocations (one per rebase
- # commit) from each running a full workspace pass over every stale
- # member. Coalesce those triggers at the workspace level: the first pass
- # holds this lock, and every concurrent one defers by recording a pending
- # marker per stale repo so the running pass rolls forward to the latest
- # HEAD instead of a second full index being spawned.
- workspace_owner = _try_acquire_workspace_lock(workspace_root)
- if workspace_owner is not None:
- return _defer_to_running_workspace_update(workspace_owner, stale_repos)
-
- # Update stale repos (parallel with concurrency limit). The workspace
- # lock is held for the whole pass and released once every member has
- # been attempted (including on failure) so the next hook-triggered
- # invocation can take over.
- try:
- update_pass = _RepoUpdatePass(
- ws_config=ws_config,
- semaphore=asyncio.Semaphore(_MAX_CONCURRENT_UPDATES),
- commit_depth=commit_depth,
- exclude_patterns=exclude_patterns,
- include_working_tree=include_working_tree,
- on_repo_start=on_repo_start,
- on_repo_done=on_repo_done,
- )
- update_results = await asyncio.gather(
- *[_update_stale_repo(update_pass, repo) for repo in stale_repos],
- return_exceptions=True,
- )
- changed_aliases = _collect_update_results(update_results, results)
- await _finish_workspace_pass(ws_config, workspace_root, changed_aliases, run_hooks)
- return results
- finally:
- _release_workspace_lock(workspace_root)
-
-
-def _entries_for_run(
- ws_config: WorkspaceConfig,
- repo_filter: str | None,
- only_aliases: set[str] | None,
-) -> list[RepoEntry]:
- """The workspace entries this run considers, after both filters."""
- entries = ws_config.repos
- if repo_filter:
- entry = ws_config.get_repo(repo_filter)
- if entry is None:
- available = ", ".join(ws_config.repo_aliases())
- raise ValueError(f"Unknown repo '{repo_filter}'. Available: {available}")
- entries = [entry]
-
- if only_aliases is not None:
- entries = [e for e in entries if e.alias in only_aliases]
- return entries
-
-
-async def _select_stale_repos(
- workspace_root: Path,
- entries: list[RepoEntry],
- include_working_tree: bool,
- results: list[RepoUpdateResult],
-) -> list[_StaleRepo]:
- """Return the stale entries; append a skipped result for every other one."""
- stale_repos: list[_StaleRepo] = []
- for entry in entries:
- abs_path = (workspace_root / entry.path).resolve()
- if not abs_path.is_dir():
- results.append(
- RepoUpdateResult(
- alias=entry.alias,
- updated=False,
- skipped_reason="missing_directory",
- )
- )
- continue
-
- is_stale, current_head = await _repo_is_stale(abs_path, include_working_tree)
- if not is_stale:
- # Nothing to regenerate, but the DB freshness stamp can still be
- # behind (e.g. a row left drifted by a pre-fix run). Reconcile it so
- # the server's /api/repos no longer reports "index behind checkout".
- await reconcile_repo_head_commit(abs_path, current_head)
- results.append(
- RepoUpdateResult(
- alias=entry.alias,
- updated=False,
- skipped_reason="up_to_date",
- )
- )
- continue
-
- # First-time indexing runs the full pipeline; the `.repowise/` dir is
- # created on demand by ``update_single_repo_index`` (resolve_db_url)
- # and ``state.json`` is written by ``_write_repo_state``.
- first_time = not (abs_path / ".repowise").is_dir()
- stale_repos.append(_StaleRepo(entry.alias, abs_path, current_head or "", first_time))
- return stale_repos
-
-
-async def _repo_is_stale(abs_path: Path, include_working_tree: bool) -> tuple[bool, str | None]:
- """Return ``(is_stale, current_head)`` for one workspace member."""
- from ..repo_config import config_fingerprint
-
- # Check staleness against stored commit in state.json
- state_path = abs_path / ".repowise" / "state.json"
- stored_commit = None
- state: dict[str, Any] = {}
- if state_path.is_file():
- try:
- state = _json.loads(state_path.read_text(encoding="utf-8"))
- stored_commit = state.get("last_sync_commit")
- except Exception:
- pass
-
- is_stale, current_head, _commits_behind = check_repo_staleness(
- abs_path,
- stored_commit,
- )
- stored_config_fp = state.get("config_fingerprint")
- config_state_missing = stored_config_fp is None and await _has_persisted_repo_index(abs_path)
- if not is_stale and (
- config_state_missing
- or (stored_config_fp is not None and stored_config_fp != config_fingerprint(abs_path))
- ):
- is_stale = True
-
- # A watched repo's changes are uncommitted by definition, so the
- # commit-to-commit staleness check above says "up to date" for exactly
- # the work the watcher woke up for.
- if not is_stale and include_working_tree and has_working_tree_changes(abs_path):
- is_stale = True
-
- # Rows written under older git history rules: one full walk refreshes
- # them, as the single-repo update does, even with HEAD unmoved.
- if not is_stale and git_history_stale(state) and await _has_persisted_repo_index(abs_path):
- is_stale = True
- return is_stale, current_head
-
-
-def _defer_to_running_workspace_update(
- workspace_owner: dict[str, Any], stale_repos: list[_StaleRepo]
-) -> list[RepoUpdateResult]:
- """Queue every stale repo for the workspace update already in flight."""
- age = _lock_age_seconds(workspace_owner)
- _log.info(
- "workspace_update: deferring — a workspace update is already "
- "in flight (pid=%s elapsed=%ss); queuing %d stale repo(s) for it",
- workspace_owner.get("pid"),
- int(age) if age is not None else "?",
- len(stale_repos),
- )
- # Record pending so the running workspace update rolls forward to the
- # latest HEAD of each member. Mirrors the per-repo deferral in
- # ``_defer_in_flight_repo``.
- for _alias, path, new_head, _first_time in stale_repos:
- if new_head:
- with suppress(OSError):
- (path / ".repowise").mkdir(parents=True, exist_ok=True)
- (path / ".repowise" / ".update.pending").write_text(new_head, encoding="utf-8")
- return [
- RepoUpdateResult(
- alias=alias,
- updated=False,
- skipped_reason="in_flight",
- lock_age_seconds=age,
- )
- for alias, _path, _head, _first_time in stale_repos
- ]
-
-
-async def _update_stale_repo(update_pass: _RepoUpdatePass, repo: _StaleRepo) -> RepoUpdateResult:
- """Update one stale repo under the pass's concurrency limit."""
- alias, path, new_head, first_time = repo
- async with update_pass.semaphore:
- if update_pass.on_repo_start:
- update_pass.on_repo_start(alias)
-
- # Ensure the .repowise/ dir exists before the pipeline runs so
- # first-time indexing has a place to put wiki.db and state.json.
- (path / ".repowise").mkdir(parents=True, exist_ok=True)
-
- # Per-repo single-flight lock. The post-commit hook fires a
- # new ``repowise update`` for every commit; without this guard,
- # rapid-fire commits race on save_state, each pass starts from
- # the same stale base, and the wiki never converges to HEAD.
- # Check + acquire are one atomic exclusive create.
- existing = _try_acquire_lock(path, new_head)
- if existing is not None:
- return _defer_in_flight_repo(alias, path, new_head, existing)
-
- try:
- update_started = time.monotonic()
- result = await update_single_repo_index(
- path,
- commit_depth=update_pass.commit_depth,
- exclude_patterns=update_pass.exclude_patterns,
- include_working_tree=update_pass.include_working_tree,
- )
- if result.updated and result.phase_timings is None:
- result.phase_timings = {"run": time.monotonic() - update_started}
- finally:
- _release_lock(path)
- result.alias = alias
- result.first_time_indexed = first_time and result.updated
-
- if result.updated and new_head:
- _write_repo_state(path, alias, new_head, first_time, result)
- # Keep the DB freshness stamp in lockstep with last_sync_commit.
- # The no-relevant-changes incremental path returns updated=True
- # without re-running DB persistence, so the row would otherwise
- # lag HEAD; a no-op when persistence already stamped it.
- await reconcile_repo_head_commit(path, new_head)
- # Drop any stale pending marker now that we've advanced to
- # new_head (a bailed sibling update may have written one).
- clear_stale_update_pending(path, new_head)
-
- # Update workspace config entry
- if result.updated:
- entry = update_pass.ws_config.get_repo(alias)
- if entry is not None:
- entry.indexed_at = datetime.now(UTC).isoformat()
- entry.last_commit_at_index = new_head
-
- if update_pass.on_repo_done:
- update_pass.on_repo_done(result)
-
- return result
-
-
-def _defer_in_flight_repo(
- alias: str, path: Path, new_head: str, existing: dict[str, Any]
-) -> RepoUpdateResult:
- """Leave a pending marker for the update that already holds this repo's lock."""
- age = _lock_age_seconds(existing)
- target_short = (existing.get("target_commit") or "")[:8]
- _log.info(
- "workspace_update: skipping %s — update already in flight "
- "(pid=%s target=%s elapsed=%ss)",
- alias,
- existing.get("pid"),
- target_short,
- int(age) if age is not None else "?",
- )
- # Record pending so the running update can roll forward.
- with suppress(OSError):
- (path / ".repowise" / ".update.pending").write_text(new_head, encoding="utf-8")
- return RepoUpdateResult(
- alias=alias,
- updated=False,
- skipped_reason="in_flight",
- lock_age_seconds=age,
- )
-
-
-def _write_repo_state(
- path: Path, alias: str, new_head: str, first_time: bool, result: RepoUpdateResult
-) -> None:
- """Advance ``state.json`` to *new_head* after a successful repo update."""
- state_path = path / ".repowise" / "state.json"
- state: dict[str, Any] = {}
- if state_path.is_file():
- with suppress(Exception):
- state = _json.loads(state_path.read_text(encoding="utf-8"))
-
- # Falsy, not absent: an explicit null survives a
- # membership test and strands the pointer permanently.
- if not state.get("last_docs_commit") and state.get("last_sync_commit"):
- state["last_docs_commit"] = state["last_sync_commit"]
-
- state["last_sync_commit"] = new_head
- if result.kg_state:
- state["knowledge_graph"] = result.kg_state
- if result.working_tree_paths is not None:
- state["working_tree_paths"] = result.working_tree_paths
- if result.phase_timings is not None:
- state["phase_timings"] = result.phase_timings
- if result.git_history_refreshed:
- state[GIT_HISTORY_VERSION_KEY] = GIT_HISTORY_VERSION
- # Stamp the config fingerprint so the drift check in
- # update_single_repo_index stays calibrated (and legacy repos
- # without one stop re-triggering the full re-index).
- with suppress(Exception):
- from ..repo_config import (
- config_dependency_fingerprints,
- config_fingerprint,
- load_repo_config,
- )
-
- state["config_fingerprint"] = config_fingerprint(path)
- state["config_dependency_fingerprints"] = config_dependency_fingerprints(
- path, config=load_repo_config(path)
- )
- # Mark first-time so downstream tooling (status, doctor) can
- # distinguish a never-indexed repo from one that's been
- # updated at least once.
- if first_time and "docs_mode" not in state and "docs_enabled" not in state:
- # This path indexes only; nothing renders pages here, not
- # even from templates.
- state.update(docs_mode_state_fields("none"))
- state["docs_skip_reason"] = (
- "first-time index via update; run "
- "`repowise update --repo " + alias + " --docs` to generate docs"
- )
- from ..fsutils import atomic_write_text
-
- state_path.parent.mkdir(parents=True, exist_ok=True)
- atomic_write_text(state_path, _json.dumps(state, indent=2))
-
-
-def _collect_update_results(
- update_results: list[RepoUpdateResult | BaseException],
- results: list[RepoUpdateResult],
-) -> list[str]:
- """Append each gathered result to *results*; return the updated aliases."""
- changed_aliases: list[str] = []
- for r in update_results:
- if isinstance(r, Exception):
- results.append(
- RepoUpdateResult(
- alias="unknown",
- updated=False,
- error=str(r),
- )
- )
- else:
- results.append(r)
- if r.updated:
- changed_aliases.append(r.alias)
- return changed_aliases
-
-
-async def _finish_workspace_pass(
- ws_config: WorkspaceConfig,
- workspace_root: Path,
- changed_aliases: list[str],
- run_hooks: bool,
-) -> None:
- """Save the updated workspace config, then run the cross-repo hooks."""
- if changed_aliases:
- ws_config.save(workspace_root)
-
- # ``run_hooks`` lets the CLI defer these so they run once over the union
- # of index-only and docs repos, rather than on this partial set.
- if changed_aliases and run_hooks:
- await run_cross_repo_hooks(ws_config, workspace_root, changed_aliases)
-
-
-# ---------------------------------------------------------------------------
-# Cross-repo hooks
-# ---------------------------------------------------------------------------
-
-
-def _log_phase(timings: PhaseTimingRecorder, phase: str, **counts: int) -> None:
- """Emit one structured line for a finished cross-repo phase.
-
- Duration *and* the counts the phase produced. A timer alone cannot tell a
- genuine speed-up from a phase that got faster by doing less work, which is
- the specific regression workspace mode has already had once — so the counts
- are not optional decoration.
- """
- detail = ", ".join(f"{k}={v}" for k, v in counts.items())
- _log.info(
- "workspace phase %s: %.2fs%s",
- phase,
- timings.timings.get(phase, 0.0),
- f" ({detail})" if detail else "",
- )
-
-
-async def run_cross_repo_hooks(
- ws_config: WorkspaceConfig,
- workspace_root: Path,
- changed_repos: list[str],
-) -> None:
- """Run cross-repo analysis after workspace repos are updated.
-
- Detects cross-repo co-changes (files committed by the same author within
- a time window across repos) and package/manifest dependencies. Results are
- persisted to ``.repowise-workspace/cross_repo_edges.json`` and loaded by
- the MCP server's :class:`CrossRepoEnricher` at startup. Ends by refreshing
- the workspace store (:mod:`.store`).
- """
- if len(ws_config.repos) < 2:
- return
-
- from .repo_index import WorkspaceIndex, open_workspace_index
-
- timings = PhaseTimingRecorder()
-
- # The read side of every repo's index, opened once here and closed in the
- # finally below, so one connection per repo serves all five phases.
- # Indexing has just written these databases; without this the phases below
- # re-derive from raw text what they already hold. Only the HTTP extractor
- # reads it today, so nothing is opened when that is off.
- workspace_index = (
- await open_workspace_index(ws_config, workspace_root)
- if ws_config.contracts.detect_http
- else WorkspaceIndex({})
- )
- try:
- await _run_phases(ws_config, workspace_root, changed_repos, timings, workspace_index)
- finally:
- await workspace_index.close()
-
- # Last: derived components read the system graph the phases just wrote.
- from .store import refresh_workspace_store
-
- timings.on_phase_start("workspace_store", None)
- try:
- await refresh_workspace_store(ws_config, workspace_root)
- except Exception:
- _log.warning("Workspace store refresh failed", exc_info=True)
- timings.on_phase_done("workspace_store")
- _log_phase(timings, "workspace_store")
-
- # Each updated repo snapshotted its components before contracts were
- # extracted at its new commit; measure them now.
- for alias in changed_repos:
- entry = ws_config.get_repo(alias)
- if entry is not None:
- await _refresh_contract_facts((workspace_root / entry.path).resolve())
-
-
-async def _refresh_contract_facts(repo_path: Path) -> None:
- """Best-effort: a failure leaves the run's contracts unavailable."""
- from ..events.store import refresh_contract_facts
- from ..persistence import create_engine, create_session_factory, get_session
- from ..persistence.crud import get_repository_by_path
- from ..persistence.database import has_db_store, resolve_db_url
-
- if not has_db_store(repo_path):
- return
- engine = create_engine(resolve_db_url(repo_path))
- try:
- async with get_session(create_session_factory(engine)) as session:
- repo = await get_repository_by_path(session, str(repo_path))
- if repo is not None:
- await refresh_contract_facts(session, repo.id)
- except Exception:
- _log.warning("Contract facts not refreshed for %s", repo_path, exc_info=True)
- finally:
- await engine.dispose()
-
-
-async def _run_phases(
- ws_config: WorkspaceConfig,
- workspace_root: Path,
- changed_repos: list[str],
- timings: PhaseTimingRecorder,
- workspace_index: WorkspaceIndex,
-) -> None:
- """The five cross-repo phases, over an already-open workspace index."""
- from .contracts import ContractStore, load_contract_store
-
- boundaries_by_repo = await _boundaries_phase(ws_config, workspace_root, timings)
-
- # Snapshot the contracts as they stand on disk BEFORE extraction overwrites
- # them. Two jobs, one read: the baseline for the breaking-change diff, and
- # the source of any rows extraction carries forward instead of recomputing.
- # Loaded here rather than inside extraction so the ordering against the
- # write is explicit and the 360 KB parse happens once.
- previous_store = load_contract_store(workspace_root) or ContractStore()
-
- overlay, store, extraction_ok = await _analysis_and_extraction_phases(
- ws_config,
- workspace_root,
- changed_repos,
- timings,
- workspace_index,
- boundaries_by_repo,
- previous_store,
- )
- system_graph = await _system_graph_phase(
- ws_config, workspace_root, timings, store, overlay, boundaries_by_repo
- )
- _breaking_change_phase(workspace_root, timings, previous_store, store, extraction_ok)
-
- # Conformance + cycles — check declared dependency rules and detect circular
- # service dependencies over the freshly-built system graph.
- if system_graph is not None:
- _conformance_phase(ws_config, workspace_root, timings, system_graph)
-
- _log.info("Cross-repo phase timings (seconds): %s", timings.timings)
-
-
-async def _boundaries_phase(
- ws_config: WorkspaceConfig,
- workspace_root: Path,
- timings: PhaseTimingRecorder,
-) -> dict[str, list[ServiceBoundary]]:
- """Service boundaries, detected once for the whole workspace.
-
- Contract extraction and the system-graph build both need them and each
- used to walk every repo for its own copy.
- """
- from .system_graph import _detect_boundaries_by_repo
-
- boundaries_by_repo: dict[str, list[ServiceBoundary]] = {}
- timings.on_phase_start("boundaries", None)
- try:
- boundaries_by_repo = await asyncio.to_thread(
- _detect_boundaries_by_repo, ws_config, workspace_root
- )
- except Exception:
- _log.warning("Service boundary detection failed", exc_info=True)
- timings.on_phase_done("boundaries")
- _log_phase(
- timings,
- "boundaries",
- repos=len(boundaries_by_repo),
- boundaries=sum(len(b) for b in boundaries_by_repo.values()),
- )
- return boundaries_by_repo
-
-
-async def _analysis_and_extraction_phases(
- ws_config: WorkspaceConfig,
- workspace_root: Path,
- changed_repos: list[str],
- timings: PhaseTimingRecorder,
- workspace_index: WorkspaceIndex,
- boundaries_by_repo: dict[str, list[ServiceBoundary]],
- previous_store: ContractStore,
-) -> tuple[CrossRepoOverlay, ContractStore, bool]:
- """Run cross-repo analysis and contract extraction together.
-
- Returns ``(overlay, store, extraction_ok)``; a failed phase yields an
- empty result.
- """
- from .contracts import ContractStore, run_contract_extraction
- from .cross_repo import CrossRepoOverlay, run_cross_repo_analysis
-
- # Phases 1 and 2 are independent: they read disjoint inputs (git history and
- # manifests vs source files and the symbol index), write different artifacts
- # (cross_repo_edges.json vs contracts.json), and share no mutable state —
- # boundaries_by_repo is computed above and passed in read-only. Both push
- # their blocking work through asyncio.to_thread, so gather genuinely
- # overlaps them rather than interleaving two synchronous bodies.
- # Each coroutine times itself, so running them together does not cost the
- # ability to say which one dominates — the question this instrumentation
- # exists to answer, and one a single duration for the pair would destroy.
- async def _timed(phase: str, coro: Awaitable[Any]) -> Any:
- timings.on_phase_start(phase, None)
- try:
- return await coro
- finally:
- timings.on_phase_done(phase)
-
- overlay_result, store_result = await asyncio.gather(
- _timed(
- "cross_repo_analysis", run_cross_repo_analysis(ws_config, workspace_root, changed_repos)
- ),
- _timed(
- "contract_extraction",
- run_contract_extraction(
- ws_config,
- workspace_root,
- changed_repos,
- boundaries_by_repo or None,
- previous_store,
- workspace_index,
- ),
- ),
- return_exceptions=True,
- )
-
- # Cancellation and interpreter-level exits are not phase failures — the old
- # `except Exception` let them propagate by construction, and gather's
- # return_exceptions=True does not. Re-raise them before anything downstream
- # treats a cancelled run as a completed one.
- for result in (overlay_result, store_result):
- if isinstance(result, BaseException) and not isinstance(result, Exception):
- raise result
-
- overlay = CrossRepoOverlay()
- if isinstance(overlay_result, Exception):
- _log.warning("Cross-repo analysis failed", exc_info=overlay_result)
- else:
- overlay = overlay_result
-
- store = ContractStore()
- extraction_ok = not isinstance(store_result, Exception)
- if isinstance(store_result, Exception):
- _log.warning("Contract extraction failed", exc_info=store_result)
- else:
- store = store_result
-
- _log_phase(
- timings,
- "cross_repo_analysis",
- co_changes=len(overlay.co_changes),
- package_deps=len(overlay.package_deps),
- )
- _log_phase(
- timings,
- "contract_extraction",
- contracts=len(store.contracts),
- links=len(store.contract_links),
- # Repos actually walked this run — the number that separates a real
- # speed-up from a phase that got faster by doing less than it claims.
- # Derived from the stamp rather than summing extraction_stats, which
- # also carries the counters of the repos this run skipped.
- repos_extracted=sum(
- 1 for p in store.repo_provenance.values() if p.get("extracted_at") == store.generated_at
- ),
- repos_reused=sum(
- 1 for p in store.repo_provenance.values() if p.get("extracted_at") != store.generated_at
- ),
- )
- return overlay, store, extraction_ok
-
-
-async def _system_graph_phase(
- ws_config: WorkspaceConfig,
- workspace_root: Path,
- timings: PhaseTimingRecorder,
- store: ContractStore,
- overlay: CrossRepoOverlay,
- boundaries_by_repo: dict[str, list[ServiceBoundary]],
-) -> SystemGraph | None:
- """Build the system graph, the service-granular structure every workspace view reads.
-
- Built after extraction so it folds in the contracts and overlay.
- """
- from .system_graph import run_system_graph_build
-
- system_graph: SystemGraph | None = None
- timings.on_phase_start("system_graph", None)
- try:
- system_graph = await run_system_graph_build(
- ws_config, workspace_root, store, overlay, boundaries_by_repo or None
- )
- except Exception:
- _log.warning("System graph build failed", exc_info=True)
- timings.on_phase_done("system_graph")
- _log_phase(
- timings,
- "system_graph",
- nodes=len(system_graph.nodes) if system_graph else 0,
- edges=len(system_graph.edges) if system_graph else 0,
- )
- return system_graph
-
-
-def _breaking_change_phase(
- workspace_root: Path,
- timings: PhaseTimingRecorder,
- previous_store: ContractStore,
- store: ContractStore,
- extraction_ok: bool,
-) -> None:
- """Diff the previous (on-disk) contracts against the fresh set and persist the report.
-
- Gated on the SHAPE of the result, not on whether an exception escaped.
- Diffing a populated baseline against an empty set reports every contract
- in the workspace as removed, and extraction has more than one way to hand
- back nothing: it raises, or it returns an empty store early because fewer
- than two repos are currently indexed (a repo unmounted, renamed, or having
- just lost its .repowise/). Both would publish themselves as the largest
- breaking change the workspace has ever seen. An empty result is only
- trustworthy when the baseline is empty too.
- """
- from .breaking_change import run_breaking_change_detection
-
- if extraction_ok and (store.contracts or not previous_store.contracts):
- report = None
- timings.on_phase_start("breaking_change", None)
- try:
- report = run_breaking_change_detection(workspace_root, previous_store, store)
- except Exception:
- _log.warning("Breaking-change detection failed", exc_info=True)
- timings.on_phase_done("breaking_change")
- _log_phase(
- timings,
- "breaking_change",
- breaking=len(report.changes) if report else 0,
- )
- else:
- _log.warning(
- "Skipping breaking-change detection: extraction produced no contracts "
- "(ok=%s) while the previous artifact holds %d — diffing these would "
- "report the whole workspace as removed",
- extraction_ok,
- len(previous_store.contracts),
- )
-
-
-def _conformance_phase(
- ws_config: WorkspaceConfig,
- workspace_root: Path,
- timings: PhaseTimingRecorder,
- system_graph: SystemGraph,
-) -> None:
- """Check declared dependency rules and service cycles over the system graph."""
- from .conformance import run_conformance_check
-
- conformance = None
- timings.on_phase_start("conformance", None)
- try:
- conformance = run_conformance_check(ws_config, workspace_root, system_graph)
- except Exception:
- _log.warning("Conformance check failed", exc_info=True)
- timings.on_phase_done("conformance")
- _log_phase(
- timings,
- "conformance",
- rules=conformance.rules_evaluated if conformance else 0,
- violations=len(conformance.violations) if conformance else 0,
- # The true total, not the capped list — a workspace with 500 cycles
- # must not report the same number as one with 50.
- cycles=conformance.total_cycles if conformance else 0,
- )
diff --git a/packages/core/src/repowise/core/workspace/update/__init__.py b/packages/core/src/repowise/core/workspace/update/__init__.py
new file mode 100644
index 000000000..fc469a894
--- /dev/null
+++ b/packages/core/src/repowise/core/workspace/update/__init__.py
@@ -0,0 +1,83 @@
+"""Workspace-level update orchestration.
+
+Handles staleness detection, parallel multi-repo updates, and cross-repo
+analysis hooks. The package re-exports every name the old single module held.
+"""
+
+# ruff: noqa: F401
+from __future__ import annotations
+
+from .phases import (
+ _analysis_and_extraction_phases,
+ _boundaries_phase,
+ _breaking_change_phase,
+ _conformance_phase,
+ _log_phase,
+ _refresh_contract_facts,
+ _run_phases,
+ _system_graph_phase,
+ run_cross_repo_hooks,
+)
+from .repo import (
+ RepoUpdateResult,
+ _has_persisted_repo_index,
+ _incremental_repo_update,
+ _merged_repo_excludes,
+ update_single_repo_index,
+)
+from .state import (
+ _ANCESTRY_CACHE_MAX,
+ IndexedCommit,
+ _ancestry_cache,
+ _older_commit,
+ check_repo_staleness,
+ clear_stale_update_pending,
+ commit_exists,
+ count_commits_between,
+ get_head_commit,
+ read_repo_state,
+ read_state_commit,
+ reconcile_repo_head_commit,
+ resolve_indexed_commit,
+ restamp_changed_sync_commit,
+ sync_workspace_state_from_disk,
+)
+from .workspace_pass import (
+ _MAX_CONCURRENT_UPDATES,
+ _collect_update_results,
+ _defer_in_flight_repo,
+ _defer_to_running_workspace_update,
+ _entries_for_run,
+ _finish_workspace_pass,
+ _lock_age_seconds,
+ _release_lock,
+ _release_workspace_lock,
+ _repo_is_stale,
+ _RepoUpdatePass,
+ _select_stale_repos,
+ _StaleRepo,
+ _try_acquire_lock,
+ _try_acquire_workspace_lock,
+ _update_stale_repo,
+ _write_repo_state,
+ update_workspace,
+)
+
+__all__ = [
+ "IndexedCommit",
+ "RepoUpdateResult",
+ "check_repo_staleness",
+ "clear_stale_update_pending",
+ "commit_exists",
+ "count_commits_between",
+ "get_head_commit",
+ "read_repo_state",
+ "read_state_commit",
+ "reconcile_repo_head_commit",
+ "resolve_indexed_commit",
+ "restamp_changed_sync_commit",
+ "run_cross_repo_hooks",
+ "sync_workspace_state_from_disk",
+ "update_single_repo_index",
+ "update_workspace",
+]
diff --git a/packages/core/src/repowise/core/workspace/update/phases.py b/packages/core/src/repowise/core/workspace/update/phases.py
new file mode 100644
index 000000000..07cd11782
--- /dev/null
+++ b/packages/core/src/repowise/core/workspace/update/phases.py
@@ -0,0 +1,376 @@
+"""Cross-repo hooks run after a workspace update, one timed phase at a time."""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+from collections.abc import Awaitable
+from pathlib import Path
+from typing import TYPE_CHECKING, Any
+
+from ...pipeline.phase_timing import PhaseTimingRecorder
+from ..config import WorkspaceConfig
+
+if TYPE_CHECKING:
+ from repowise.core.workspace.contracts import ContractStore
+ from repowise.core.workspace.cross_repo import CrossRepoOverlay
+ from repowise.core.workspace.extractors.service_boundary import ServiceBoundary
+ from repowise.core.workspace.repo_index import WorkspaceIndex
+ from repowise.core.workspace.system_graph import SystemGraph
+
+_log = logging.getLogger("repowise.workspace.update")
+
+
+def _log_phase(timings: PhaseTimingRecorder, phase: str, **counts: int) -> None:
+ """Emit one structured line for a finished cross-repo phase.
+
+ Duration *and* the counts the phase produced. A timer alone cannot tell a
+ genuine speed-up from a phase that got faster by doing less work, which is
+ the specific regression workspace mode has already had once — so the counts
+ are not optional decoration.
+ """
+ detail = ", ".join(f"{k}={v}" for k, v in counts.items())
+ _log.info(
+ "workspace phase %s: %.2fs%s",
+ phase,
+ timings.timings.get(phase, 0.0),
+ f" ({detail})" if detail else "",
+ )
+
+
+async def run_cross_repo_hooks(
+ ws_config: WorkspaceConfig,
+ workspace_root: Path,
+ changed_repos: list[str],
+) -> None:
+ """Run cross-repo analysis after workspace repos are updated.
+
+ Detects cross-repo co-changes (files committed by the same author within
+ a time window across repos) and package/manifest dependencies. Results are
+ persisted to ``.repowise-workspace/cross_repo_edges.json`` and loaded by
+ the MCP server's :class:`CrossRepoEnricher` at startup. Ends by refreshing
+ the workspace store (:mod:`.store`).
+ """
+ if len(ws_config.repos) < 2:
+ return
+
+ from ..repo_index import WorkspaceIndex, open_workspace_index
+
+ timings = PhaseTimingRecorder()
+
+ # One read connection per repo serves all five phases; only the HTTP
+ # extractor reads it, so nothing is opened when that is off.
+ workspace_index = (
+ await open_workspace_index(ws_config, workspace_root)
+ if ws_config.contracts.detect_http
+ else WorkspaceIndex({})
+ )
+ try:
+ await _run_phases(ws_config, workspace_root, changed_repos, timings, workspace_index)
+ finally:
+ await workspace_index.close()
+
+ # Last: derived components read the system graph the phases just wrote.
+ from ..store import refresh_workspace_store
+
+ timings.on_phase_start("workspace_store", None)
+ try:
+ await refresh_workspace_store(ws_config, workspace_root)
+ except Exception:
+ _log.warning("Workspace store refresh failed", exc_info=True)
+ timings.on_phase_done("workspace_store")
+ _log_phase(timings, "workspace_store")
+
+ # Each updated repo snapshotted its components before contracts were
+ # extracted at its new commit; measure them now.
+ for alias in changed_repos:
+ entry = ws_config.get_repo(alias)
+ if entry is not None:
+ await _refresh_contract_facts((workspace_root / entry.path).resolve())
+
+
+async def _refresh_contract_facts(repo_path: Path) -> None:
+ """Best-effort: a failure leaves the run's contracts unavailable."""
+ from ...events.store import refresh_contract_facts
+ from ...persistence import create_engine, create_session_factory, get_session
+ from ...persistence.crud import get_repository_by_path
+ from ...persistence.database import has_db_store, resolve_db_url
+
+ if not has_db_store(repo_path):
+ return
+ engine = create_engine(resolve_db_url(repo_path))
+ try:
+ async with get_session(create_session_factory(engine)) as session:
+ repo = await get_repository_by_path(session, str(repo_path))
+ if repo is not None:
+ await refresh_contract_facts(session, repo.id)
+ except Exception:
+ _log.warning("Contract facts not refreshed for %s", repo_path, exc_info=True)
+ finally:
+ await engine.dispose()
+
+
+async def _run_phases(
+ ws_config: WorkspaceConfig,
+ workspace_root: Path,
+ changed_repos: list[str],
+ timings: PhaseTimingRecorder,
+ workspace_index: WorkspaceIndex,
+) -> None:
+ """The five cross-repo phases, over an already-open workspace index."""
+ from ..contracts import ContractStore, load_contract_store
+
+ boundaries_by_repo = await _boundaries_phase(ws_config, workspace_root, timings)
+
+ # Snapshot the contracts as they stand on disk BEFORE extraction overwrites
+ # them. Two jobs, one read: the baseline for the breaking-change diff, and
+ # the source of any rows extraction carries forward instead of recomputing.
+ # Loaded here rather than inside extraction so the ordering against the
+ # write is explicit and the 360 KB parse happens once.
+ previous_store = load_contract_store(workspace_root) or ContractStore()
+
+ overlay, store, extraction_ok = await _analysis_and_extraction_phases(
+ ws_config,
+ workspace_root,
+ changed_repos,
+ timings,
+ workspace_index,
+ boundaries_by_repo,
+ previous_store,
+ )
+ system_graph = await _system_graph_phase(
+ ws_config, workspace_root, timings, store, overlay, boundaries_by_repo
+ )
+ _breaking_change_phase(workspace_root, timings, previous_store, store, extraction_ok)
+
+ # Conformance + cycles — check declared dependency rules and detect circular
+ # service dependencies over the freshly-built system graph.
+ if system_graph is not None:
+ _conformance_phase(ws_config, workspace_root, timings, system_graph)
+
+ _log.info("Cross-repo phase timings (seconds): %s", timings.timings)
+
+
+async def _boundaries_phase(
+ ws_config: WorkspaceConfig,
+ workspace_root: Path,
+ timings: PhaseTimingRecorder,
+) -> dict[str, list[ServiceBoundary]]:
+ """Service boundaries, detected once for contract extraction and the system graph."""
+ from ..system_graph import _detect_boundaries_by_repo
+
+ boundaries_by_repo: dict[str, list[ServiceBoundary]] = {}
+ timings.on_phase_start("boundaries", None)
+ try:
+ boundaries_by_repo = await asyncio.to_thread(
+ _detect_boundaries_by_repo, ws_config, workspace_root
+ )
+ except Exception:
+ _log.warning("Service boundary detection failed", exc_info=True)
+ timings.on_phase_done("boundaries")
+ _log_phase(
+ timings,
+ "boundaries",
+ repos=len(boundaries_by_repo),
+ boundaries=sum(len(b) for b in boundaries_by_repo.values()),
+ )
+ return boundaries_by_repo
+
+
+async def _analysis_and_extraction_phases(
+ ws_config: WorkspaceConfig,
+ workspace_root: Path,
+ changed_repos: list[str],
+ timings: PhaseTimingRecorder,
+ workspace_index: WorkspaceIndex,
+ boundaries_by_repo: dict[str, list[ServiceBoundary]],
+ previous_store: ContractStore,
+) -> tuple[CrossRepoOverlay, ContractStore, bool]:
+ """Run cross-repo analysis and contract extraction together.
+
+ Returns ``(overlay, store, extraction_ok)``; a failed phase yields an
+ empty result.
+ """
+ from ..contracts import ContractStore, run_contract_extraction
+ from ..cross_repo import CrossRepoOverlay, run_cross_repo_analysis
+
+ # Phases 1 and 2 are independent: they read disjoint inputs (git history and
+ # manifests vs source files and the symbol index), write different artifacts
+ # (cross_repo_edges.json vs contracts.json), and share no mutable state —
+ # boundaries_by_repo is computed above and passed in read-only. Both push
+ # their blocking work through asyncio.to_thread, so gather genuinely
+ # overlaps them rather than interleaving two synchronous bodies.
+ # Each coroutine times itself, so running them together does not cost the
+ # ability to say which one dominates — the question this instrumentation
+ # exists to answer, and one a single duration for the pair would destroy.
+ async def _timed(phase: str, coro: Awaitable[Any]) -> Any:
+ timings.on_phase_start(phase, None)
+ try:
+ return await coro
+ finally:
+ timings.on_phase_done(phase)
+
+ overlay_result, store_result = await asyncio.gather(
+ _timed(
+ "cross_repo_analysis", run_cross_repo_analysis(ws_config, workspace_root, changed_repos)
+ ),
+ _timed(
+ "contract_extraction",
+ run_contract_extraction(
+ ws_config,
+ workspace_root,
+ changed_repos,
+ boundaries_by_repo or None,
+ previous_store,
+ workspace_index,
+ ),
+ ),
+ return_exceptions=True,
+ )
+
+ # Cancellation and interpreter-level exits are not phase failures — the old
+ # `except Exception` let them propagate by construction, and gather's
+ # return_exceptions=True does not. Re-raise them before anything downstream
+ # treats a cancelled run as a completed one.
+ for result in (overlay_result, store_result):
+ if isinstance(result, BaseException) and not isinstance(result, Exception):
+ raise result
+
+ overlay = CrossRepoOverlay()
+ if isinstance(overlay_result, Exception):
+ _log.warning("Cross-repo analysis failed", exc_info=overlay_result)
+ else:
+ overlay = overlay_result
+
+ store = ContractStore()
+ extraction_ok = not isinstance(store_result, Exception)
+ if isinstance(store_result, Exception):
+ _log.warning("Contract extraction failed", exc_info=store_result)
+ else:
+ store = store_result
+
+ _log_phase(
+ timings,
+ "cross_repo_analysis",
+ co_changes=len(overlay.co_changes),
+ package_deps=len(overlay.package_deps),
+ )
+ _log_phase(
+ timings,
+ "contract_extraction",
+ contracts=len(store.contracts),
+ links=len(store.contract_links),
+ # Repos actually walked this run — the number that separates a real
+ # speed-up from a phase that got faster by doing less than it claims.
+ # Derived from the stamp rather than summing extraction_stats, which
+ # also carries the counters of the repos this run skipped.
+ repos_extracted=sum(
+ 1 for p in store.repo_provenance.values() if p.get("extracted_at") == store.generated_at
+ ),
+ repos_reused=sum(
+ 1 for p in store.repo_provenance.values() if p.get("extracted_at") != store.generated_at
+ ),
+ )
+ return overlay, store, extraction_ok
+
+
+async def _system_graph_phase(
+ ws_config: WorkspaceConfig,
+ workspace_root: Path,
+ timings: PhaseTimingRecorder,
+ store: ContractStore,
+ overlay: CrossRepoOverlay,
+ boundaries_by_repo: dict[str, list[ServiceBoundary]],
+) -> SystemGraph | None:
+ """Build the system graph, the service-granular structure every workspace view reads.
+
+ Built after extraction so it folds in the contracts and overlay.
+ """
+ from ..system_graph import run_system_graph_build
+
+ system_graph: SystemGraph | None = None
+ timings.on_phase_start("system_graph", None)
+ try:
+ system_graph = await run_system_graph_build(
+ ws_config, workspace_root, store, overlay, boundaries_by_repo or None
+ )
+ except Exception:
+ _log.warning("System graph build failed", exc_info=True)
+ timings.on_phase_done("system_graph")
+ _log_phase(
+ timings,
+ "system_graph",
+ nodes=len(system_graph.nodes) if system_graph else 0,
+ edges=len(system_graph.edges) if system_graph else 0,
+ )
+ return system_graph
+
+
+def _breaking_change_phase(
+ workspace_root: Path,
+ timings: PhaseTimingRecorder,
+ previous_store: ContractStore,
+ store: ContractStore,
+ extraction_ok: bool,
+) -> None:
+ """Diff the previous (on-disk) contracts against the fresh set and persist the report.
+
+ Gated on the SHAPE of the result, not on whether an exception escaped.
+ Diffing a populated baseline against an empty set reports every contract
+ in the workspace as removed, and extraction has more than one way to hand
+ back nothing: it raises, or it returns an empty store early because fewer
+ than two repos are currently indexed (a repo unmounted, renamed, or having
+ just lost its .repowise/). Both would publish themselves as the largest
+ breaking change the workspace has ever seen. An empty result is only
+ trustworthy when the baseline is empty too.
+ """
+ from ..breaking_change import run_breaking_change_detection
+
+ if extraction_ok and (store.contracts or not previous_store.contracts):
+ report = None
+ timings.on_phase_start("breaking_change", None)
+ try:
+ report = run_breaking_change_detection(workspace_root, previous_store, store)
+ except Exception:
+ _log.warning("Breaking-change detection failed", exc_info=True)
+ timings.on_phase_done("breaking_change")
+ _log_phase(
+ timings,
+ "breaking_change",
+ breaking=len(report.changes) if report else 0,
+ )
+ else:
+ _log.warning(
+ "Skipping breaking-change detection: extraction produced no contracts "
+ "(ok=%s) while the previous artifact holds %d — diffing these would "
+ "report the whole workspace as removed",
+ extraction_ok,
+ len(previous_store.contracts),
+ )
+
+
+def _conformance_phase(
+ ws_config: WorkspaceConfig,
+ workspace_root: Path,
+ timings: PhaseTimingRecorder,
+ system_graph: SystemGraph,
+) -> None:
+ """Check declared dependency rules and service cycles over the system graph."""
+ from ..conformance import run_conformance_check
+
+ conformance = None
+ timings.on_phase_start("conformance", None)
+ try:
+ conformance = run_conformance_check(ws_config, workspace_root, system_graph)
+ except Exception:
+ _log.warning("Conformance check failed", exc_info=True)
+ timings.on_phase_done("conformance")
+ _log_phase(
+ timings,
+ "conformance",
+ rules=conformance.rules_evaluated if conformance else 0,
+ violations=len(conformance.violations) if conformance else 0,
+ # The true total, not the capped list — a workspace with 500 cycles
+ # must not report the same number as one with 50.
+ cycles=conformance.total_cycles if conformance else 0,
+ )
diff --git a/packages/core/src/repowise/core/workspace/update/repo.py b/packages/core/src/repowise/core/workspace/update/repo.py
new file mode 100644
index 000000000..9b0aa3fbc
--- /dev/null
+++ b/packages/core/src/repowise/core/workspace/update/repo.py
@@ -0,0 +1,478 @@
+"""Single-repo index refresh: the incremental path with a full-pipeline fallback."""
+
+from __future__ import annotations
+
+import json as _json
+import logging
+import sqlite3
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any
+
+from ...ingestion.git_indexer import git_history_stale
+from ...ingestion.git_indexer._constants import _DEFAULT_COMMIT_LIMIT
+from .state import commit_exists, get_head_commit, read_repo_state
+
+_log = logging.getLogger("repowise.workspace.update")
+
+
+async def _merged_repo_excludes(
+ repo_path: Path,
+ extra_exclude_patterns: list[str] | None = None,
+) -> list[str]:
+ """Merge config.yaml excludes with the persisted repo settings' excludes.
+
+ Local indexes read ``settings_json`` straight from the repo-local
+ ``wiki.db`` (cheaper than an engine for one row); a configured shared
+ database is the source of truth instead.
+ """
+ from ...repo_config import load_repo_config
+
+ patterns: list[str] = list(load_repo_config(repo_path).get("exclude_patterns") or [])
+
+ from ...persistence.database import get_configured_db_url
+
+ configured_url = get_configured_db_url()
+ settings_json: str | None = None
+
+ if configured_url is None:
+ db_path = repo_path / ".repowise" / "wiki.db"
+ if db_path.is_file():
+ try:
+ with sqlite3.connect(str(db_path)) as conn:
+ row = conn.execute("SELECT settings_json FROM repositories LIMIT 1").fetchone()
+ if row and row[0]:
+ settings_json = row[0]
+ except Exception:
+ pass
+ else:
+ from ...persistence import (
+ create_engine,
+ create_session_factory,
+ get_session,
+ init_db,
+ )
+ from ...persistence.crud import get_repository_by_path
+
+ try:
+ engine = create_engine(configured_url)
+ try:
+ await init_db(engine)
+ sf = create_session_factory(engine)
+ async with get_session(sf) as session:
+ repo = await get_repository_by_path(session, str(repo_path))
+ if repo is not None and repo.settings_json:
+ settings_json = repo.settings_json
+ finally:
+ await engine.dispose()
+ except Exception:
+ pass
+
+ if settings_json:
+ try:
+ settings = _json.loads(settings_json)
+ if isinstance(settings, dict):
+ for value in settings.get("exclude_patterns") or []:
+ if isinstance(value, str) and value not in patterns:
+ patterns.append(value)
+ except Exception:
+ pass
+
+ for pattern in extra_exclude_patterns or []:
+ if pattern not in patterns:
+ patterns.append(pattern)
+ return patterns
+
+
+@dataclass
+class RepoUpdateResult:
+ """Result of updating a single repo within a workspace."""
+
+ alias: str
+ updated: bool # True if an update was performed
+ skipped_reason: str | None = None # "up_to_date", "missing_directory", etc.
+ # How long the winning update had held the lock, when this repo deferred to
+ # one. Carried on the result because the caller reports the deferral and
+ # the age is the part that tells a slow update apart from a wedged one.
+ lock_age_seconds: float | None = None
+ file_count: int = 0
+ 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, so the block rides on the result.
+ kg_state: dict[str, Any] | None = None
+ # Repo-relative paths this run indexed from the working tree rather than
+ # from a commit. Persisted as state.json "working_tree_paths" so the next
+ # run can tell which of them have since been reverted or deleted — working
+ # tree state has no ``last_sync_commit`` to diff against. None on the
+ # commit-anchored path, which leaves the stored list alone.
+ working_tree_paths: list[str] | None = None
+ phase_timings: dict[str, float] | None = None
+ # True when this run walked the whole git history and persisted every row,
+ # so the caller stamps ``git_history_version``.
+ git_history_refreshed: bool = False
+
+
+async def _incremental_repo_update(
+ repo_path: Path,
+ *,
+ state: dict[str, Any],
+ base_ref: str,
+ exclude_patterns: list[str] | None = None,
+ include_working_tree: bool = False,
+ force_full_git: bool = False,
+) -> RepoUpdateResult | None:
+ """Refresh an already-indexed repo through the incremental update path.
+
+ Mirrors the single-repo ``repowise update --index-only`` flow: diff
+ ``base_ref..HEAD``, rebuild the graph (parse-cache backed), re-index git
+ metadata for the changed files only, run partial health/dead-code
+ analysis, and upsert the results. Deletions and renames prune stale rows
+ and tombstone pages, as the single-repo path does. State-file updates stay
+ with the caller.
+
+ Raises on failure — the caller falls back to the full pipeline.
+ """
+ from ...ingestion.change_detector import ChangeDetector, merge_file_diffs
+ from ...pipeline.incremental import (
+ DocDriftUpdate,
+ persist_incremental_index,
+ rebuild_graph_and_git,
+ run_doc_drift_partial,
+ run_partial_analysis,
+ )
+ from ...pipeline.phases.git import drop_transient_git_signals
+
+ alias = repo_path.name
+ head = get_head_commit(repo_path) or "HEAD"
+
+ detector = ChangeDetector(repo_path)
+ working_tree_diffs: list = []
+ working_tree_paths: list[str] | None = None
+ if include_working_tree:
+ working_tree_diffs = detector.get_working_tree_changes()
+ dirty = {fd.path for fd in working_tree_diffs}
+ # Re-diff anything the last run indexed from the working tree that no
+ # longer diverges from HEAD, so a reverted edit or a deleted untracked
+ # file stops being served. See ``stale_working_tree_diffs``.
+ working_tree_diffs += detector.stale_working_tree_diffs(
+ state.get("working_tree_paths") or [], dirty
+ )
+ working_tree_paths = sorted(dirty)
+
+ file_diffs = merge_file_diffs(
+ detector.get_changed_files(base_ref, head),
+ working_tree_diffs,
+ )
+ if not file_diffs and not force_full_git:
+ # New commits but nothing the index cares about changed (merge/empty
+ # commits, or every change excluded). Report success so the caller
+ # bumps ``last_sync_commit`` instead of re-diffing forever.
+ return RepoUpdateResult(alias=alias, updated=True, working_tree_paths=working_tree_paths)
+
+ # Per-repo config, like the single-repo update path. The workspace-level
+ # ``exclude_patterns`` (when provided) apply on top.
+ from ...repo_config import load_repo_config
+
+ cfg = load_repo_config(repo_path)
+ merged_excludes = await _merged_repo_excludes(repo_path, exclude_patterns)
+
+ # Decay-only rows for idle files, persisted beside the changed rows but kept
+ # out of git_meta_map so partial health's repo-wide aggregates are unaffected.
+ git_decay_map: dict[str, dict] = {}
+ full_git_summaries: list[Any] = []
+ (
+ parsed_files,
+ source_map,
+ graph_builder,
+ _structure,
+ file_count,
+ git_meta_map,
+ ) = await rebuild_graph_and_git(
+ repo_path,
+ file_diffs,
+ cfg,
+ merged_excludes,
+ git_tier=state.get("git_tier"),
+ include_submodules=bool(state.get("include_submodules", False)),
+ include_nested_repos=bool(state.get("include_nested_repos", False)),
+ idle_decay_sink=git_decay_map,
+ force_full_git=force_full_git,
+ git_summary_sink=full_git_summaries,
+ log=_log.info,
+ )
+
+ # Stored per-file git fields: ``git_meta_map`` covers only the changed files,
+ # and an empty dict reads as "no commits in 90 days" to the dead-code analyzer.
+ from ...pipeline.incremental import (
+ load_stored_coverage_map,
+ load_stored_function_mod_p80,
+ load_stored_git_meta,
+ load_stored_performance_callers,
+ )
+
+ stored_git_meta = await load_stored_git_meta(repo_path, log=_log.info)
+ # Repo-wide p80, so the Function Hotspot gate scores against the full repo.
+ stored_function_mod_p80 = await load_stored_function_mod_p80(repo_path, log=_log.info)
+ performance_changed_paths = {diff.path for diff in file_diffs}
+ performance_changed_paths.update(
+ diff.old_path for diff in file_diffs if getattr(diff, "old_path", None)
+ )
+ stored_performance_callers = await load_stored_performance_callers(
+ repo_path, performance_changed_paths, log=_log.info
+ )
+ # Without a coverage_map the changed files would lose their stored coverage.
+ stored_coverage_map = await load_stored_coverage_map(repo_path, log=_log.info)
+
+ partial_health_report, dead_code_report = run_partial_analysis(
+ repo_path,
+ graph_builder,
+ git_meta_map,
+ parsed_files,
+ file_diffs,
+ source_map=source_map,
+ stored_git_meta=stored_git_meta,
+ stored_performance_callers=stored_performance_callers,
+ repo_function_mod_p80=stored_function_mod_p80,
+ coverage_map=stored_coverage_map,
+ log=_log.info,
+ )
+ doc_drift_report = run_doc_drift_partial(
+ graph_builder,
+ source_map,
+ repo_path=repo_path,
+ log=_log.info,
+ update=DocDriftUpdate.from_file_diffs(base_ref, file_diffs),
+ )
+
+ # Drop the transient, non-serializable ``BlameIndex`` before persistence.
+ drop_transient_git_signals(list(git_meta_map.values()))
+
+ # Refresh the knowledge graph (layers/tour/entry points) when the graph shape changed.
+ 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,
+ )
+
+ # A full walk is stamped only when its rows reached the store.
+ failed_steps: list[str] = []
+ await persist_incremental_index(
+ repo_path,
+ graph_builder,
+ git_meta_map,
+ dead_code_report,
+ partial_health_report,
+ [fd.path for fd in file_diffs],
+ doc_drift_report=doc_drift_report,
+ current_graph_file_paths={pf.file_info.path for pf in parsed_files},
+ # Tombstones pages for deleted/renamed paths.
+ file_diffs=file_diffs,
+ knowledge_graph_result=kg,
+ parsed_files=parsed_files,
+ source_map=source_map,
+ git_decay_map=git_decay_map,
+ full_git_summary=full_git_summaries[0] if full_git_summaries else None,
+ failed_steps=failed_steps,
+ 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,
+ working_tree_paths=working_tree_paths,
+ git_history_refreshed=bool(full_git_summaries) and "Git persist" not in failed_steps,
+ )
+
+
+async def _has_persisted_repo_index(repo_path: Path) -> bool:
+ """Return whether this repo has persisted index data.
+
+ Local SQLite indexes are identified by their repo-local wiki.db.
+ When a shared database is configured, the repository row is the source
+ of truth instead; a repo-local wiki.db is not expected to exist.
+ """
+ from ...persistence.database import get_configured_db_url
+
+ if get_configured_db_url() is None:
+ return (repo_path / ".repowise" / "wiki.db").is_file()
+
+ from ...persistence import (
+ create_engine,
+ create_session_factory,
+ get_session,
+ init_db,
+ )
+ from ...persistence.crud import get_repository_by_path
+
+ engine = create_engine(get_configured_db_url())
+ try:
+ await init_db(engine)
+ sf = create_session_factory(engine)
+ async with get_session(sf) as session:
+ return await get_repository_by_path(session, str(repo_path)) is not None
+ finally:
+ await engine.dispose()
+
+
+async def update_single_repo_index(
+ repo_path: Path,
+ *,
+ commit_depth: int = _DEFAULT_COMMIT_LIMIT,
+ exclude_patterns: list[str] | None = None,
+ include_working_tree: bool = False,
+ progress: Any | None = None,
+) -> RepoUpdateResult:
+ """Refresh the index for a single repo.
+
+ Already-indexed repos (a persisted ``last_sync_commit`` whose commit
+ still resolves, plus an existing ``wiki.db``) go through the incremental
+ update path — changed-files diff, partial analysis, upsert persistence.
+ Never-indexed repos, config changes (``config.yaml`` / health-rules
+ fingerprint drift, which invalidates every persisted score), and any
+ incremental failure run the full ingestion pipeline instead (index-only —
+ no wiki pages).
+ """
+ from ...repo_config import (
+ changed_config_dependencies,
+ config_dependency_fingerprints,
+ config_fingerprint,
+ load_repo_config,
+ )
+
+ alias = repo_path.name
+ state = read_repo_state(repo_path)
+ base_ref = state.get("last_sync_commit")
+ merged_excludes = await _merged_repo_excludes(repo_path, exclude_patterns)
+ repo_config = load_repo_config(repo_path)
+ repo_commit_depth = int(repo_config.get("commit_limit", commit_depth))
+ repo_follow_renames = bool(repo_config.get("follow_renames", False))
+
+ # Config drift check, mirroring the single-repo update path: a changed
+ # config.yaml / health-rules.json invalidates persisted health scores and
+ # exclude handling, so the incremental (changed-files-only) path must not
+ # run. The full pipeline below re-derives everything under the new config;
+ # the workspace pass stamps the new fingerprint into state.json afterwards.
+ # A missing stored fingerprint (legacy state) is NOT drift — same as the
+ # single-repo path, which only stamps it — so legacy repos don't pay a
+ # surprise full re-index.
+ stored_fp = state.get("config_fingerprint")
+ config_changed = stored_fp is not None and stored_fp != config_fingerprint(repo_path)
+ current_dependency_fps = config_dependency_fingerprints(repo_path, config=repo_config)
+ changed_dependencies = (
+ changed_config_dependencies(
+ state.get("config_dependency_fingerprints"), current_dependency_fps
+ )
+ if config_changed
+ else set()
+ )
+ # Workspace indexing has no generation layer. Only settings that affect
+ # its persisted graph/history/health stores require a full re-index;
+ # formatting, distill/MCP, and generation-only edits are state updates.
+ requires_full_reindex = config_changed and (
+ changed_dependencies is None
+ or bool((changed_dependencies or set()) - {"state_only", "generation"})
+ )
+ require_git_success = requires_full_reindex and (
+ changed_dependencies is None
+ or bool({"traversal", "git_history", "other"} & (changed_dependencies or set()))
+ )
+ require_health_success = requires_full_reindex and (
+ changed_dependencies is None
+ or bool(
+ {"traversal", "git_history", "health", "other"}
+ & (changed_dependencies or set())
+ )
+ )
+ has_persisted_index = await _has_persisted_repo_index(repo_path)
+ if requires_full_reindex and has_persisted_index:
+ _log.info(
+ "workspace_update: %s config fingerprint drifted — full re-index "
+ "so health scores reflect the new config",
+ alias,
+ )
+
+ if (
+ not requires_full_reindex
+ and base_ref
+ and has_persisted_index
+ and commit_exists(repo_path, str(base_ref))
+ ):
+ try:
+ incremental_result = await _incremental_repo_update(
+ repo_path,
+ state=state,
+ base_ref=str(base_ref),
+ exclude_patterns=exclude_patterns,
+ include_working_tree=include_working_tree,
+ force_full_git=git_history_stale(state),
+ )
+ if incremental_result is not None:
+ return incremental_result
+ except Exception:
+ _log.warning(
+ "Incremental update failed for %s — falling back to the full pipeline",
+ repo_path,
+ exc_info=True,
+ )
+
+ try:
+ from ...pipeline.full_index import index_repo_full
+
+ result = await index_repo_full(
+ repo_path,
+ commit_depth=repo_commit_depth,
+ exclude_patterns=merged_excludes,
+ include_submodules=bool(state.get("include_submodules", False)),
+ include_nested_repos=bool(state.get("include_nested_repos", False)),
+ follow_renames=repo_follow_renames,
+ require_git_success=require_git_success,
+ require_health_success=require_health_success,
+ progress=progress,
+ )
+
+ # index_repo_full already exported knowledge-graph.json; build the
+ # state.json summary block so the workspace pass stamps it too.
+ 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
+
+ kg_state = build_kg_state(kg)
+
+ return RepoUpdateResult(
+ alias=alias,
+ updated=True,
+ file_count=result.file_count,
+ symbol_count=result.symbol_count,
+ kg_state=kg_state,
+ git_history_refreshed=getattr(result, "git_summary", None) is not None,
+ )
+ except Exception as exc:
+ return RepoUpdateResult(
+ alias=alias,
+ updated=False,
+ error=str(exc),
+ )
diff --git a/packages/core/src/repowise/core/workspace/update/state.py b/packages/core/src/repowise/core/workspace/update/state.py
new file mode 100644
index 000000000..e2df51d03
--- /dev/null
+++ b/packages/core/src/repowise/core/workspace/update/state.py
@@ -0,0 +1,322 @@
+"""HEAD, commit and ``state.json`` helpers shared by the workspace update paths."""
+
+from __future__ import annotations
+
+import asyncio
+import json as _json
+import logging
+import subprocess
+from contextlib import suppress
+from datetime import UTC, datetime
+from pathlib import Path
+from typing import Any, NamedTuple
+
+from ..config import WorkspaceConfig
+
+_log = logging.getLogger("repowise.workspace.update")
+
+
+def get_head_commit(repo_path: Path) -> str | None:
+ """Return the current HEAD commit SHA via git, or ``None``."""
+ try:
+ result = subprocess.run(
+ ["git", "rev-parse", "HEAD"],
+ cwd=str(repo_path),
+ capture_output=True,
+ text=True,
+ timeout=10,
+ )
+ if result.returncode == 0:
+ return result.stdout.strip()
+ except Exception:
+ pass
+ return None
+
+
+def count_commits_between(repo_path: Path, base: str, head: str) -> int:
+ """Return the number of commits between *base* and *head*, or 0 on error."""
+ try:
+ result = subprocess.run(
+ ["git", "rev-list", "--count", f"{base}..{head}"],
+ cwd=str(repo_path),
+ capture_output=True,
+ text=True,
+ timeout=10,
+ )
+ if result.returncode == 0:
+ return int(result.stdout.strip())
+ except Exception:
+ pass
+ return 0
+
+
+def commit_exists(repo_path: Path, sha: str) -> bool:
+ """Return True when *sha* resolves to a commit in *repo_path*.
+
+ The incremental path must verify this itself: ``ChangeDetector`` returns
+ an **empty** diff for unresolvable refs, which would masquerade as "no
+ changes" and let the caller bump ``last_sync_commit`` past commits that
+ were never indexed (e.g. after a rebase or an aggressive ``git gc``).
+ """
+ try:
+ result = subprocess.run(
+ ["git", "cat-file", "-e", f"{sha}^{{commit}}"],
+ cwd=str(repo_path),
+ capture_output=True,
+ timeout=10,
+ )
+ return result.returncode == 0
+ except Exception:
+ return False
+
+
+def clear_stale_update_pending(repo_path: Path, indexed_head: str | None) -> None:
+ """Drop ``.repowise/.update.pending`` once the index has caught up to it.
+
+ A deferred update records the latest HEAD in this marker; the update that
+ holds the lock calls this on success. The marker is kept only when it
+ points strictly *ahead* of ``indexed_head``; equal, ancestor and
+ unresolvable commits are cleared.
+ """
+ pending_path = repo_path / ".repowise" / ".update.pending"
+ try:
+ pending_head = pending_path.read_text(encoding="utf-8").strip()
+ except OSError:
+ return
+ if pending_head and indexed_head and pending_head != indexed_head:
+ try:
+ # indexed_head is an ancestor of pending_head => strictly ahead,
+ # keep it. Non-zero (incl. unresolvable pending) => safe to clear.
+ ahead = subprocess.run(
+ ["git", "merge-base", "--is-ancestor", indexed_head, pending_head],
+ cwd=str(repo_path),
+ capture_output=True,
+ timeout=10,
+ )
+ if ahead.returncode == 0:
+ return
+ except Exception:
+ pass
+ with suppress(OSError):
+ pending_path.unlink(missing_ok=True)
+
+
+def read_repo_state(repo_path: Path) -> dict[str, Any]:
+ """Return the parsed ``<repo>/.repowise/state.json``, or ``{}``."""
+ state_path = repo_path / ".repowise" / "state.json"
+ if not state_path.is_file():
+ return {}
+ try:
+ data = _json.loads(state_path.read_text(encoding="utf-8"))
+ return data if isinstance(data, dict) else {}
+ except Exception:
+ return {}
+
+
+def read_state_commit(repo_path: Path) -> str | None:
+ """Return ``last_sync_commit`` from ``<repo>/.repowise/state.json`` or None."""
+ sha = read_repo_state(repo_path).get("last_sync_commit")
+ return str(sha) if sha else None
+
+
+class IndexedCommit(NamedTuple):
+ """The commit an index describes, or why it cannot be named."""
+
+ sha: str | None
+ problem: str | None = None
+
+
+def resolve_indexed_commit(repo_path: Path | None, row_commit: str | None) -> IndexedCommit:
+ """The commit the index describes, from ``state.json`` and the repository row.
+
+ Every update writes both from one captured head, so they normally agree.
+ When one is an ancestor of the other (an update interrupted between the
+ two writes, or a row an older build left behind), the index describes the
+ older: the files between them then count as changed since the index was
+ built, which over-selects rather than misses. Two commits neither of which
+ contains the other (a rebase, a restored backup), or a sha git cannot
+ read, leave the commit unknown.
+ """
+ state = read_state_commit(repo_path) if repo_path is not None else None
+ if not state or not row_commit or state == row_commit:
+ return IndexedCommit(state or row_commit)
+ older = _older_commit(str(repo_path), state, row_commit)
+ if older is not None:
+ return IndexedCommit(older)
+ return IndexedCommit(
+ None,
+ f"The index records two commits ({state[:7]} in state.json, {row_commit[:7]} "
+ "in its database) and neither contains the other, so what it describes is "
+ "unknown; run `repowise update`.",
+ )
+
+
+# (repo_path, a, b) -> the older commit, or None when neither contains the
+# other. Only definite answers: a timeout or an unknown sha is asked again.
+_ancestry_cache: dict[tuple[str, str, str], str | None] = {}
+_ANCESTRY_CACHE_MAX = 32
+
+
+def _older_commit(repo_path: str, a: str, b: str) -> str | None:
+ """The one of *a*, *b* that is an ancestor of the other, else ``None``.
+
+ Cached because the freshness envelope asks on every response while the two
+ stamps disagree. Ancestry between two known shas never changes, and the
+ next update makes the stamps equal, which ends the asking.
+ """
+ from ...git_refs import is_ancestor
+
+ key = (repo_path, a, b)
+ if key in _ancestry_cache:
+ return _ancestry_cache[key]
+ a_first = is_ancestor(repo_path, a, b)
+ b_first = None if a_first else is_ancestor(repo_path, b, a)
+ older = a if a_first else b if b_first else None
+ if older is not None or (a_first is False and b_first is False):
+ if len(_ancestry_cache) >= _ANCESTRY_CACHE_MAX:
+ _ancestry_cache.clear()
+ _ancestry_cache[key] = older
+ return older
+
+
+def sync_workspace_state_from_disk(
+ workspace_root: Path,
+ ws_config: WorkspaceConfig,
+ *,
+ save_if_changed: bool = True,
+) -> list[str]:
+ """Refresh ``WorkspaceConfig`` entries from each repo's on-disk
+ ``state.json``.
+
+ A child repo can be updated outside the workspace orchestrator (the
+ user runs ``repowise update`` inside the child dir directly), which
+ drifts ``RepoEntry.last_commit_at_index`` away from the actual
+ ``state.json`` value. Call this before any workspace-level decision
+ that reads from ``ws_config`` so we never act on stale info.
+
+ Returns the list of aliases that changed.
+ """
+ changed: list[str] = []
+ for entry in ws_config.repos:
+ abs_path = (workspace_root / entry.path).resolve()
+ if not abs_path.is_dir():
+ continue
+ disk_commit = read_state_commit(abs_path)
+ if disk_commit is not None and disk_commit != entry.last_commit_at_index:
+ entry.last_commit_at_index = disk_commit
+ changed.append(entry.alias)
+ if changed and save_if_changed:
+ try:
+ ws_config.save(workspace_root)
+ except Exception:
+ # Saving is best-effort — the in-memory sync still happened.
+ _log.warning("Could not persist synced workspace config", exc_info=True)
+ return changed
+
+
+def check_repo_staleness(
+ repo_path: Path,
+ last_commit: str | None,
+) -> tuple[bool, str | None, int]:
+ """Check if a repo has new commits since *last_commit*.
+
+ Returns ``(is_stale, current_head, commits_behind)``.
+ """
+ current_head = get_head_commit(repo_path)
+ if current_head is None:
+ return False, None, 0
+
+ if last_commit is None:
+ # Never indexed — treat as stale
+ return True, current_head, 0
+
+ if current_head == last_commit:
+ # Same reconciliation as the single-repo update: a page can be stale
+ # with HEAD unmoved, and only an update clears it.
+ try:
+ from repowise.core.persistence import load_stale_structural_file_paths
+
+ if load_stale_structural_file_paths(repo_path):
+ return True, current_head, 0
+ except Exception:
+ _log.debug("stale page probe failed for %s", repo_path, exc_info=True)
+ return False, current_head, 0
+
+ behind = count_commits_between(repo_path, last_commit, current_head)
+ return True, current_head, behind
+
+
+def restamp_changed_sync_commit(repo_path: Path, previous: str | None, current: str | None) -> None:
+ """Move the repository row to a ``last_sync_commit`` a state write just changed.
+
+ The CLI and server state writers call this (the workspace updater awaits
+ :func:`reconcile_repo_head_commit` itself), so a path that advances the
+ sync commit leaves the row on the same commit, whatever HEAD its persist
+ step read (a pull during a long run moves it). An unchanged commit is left
+ alone: the "up to date" paths stamp it themselves. The state file is
+ already written, so a failure here is logged, not raised.
+ """
+ if not current or current == previous:
+ return
+
+ try:
+ asyncio.get_running_loop()
+ except RuntimeError:
+ pass
+ else:
+ # Ceiling: callers must be off-loop; skipped here, the resolver still
+ # reads the ancestor pair this leaves correctly.
+ _log.warning("Skipped the repository row restamp for %s: called on an event loop", repo_path)
+ return
+ try:
+ asyncio.run(reconcile_repo_head_commit(repo_path, current))
+ except Exception:
+ _log.warning("Could not restamp the repository row for %s", repo_path, exc_info=True)
+
+
+async def reconcile_repo_head_commit(repo_path: Path, head: str | None) -> None:
+ """Advance the DB freshness for *repo_path* after a sync-check to *head*.
+
+ The "up to date" skip and the no-relevant-changes incremental path bump
+ ``last_sync_commit`` without re-running the persistence that stamps the
+ ``repositories`` row, which the server reads for the indexed commit and
+ the "indexed at" time. Stamps ``head_commit`` only on drift but always
+ advances ``updated_at``. Creates a missing row in an existing store (a
+ configured database counts as existing); a no-op when no store exists.
+ The single head-commit stamper for the CLI and workspace update paths.
+ """
+ from ...persistence.database import has_db_store, resolve_db_url
+
+ if not head or not has_db_store(repo_path):
+ return
+
+ from ...persistence import (
+ create_engine,
+ create_session_factory,
+ get_session,
+ init_db,
+ upsert_repository,
+ )
+ from ...persistence.crud import get_repository_by_path
+
+ url = resolve_db_url(repo_path)
+ engine = create_engine(url)
+ try:
+ await init_db(engine)
+ sf = create_session_factory(engine)
+ async with get_session(sf) as session:
+ repo = await get_repository_by_path(session, str(repo_path))
+ if repo is None:
+ await upsert_repository(
+ session,
+ name=repo_path.name,
+ local_path=str(repo_path),
+ head_commit=head,
+ )
+ else:
+ if repo.head_commit != head:
+ repo.head_commit = head
+ repo.updated_at = datetime.now(UTC)
+ await session.flush()
+ finally:
+ await engine.dispose()
diff --git a/packages/core/src/repowise/core/workspace/update/workspace_pass.py b/packages/core/src/repowise/core/workspace/update/workspace_pass.py
new file mode 100644
index 000000000..35a5470ca
--- /dev/null
+++ b/packages/core/src/repowise/core/workspace/update/workspace_pass.py
@@ -0,0 +1,466 @@
+"""One workspace update pass: select stale members, update them in parallel, run the hooks."""
+
+from __future__ import annotations
+
+import asyncio
+import json as _json
+import logging
+import time
+from collections.abc import Callable
+from contextlib import suppress
+from dataclasses import dataclass
+from datetime import UTC, datetime
+from pathlib import Path
+from typing import Any, NamedTuple
+
+# The shared single-flight guards: ``update_single_repo_index`` bypasses the CLI
+# lock acquisition, so the workspace pass takes the per-repo lock itself.
+from repowise.core.update_lock import (
+ lock_age_seconds as _lock_age_seconds,
+)
+from repowise.core.update_lock import (
+ release_update_lock as _release_lock,
+)
+from repowise.core.update_lock import (
+ release_workspace_lock as _release_workspace_lock,
+)
+from repowise.core.update_lock import (
+ try_acquire_update_lock as _try_acquire_lock,
+)
+from repowise.core.update_lock import (
+ update_workspace_lock as _try_acquire_workspace_lock,
+)
+
+from ...docs_mode import docs_mode_state_fields
+from ...ingestion.change_detector import has_working_tree_changes
+from ...ingestion.git_indexer import (
+ GIT_HISTORY_VERSION,
+ GIT_HISTORY_VERSION_KEY,
+ git_history_stale,
+)
+from ...ingestion.git_indexer._constants import _DEFAULT_COMMIT_LIMIT
+from ..config import RepoEntry, WorkspaceConfig
+from .phases import run_cross_repo_hooks
+from .repo import RepoUpdateResult, _has_persisted_repo_index, update_single_repo_index
+from .state import (
+ check_repo_staleness,
+ clear_stale_update_pending,
+ reconcile_repo_head_commit,
+ sync_workspace_state_from_disk,
+)
+
+_log = logging.getLogger("repowise.workspace.update")
+
+
+_MAX_CONCURRENT_UPDATES = 4
+
+
+class _StaleRepo(NamedTuple):
+ """A workspace member selected for this update pass."""
+
+ alias: str
+ path: Path
+ new_head: str
+ first_time: bool
+
+
+@dataclass
+class _RepoUpdatePass:
+ """What every per-repo update in one workspace pass shares."""
+
+ ws_config: WorkspaceConfig
+ semaphore: asyncio.Semaphore
+ commit_depth: int
+ exclude_patterns: list[str] | None
+ include_working_tree: bool
+ on_repo_start: Callable[[str], None] | None
+ on_repo_done: Callable[[RepoUpdateResult], None] | None
+
+
+async def update_workspace(
+ workspace_root: Path,
+ ws_config: WorkspaceConfig,
+ *,
+ repo_filter: str | None = None,
+ only_aliases: set[str] | None = None,
+ run_hooks: bool = True,
+ dry_run: bool = False,
+ commit_depth: int = _DEFAULT_COMMIT_LIMIT,
+ exclude_patterns: list[str] | None = None,
+ include_working_tree: bool = False,
+ on_repo_start: Callable[[str], None] | None = None,
+ on_repo_done: Callable[[RepoUpdateResult], None] | None = None,
+) -> list[RepoUpdateResult]:
+ """Update stale repos in the workspace (index-only).
+
+ Args:
+ workspace_root: Path to the workspace root directory.
+ ws_config: Loaded workspace configuration.
+ repo_filter: If set, only update this repo alias.
+ only_aliases: If set, restrict the run to this subset of aliases (on
+ top of ``repo_filter``). The CLI uses this to hand the fast
+ index-only path just the repos it isn't updating via the
+ single-repo docs path, so the two orchestrators never touch the
+ same repo in one workspace run.
+ run_hooks: When False, skip the cross-repo analysis hooks at the end.
+ The CLI sets this so it can run them once over the union of
+ index-only and docs repos, instead of on a partial set here.
+ dry_run: If True, detect staleness but don't actually update.
+ commit_depth: Max commits to analyze per file.
+ exclude_patterns: Gitignore-style patterns to exclude.
+ include_working_tree: Count uncommitted work as staleness, and index
+ it. Off for every commit-anchored caller (hooks, webhooks, a
+ manual sync); ``repowise watch --workspace`` sets it, because a
+ repo it is watching normally has no new commits at all.
+ on_repo_start: Called with alias when a repo update begins.
+ on_repo_done: Called with result when a repo update finishes.
+
+ Returns:
+ List of :class:`RepoUpdateResult` for each repo.
+ """
+ results: list[RepoUpdateResult] = []
+ entries = _entries_for_run(ws_config, repo_filter, only_aliases)
+
+ # A child repo may have been updated on its own; read its state.json first.
+ sync_workspace_state_from_disk(workspace_root, ws_config)
+
+ stale_repos = await _select_stale_repos(workspace_root, entries, include_working_tree, results)
+ if dry_run or not stale_repos:
+ return results
+
+ # Workspace single-flight: concurrent hook-triggered passes defer to the
+ # one holding this lock by leaving a pending marker per stale repo, so the
+ # running pass rolls forward instead of a second full pass starting.
+ workspace_owner = _try_acquire_workspace_lock(workspace_root)
+ if workspace_owner is not None:
+ return _defer_to_running_workspace_update(workspace_owner, stale_repos)
+
+ # The workspace lock is held until every member has been attempted.
+ try:
+ update_pass = _RepoUpdatePass(
+ ws_config=ws_config,
+ semaphore=asyncio.Semaphore(_MAX_CONCURRENT_UPDATES),
+ commit_depth=commit_depth,
+ exclude_patterns=exclude_patterns,
+ include_working_tree=include_working_tree,
+ on_repo_start=on_repo_start,
+ on_repo_done=on_repo_done,
+ )
+ update_results = await asyncio.gather(
+ *[_update_stale_repo(update_pass, repo) for repo in stale_repos],
+ return_exceptions=True,
+ )
+ changed_aliases = _collect_update_results(update_results, results)
+ await _finish_workspace_pass(ws_config, workspace_root, changed_aliases, run_hooks)
+ return results
+ finally:
+ _release_workspace_lock(workspace_root)
+
+
+def _entries_for_run(
+ ws_config: WorkspaceConfig,
+ repo_filter: str | None,
+ only_aliases: set[str] | None,
+) -> list[RepoEntry]:
+ """The workspace entries this run considers, after both filters."""
+ entries = ws_config.repos
+ if repo_filter:
+ entry = ws_config.get_repo(repo_filter)
+ if entry is None:
+ available = ", ".join(ws_config.repo_aliases())
+ raise ValueError(f"Unknown repo '{repo_filter}'. Available: {available}")
+ entries = [entry]
+
+ if only_aliases is not None:
+ entries = [e for e in entries if e.alias in only_aliases]
+ return entries
+
+
+async def _select_stale_repos(
+ workspace_root: Path,
+ entries: list[RepoEntry],
+ include_working_tree: bool,
+ results: list[RepoUpdateResult],
+) -> list[_StaleRepo]:
+ """Return the stale entries; append a skipped result for every other one."""
+ stale_repos: list[_StaleRepo] = []
+ for entry in entries:
+ abs_path = (workspace_root / entry.path).resolve()
+ if not abs_path.is_dir():
+ results.append(
+ RepoUpdateResult(
+ alias=entry.alias,
+ updated=False,
+ skipped_reason="missing_directory",
+ )
+ )
+ continue
+
+ is_stale, current_head = await _repo_is_stale(abs_path, include_working_tree)
+ if not is_stale:
+ # Nothing to regenerate, but the DB freshness stamp can still be
+ # behind; reconcile it so the server stops reporting "index behind checkout".
+ await reconcile_repo_head_commit(abs_path, current_head)
+ results.append(
+ RepoUpdateResult(
+ alias=entry.alias,
+ updated=False,
+ skipped_reason="up_to_date",
+ )
+ )
+ continue
+
+ # First-time indexing runs the full pipeline; the `.repowise/` dir is
+ # created on demand by ``update_single_repo_index`` (resolve_db_url)
+ # and ``state.json`` is written by ``_write_repo_state``.
+ first_time = not (abs_path / ".repowise").is_dir()
+ stale_repos.append(_StaleRepo(entry.alias, abs_path, current_head or "", first_time))
+ return stale_repos
+
+
+async def _repo_is_stale(abs_path: Path, include_working_tree: bool) -> tuple[bool, str | None]:
+ """Return ``(is_stale, current_head)`` for one workspace member."""
+ from ...repo_config import config_fingerprint
+
+ # Check staleness against stored commit in state.json
+ state_path = abs_path / ".repowise" / "state.json"
+ stored_commit = None
+ state: dict[str, Any] = {}
+ if state_path.is_file():
+ try:
+ state = _json.loads(state_path.read_text(encoding="utf-8"))
+ stored_commit = state.get("last_sync_commit")
+ except Exception:
+ pass
+
+ is_stale, current_head, _commits_behind = check_repo_staleness(
+ abs_path,
+ stored_commit,
+ )
+ stored_config_fp = state.get("config_fingerprint")
+ config_state_missing = stored_config_fp is None and await _has_persisted_repo_index(abs_path)
+ if not is_stale and (
+ config_state_missing
+ or (stored_config_fp is not None and stored_config_fp != config_fingerprint(abs_path))
+ ):
+ is_stale = True
+
+ # A watched repo's changes are uncommitted by definition, so the
+ # commit-to-commit staleness check above says "up to date" for exactly
+ # the work the watcher woke up for.
+ if not is_stale and include_working_tree and has_working_tree_changes(abs_path):
+ is_stale = True
+
+ # Rows written under older git history rules: one full walk refreshes
+ # them, as the single-repo update does, even with HEAD unmoved.
+ if not is_stale and git_history_stale(state) and await _has_persisted_repo_index(abs_path):
+ is_stale = True
+ return is_stale, current_head
+
+
+def _defer_to_running_workspace_update(
+ workspace_owner: dict[str, Any], stale_repos: list[_StaleRepo]
+) -> list[RepoUpdateResult]:
+ """Queue every stale repo for the workspace update already in flight."""
+ age = _lock_age_seconds(workspace_owner)
+ _log.info(
+ "workspace_update: deferring — a workspace update is already "
+ "in flight (pid=%s elapsed=%ss); queuing %d stale repo(s) for it",
+ workspace_owner.get("pid"),
+ int(age) if age is not None else "?",
+ len(stale_repos),
+ )
+ # Record pending so the running workspace update rolls forward to the
+ # latest HEAD of each member. Mirrors the per-repo deferral in
+ # ``_defer_in_flight_repo``.
+ for _alias, path, new_head, _first_time in stale_repos:
+ if new_head:
+ with suppress(OSError):
+ (path / ".repowise").mkdir(parents=True, exist_ok=True)
+ (path / ".repowise" / ".update.pending").write_text(new_head, encoding="utf-8")
+ return [
+ RepoUpdateResult(
+ alias=alias,
+ updated=False,
+ skipped_reason="in_flight",
+ lock_age_seconds=age,
+ )
+ for alias, _path, _head, _first_time in stale_repos
+ ]
+
+
+async def _update_stale_repo(update_pass: _RepoUpdatePass, repo: _StaleRepo) -> RepoUpdateResult:
+ """Update one stale repo under the pass's concurrency limit."""
+ alias, path, new_head, first_time = repo
+ async with update_pass.semaphore:
+ if update_pass.on_repo_start:
+ update_pass.on_repo_start(alias)
+
+ # Ensure the .repowise/ dir exists before the pipeline runs so
+ # first-time indexing has a place to put wiki.db and state.json.
+ (path / ".repowise").mkdir(parents=True, exist_ok=True)
+
+ # Per-repo single-flight lock. The post-commit hook fires a
+ # new ``repowise update`` for every commit; without this guard,
+ # rapid-fire commits race on save_state, each pass starts from
+ # the same stale base, and the wiki never converges to HEAD.
+ # Check + acquire are one atomic exclusive create.
+ existing = _try_acquire_lock(path, new_head)
+ if existing is not None:
+ return _defer_in_flight_repo(alias, path, new_head, existing)
+
+ try:
+ update_started = time.monotonic()
+ result = await update_single_repo_index(
+ path,
+ commit_depth=update_pass.commit_depth,
+ exclude_patterns=update_pass.exclude_patterns,
+ include_working_tree=update_pass.include_working_tree,
+ )
+ if result.updated and result.phase_timings is None:
+ result.phase_timings = {"run": time.monotonic() - update_started}
+ finally:
+ _release_lock(path)
+ result.alias = alias
+ result.first_time_indexed = first_time and result.updated
+
+ if result.updated and new_head:
+ _write_repo_state(path, alias, new_head, first_time, result)
+ # Keep the DB freshness stamp in lockstep with last_sync_commit.
+ # The no-relevant-changes incremental path returns updated=True
+ # without re-running DB persistence, so the row would otherwise
+ # lag HEAD; a no-op when persistence already stamped it.
+ await reconcile_repo_head_commit(path, new_head)
+ # Drop any stale pending marker now that we've advanced to
+ # new_head (a bailed sibling update may have written one).
+ clear_stale_update_pending(path, new_head)
+
+ # Update workspace config entry
+ if result.updated:
+ entry = update_pass.ws_config.get_repo(alias)
+ if entry is not None:
+ entry.indexed_at = datetime.now(UTC).isoformat()
+ entry.last_commit_at_index = new_head
+
+ if update_pass.on_repo_done:
+ update_pass.on_repo_done(result)
+
+ return result
+
+
+def _defer_in_flight_repo(
+ alias: str, path: Path, new_head: str, existing: dict[str, Any]
+) -> RepoUpdateResult:
+ """Leave a pending marker for the update that already holds this repo's lock."""
+ age = _lock_age_seconds(existing)
+ target_short = (existing.get("target_commit") or "")[:8]
+ _log.info(
+ "workspace_update: skipping %s — update already in flight "
+ "(pid=%s target=%s elapsed=%ss)",
+ alias,
+ existing.get("pid"),
+ target_short,
+ int(age) if age is not None else "?",
+ )
+ # Record pending so the running update can roll forward.
+ with suppress(OSError):
+ (path / ".repowise" / ".update.pending").write_text(new_head, encoding="utf-8")
+ return RepoUpdateResult(
+ alias=alias,
+ updated=False,
+ skipped_reason="in_flight",
+ lock_age_seconds=age,
+ )
+
+
+def _write_repo_state(
+ path: Path, alias: str, new_head: str, first_time: bool, result: RepoUpdateResult
+) -> None:
+ """Advance ``state.json`` to *new_head* after a successful repo update."""
+ state_path = path / ".repowise" / "state.json"
+ state: dict[str, Any] = {}
+ if state_path.is_file():
+ with suppress(Exception):
+ state = _json.loads(state_path.read_text(encoding="utf-8"))
+
+ # Falsy, not absent: an explicit null survives a
+ # membership test and strands the pointer permanently.
+ if not state.get("last_docs_commit") and state.get("last_sync_commit"):
+ state["last_docs_commit"] = state["last_sync_commit"]
+
+ state["last_sync_commit"] = new_head
+ if result.kg_state:
+ state["knowledge_graph"] = result.kg_state
+ if result.working_tree_paths is not None:
+ state["working_tree_paths"] = result.working_tree_paths
+ if result.phase_timings is not None:
+ state["phase_timings"] = result.phase_timings
+ if result.git_history_refreshed:
+ state[GIT_HISTORY_VERSION_KEY] = GIT_HISTORY_VERSION
+ # Stamp the config fingerprint so the drift check in
+ # update_single_repo_index stays calibrated (and legacy repos
+ # without one stop re-triggering the full re-index).
+ with suppress(Exception):
+ from ...repo_config import (
+ config_dependency_fingerprints,
+ config_fingerprint,
+ load_repo_config,
+ )
+
+ state["config_fingerprint"] = config_fingerprint(path)
+ state["config_dependency_fingerprints"] = config_dependency_fingerprints(
+ path, config=load_repo_config(path)
+ )
+ # Mark first-time so downstream tooling (status, doctor) can
+ # distinguish a never-indexed repo from one that's been
+ # updated at least once.
+ if first_time and "docs_mode" not in state and "docs_enabled" not in state:
+ # This path indexes only; nothing renders pages here, not
+ # even from templates.
+ state.update(docs_mode_state_fields("none"))
+ state["docs_skip_reason"] = (
+ "first-time index via update; run "
+ "`repowise update --repo " + alias + " --docs` to generate docs"
+ )
+ from ...fsutils import atomic_write_text
+
+ state_path.parent.mkdir(parents=True, exist_ok=True)
+ atomic_write_text(state_path, _json.dumps(state, indent=2))
+
+
+def _collect_update_results(
+ update_results: list[RepoUpdateResult | BaseException],
+ results: list[RepoUpdateResult],
+) -> list[str]:
+ """Append each gathered result to *results*; return the updated aliases."""
+ changed_aliases: list[str] = []
+ for r in update_results:
+ if isinstance(r, Exception):
+ results.append(
+ RepoUpdateResult(
+ alias="unknown",
+ updated=False,
+ error=str(r),
+ )
+ )
+ else:
+ results.append(r)
+ if r.updated:
+ changed_aliases.append(r.alias)
+ return changed_aliases
+
+
+async def _finish_workspace_pass(
+ ws_config: WorkspaceConfig,
+ workspace_root: Path,
+ changed_aliases: list[str],
+ run_hooks: bool,
+) -> None:
+ """Save the updated workspace config, then run the cross-repo hooks."""
+ if changed_aliases:
+ ws_config.save(workspace_root)
+
+ # ``run_hooks`` lets the CLI defer these so they run once over the union
+ # of index-only and docs repos, rather than on this partial set.
+ if changed_aliases and run_hooks:
+ await run_cross_repo_hooks(ws_config, workspace_root, changed_aliases)
diff --git a/tests/unit/cli/test_sync_commit_restamp.py b/tests/unit/cli/test_sync_commit_restamp.py
index 8cac0c25a..6548ca212 100644
--- a/tests/unit/cli/test_sync_commit_restamp.py
+++ b/tests/unit/cli/test_sync_commit_restamp.py
@@ -98,7 +98,7 @@ def test_a_server_job_leaves_both_stamps_on_one_commit(repo) -> None:
def test_a_write_that_keeps_the_sync_commit_leaves_the_row_alone(repo, monkeypatch) -> None:
from repowise.cli.helpers import save_state
- from repowise.core.workspace import update
+ from repowise.core.workspace.update import state as update
path, old, _new = repo
stamped: list[str] = []
diff --git a/tests/unit/workspace/test_indexed_commit.py b/tests/unit/workspace/test_indexed_commit.py
index e535e53ed..7c21df217 100644
--- a/tests/unit/workspace/test_indexed_commit.py
+++ b/tests/unit/workspace/test_indexed_commit.py
@@ -98,7 +98,7 @@ def test_the_server_freshness_reads_the_same_commit(repo) -> None:
def test_only_a_definite_ancestry_answer_is_cached(monkeypatch) -> None:
from repowise.core import git_refs
- from repowise.core.workspace import update
+ from repowise.core.workspace.update import state as update
monkeypatch.setattr(update, "_ancestry_cache", {})
answers = iter([None, None, True]) # a timeout both ways, then git answers
diff --git a/tests/unit/workspace/test_update.py b/tests/unit/workspace/test_update.py
index e46bbd725..315308625 100644
--- a/tests/unit/workspace/test_update.py
+++ b/tests/unit/workspace/test_update.py
@@ -346,7 +346,7 @@ class TestUpdateWorkspace:
async def _run():
with patch(
- "repowise.core.workspace.update.update_single_repo_index",
+ "repowise.core.workspace.update.workspace_pass.update_single_repo_index",
new_callable=AsyncMock,
return_value=mock_result,
):
@@ -382,7 +382,7 @@ class TestUpdateWorkspace:
async def _run():
with patch(
- "repowise.core.workspace.update.update_single_repo_index",
+ "repowise.core.workspace.update.workspace_pass.update_single_repo_index",
new_callable=AsyncMock,
return_value=mock_result,
) as mocked:
@@ -413,7 +413,7 @@ class TestUpdateWorkspace:
async def _run() -> int:
with patch(
- "repowise.core.workspace.update.update_single_repo_index",
+ "repowise.core.workspace.update.workspace_pass.update_single_repo_index",
new_callable=AsyncMock,
return_value=mock_result,
) as mocked:
@@ -546,7 +546,7 @@ class TestUpdateWorkspace:
async def _run():
with patch(
- "repowise.core.workspace.update.update_single_repo_index",
+ "repowise.core.workspace.update.workspace_pass.update_single_repo_index",
new_callable=AsyncMock,
return_value=mock_result,
):
@@ -646,7 +646,7 @@ class TestWorkspaceSingleFlight:
async def _run():
with patch(
- "repowise.core.workspace.update.update_single_repo_index",
+ "repowise.core.workspace.update.workspace_pass.update_single_repo_index",
new_callable=AsyncMock,
return_value=mock_result,
):
@@ -688,7 +688,7 @@ class TestWorkspaceSingleFlight:
async def _run():
with patch(
- "repowise.core.workspace.update.update_single_repo_index",
+ "repowise.core.workspace.update.workspace_pass.update_single_repo_index",
new_callable=AsyncMock,
return_value=mock_result,
):
@@ -731,9 +731,9 @@ class TestCrossRepoHooks:
import asyncio
with (
- patch("repowise.core.workspace.update._run_phases", _phases),
+ patch("repowise.core.workspace.update.phases._run_phases", _phases),
patch("repowise.core.workspace.store.refresh_workspace_store", AsyncMock()),
- patch("repowise.core.workspace.update._refresh_contract_facts", _refresh),
+ patch("repowise.core.workspace.update.phases._refresh_contract_facts", _refresh),
):
asyncio.run(run_cross_repo_hooks(ws_config, tmp_path, ["api"]))
assert order == ["phases", "api"]