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.

perf(workspace): a no-change workspace update refreshes only the repos that moved (#4498)

Raghav Chamadiya251d00028e94
diff --git a/packages/cli/src/repowise/cli/commands/_index_outcome.py b/packages/cli/src/repowise/cli/commands/_index_outcome.py
index 9c79d55e0..9be85ca2a 100644
--- a/packages/cli/src/repowise/cli/commands/_index_outcome.py
+++ b/packages/cli/src/repowise/cli/commands/_index_outcome.py
@@ -1,7 +1,10 @@
"""Steps every outcome of ``repowise init`` and ``repowise update`` shares.
The telemetry outcome both commands attach to ``command_run``, and the stored
-read views both refresh once every store is final.
+read views both refresh once every store is final. A workspace update is the
+exception for the views: a member whose fingerprint has not moved since its
+last refresh skips them until it moves or the UTC day changes
+(``update_cmd/member_refresh.py``).
"""
from __future__ import annotations
@@ -53,35 +56,41 @@ def record_index_outcome(
return
-def refresh_read_snapshots(repo_path: Any) -> None:
+def refresh_read_snapshots(repo_path: Any) -> bool:
"""Store the Fix first queue and the next-actions view for the next reader.
A named step at every outcome of ``repowise update`` and at the end of
- ``repowise init``, once every store is final, so ``repowise next``, the
+ ``repowise init`` (a workspace update skips unchanged members, see the
+ module docstring), once every store is final, so ``repowise next``, the
overview and the dashboard read one row instead of rebuilding in each new
process. A view no write has invalidated since is left as it is, so the
"already up to date" path costs one primary-key read per view.
Best-effort: without a snapshot a reader builds live, as before. A
snapshot that is not written is named with its error, here rather than in
- the core log, which an update keeps at ERROR.
+ the core log, which an update keeps at ERROR. Returns whether the views
+ were written: ``False`` on a failure and when the store could not be opened
+ or holds no repository row, so a caller that skips unchanged repos retries.
"""
from repowise.cli.helpers import repo_index_session
from repowise.core.persistence.crud.analysis.actions import write_read_snapshots
- async def _run() -> list[tuple[str, Exception]]:
+ async def _run() -> list[tuple[str, Exception]] | None:
async with repo_index_session(Path(repo_path)) as opened:
- return [] if opened is None else await write_read_snapshots(*opened)
+ return None if opened is None else await write_read_snapshots(*opened)
try:
- try:
- failed = run_async(_run())
- except Exception as exc:
- failed = [("read snapshots", exc)]
+ failed = run_async(_run())
+ except Exception as exc:
+ failed = [("read snapshots", exc)]
+ if failed is None: # no store to write to; silent, as before
+ return False
+ try:
for name, exc in failed:
log.debug("read_snapshot_not_written", snapshot=name, error=repr(exc))
console.print(f"[yellow]Snapshot not written: {_short_error(name, exc)}[/yellow]")
except Exception: # reporting must never fail the update
log.debug("read_snapshot_report_failed", exc_info=True)
+ return not failed
def _short_error(name: str, exc: BaseException) -> str:
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/member_refresh.py b/packages/cli/src/repowise/cli/commands/update_cmd/member_refresh.py
new file mode 100644
index 000000000..22829fb80
--- /dev/null
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/member_refresh.py
@@ -0,0 +1,126 @@
+"""Which workspace members need their per-run refresh, by fingerprint.
+
+Every workspace update ends by restamping each up-to-date member's DB row and
+re-rendering each member's editor files (CLAUDE.md, AGENTS.md, ...). Done for
+every member, a no-change update cost O(all repos): about a second per repo.
+A member's refresh reads only its own store, config, state and editor files,
+the editor templates and the date, so a digest of those taken right after a
+refresh says whether the next refresh could write anything different. The
+next run refreshes only the members whose digest moved.
+"""
+
+from __future__ import annotations
+
+import functools
+import hashlib
+import json
+from datetime import UTC, datetime
+from pathlib import Path
+
+#: Recorded digests, one per member path, beside the other workspace data.
+_STAMPS_FILE = "member_refresh.json"
+
+#: Repo-relative files a refresh reads or writes. The store and its WAL catch
+#: every write to the index (a sync, a decision, a health run); the editor
+#: files catch a user deleting or editing one. A new integration that writes a
+#: project file adds its path here.
+_MEMBER_FILES = (
+ ".repowise/wiki.db",
+ ".repowise/wiki.db-wal",
+ ".repowise/state.json",
+ ".repowise/config.yaml",
+ ".gitignore",
+ ".git/info/exclude",
+ ".claude/CLAUDE.md",
+ "AGENTS.md",
+ ".vscode/mcp.json",
+ ".github/copilot-instructions.md",
+)
+
+#: The editor-file templates, hashed into the code stamp so a template edit
+#: re-renders every member even without a version change.
+_EDITOR_TEMPLATES = ("_editor_block.j2", "claude_md.j2", "agents_md.j2")
+
+
+def _code_stamp() -> str:
+ """The installed repowise version plus the editor generator's source."""
+ import repowise.core as core
+ from repowise.cli import __version__
+
+ generation = Path(core.__file__).parent / "generation"
+ sources = sorted((generation / "editor_files").glob("*.py"))
+ sources += [generation / "templates" / name for name in _EDITOR_TEMPLATES]
+ digest = hashlib.sha256(__version__.encode())
+ for source in sources:
+ try:
+ digest.update(source.read_bytes())
+ except OSError:
+ digest.update(b"-")
+ return digest.hexdigest()
+
+
+def member_fingerprint(repo_path: Path) -> str | None:
+ """A digest of everything a refresh of *repo_path* depends on, or ``None``.
+
+ ``None`` when the store is a configured database rather than the member's
+ own file: its writes leave no trace here, so that member always refreshes.
+ The UTC date is in the digest because the refresh advances the store's
+ "indexed at" stamp, which every surface shows at day resolution; an
+ unchanged member therefore still refreshes once a day.
+
+ Ceiling: uncommitted tree edits the generator reads live (a deleted hotspot
+ file, a manifest behind the opt-in ``commands`` section) show up at the next
+ commit, index write or day; reading the tree would cost the walk this skip
+ exists to avoid. So does an integration that swallows its own write error.
+ """
+ import os
+
+ from repowise.core.git_head import read_head_commit
+
+ # Same variables as persistence.database.DB_ENV_VARS, read without importing
+ # the ORM, which a skipped member never needs.
+ if os.environ.get("REPOWISE_DB_URL") or os.environ.get("REPOWISE_DATABASE_URL"):
+ return None
+ parts = [_code_stamp(), datetime.now(UTC).date().isoformat(), read_head_commit(repo_path) or ""]
+ for name in _MEMBER_FILES:
+ try:
+ st = (repo_path / name).stat()
+ # Size as well as mtime: NTFS can give two quick writes one mtime.
+ parts.append(f"{name}:{st.st_mtime_ns}:{st.st_size}")
+ except OSError:
+ parts.append(f"{name}:-")
+ return hashlib.sha256("\n".join(parts).encode()).hexdigest()
+
+
+def _stamps_path(ws_root: Path) -> Path:
+ from repowise.core.workspace.config import WORKSPACE_DATA_DIR
+
+ return ws_root / WORKSPACE_DATA_DIR / _STAMPS_FILE
+
+
+def load_member_stamps(ws_root: Path) -> dict[str, str]:
+ """The digests the last refresh recorded, keyed by member path."""
+ try:
+ data = json.loads(_stamps_path(ws_root).read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ return {}
+ return {str(k): str(v) for k, v in data.items()} if isinstance(data, dict) else {}
+
+
+def save_member_stamps(ws_root: Path, stamps: dict[str, str]) -> None:
+ """Record *stamps*. Best-effort: a lost file only costs one full refresh."""
+ from repowise.core.fsutils import atomic_write_text
+
+ path = _stamps_path(ws_root)
+ try:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ atomic_write_text(path, json.dumps(stamps, indent=1, sort_keys=True))
+ except OSError:
+ pass
+
+
+def is_unchanged(repo_path: Path, stamps: dict[str, str]) -> bool:
+ """Whether *repo_path*'s last refresh still holds, so this one can be skipped."""
+ fingerprint = member_fingerprint(repo_path)
+ return fingerprint is not None and stamps.get(str(repo_path)) == fingerprint
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
index aa324902f..d511efa18 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
@@ -28,8 +28,6 @@ from repowise.cli.helpers import (
run_async,
save_state,
)
-from repowise.core.analysis.health import HEALTH_ANALYZER_VERSION
-from repowise.core.analysis.security_scan import SECURITY_SCANNER_VERSION
from repowise.core.ingestion.git_indexer import GIT_HISTORY_VERSION, GIT_HISTORY_VERSION_KEY
from repowise.core.pipeline import PhaseTimings, timed
@@ -429,6 +427,8 @@ def _rescore_stale_findings(
# None over it when git gave us no timestamp.
if head_ts is not None:
last_full_rescore_at = head_ts
+ from repowise.core.analysis.health import HEALTH_ANALYZER_VERSION
+
health_analyzer_version = HEALTH_ANALYZER_VERSION
if force_full_rescore and not rescored:
raise RuntimeError(
@@ -441,6 +441,8 @@ def _rescore_stale_findings(
# persist above only rescanned the changed files.
security_scanner_version = state.get("security_scanner_version")
if security_scanner_changed(state):
+ from repowise.core.analysis.security_scan import SECURITY_SCANNER_VERSION
+
with timed(timings, "security_rescan"):
if run_full_security_rescan(repo_path, exclude_patterns or []):
security_scanner_version = SECURITY_SCANNER_VERSION
@@ -1220,6 +1222,8 @@ def _run_full_health_rescore(
console.print(f"[yellow]Health re-score failed: {exc}[/yellow]")
raise
+ from repowise.core.analysis.health import HEALTH_ANALYZER_VERSION
+
# Same full-replace re-score the periodic gate runs, so it restarts the same
# cadence. Left unstamped when git is unreadable: the gate cannot fire
# without a head_ts either.
@@ -1338,6 +1342,8 @@ def health_analyzer_changed(state: dict) -> bool:
stated defect. They pick the stamp up on their first re-score from any
other trigger.
"""
+ from repowise.core.analysis.health import HEALTH_ANALYZER_VERSION
+
stored = state.get("health_analyzer_version")
return stored is not None and stored != HEALTH_ANALYZER_VERSION
@@ -1351,6 +1357,8 @@ def security_scanner_changed(state: dict) -> bool:
unstamped forever, since only the rescan this gates writes the stamp.
``init`` stamps every fresh index, so a new install never reads as stale.
"""
+ from repowise.core.analysis.security_scan import SECURITY_SCANNER_VERSION
+
return state.get("security_scanner_version") != SECURITY_SCANNER_VERSION
@@ -1364,6 +1372,8 @@ def rescan_security_if_changed(repo_path: Any, state: dict, exclude_patterns: li
return False
if not run_full_security_rescan(repo_path, exclude_patterns):
return False
+ from repowise.core.analysis.security_scan import SECURITY_SCANNER_VERSION
+
state["security_scanner_version"] = SECURITY_SCANNER_VERSION
return True
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/workspace.py b/packages/cli/src/repowise/cli/commands/update_cmd/workspace.py
index cb157ebb6..3e75211b2 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/workspace.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/workspace.py
@@ -108,7 +108,7 @@ def _workspace_update(
verbose=verbose,
)
if not dry_run and scan.up_to_date_repos:
- _reconcile_up_to_date(scan.up_to_date_repos)
+ _reconcile_up_to_date(ws_root, scan.up_to_date_repos)
if scan.stale_count == 0:
console.print("[green]All repos are up to date.[/green]")
@@ -296,17 +296,26 @@ def _wants_docs_update(
return resolve_docs_mode(repo_state) == "deterministic"
-def _reconcile_up_to_date(up_to_date_repos: list[tuple[Path, str]]) -> None:
+def _reconcile_up_to_date(ws_root: Path, up_to_date_repos: list[tuple[Path, str]]) -> None:
"""Reconcile the DB freshness stamp of up-to-date repos.
Staleness is measured against the workspace config, but the server and the
MCP freshness check read each repo DB's head_commit, which the all-up-to-date
- path would otherwise never touch. Only writes on drift.
+ path would otherwise never touch. A repo nothing has moved since the last
+ refresh (see :mod:`.member_refresh`) already carries today's stamp, so only
+ the others are opened.
"""
from repowise.core.workspace import reconcile_repo_head_commit
+ from .member_refresh import is_unchanged, load_member_stamps
+
+ stamps = load_member_stamps(ws_root)
+ moved = [(path, head) for path, head in up_to_date_repos if not is_unchanged(path, stamps)]
+ if not moved:
+ return
+
async def _reconcile() -> None:
- for repo_path, head in up_to_date_repos:
+ for repo_path, head in moved:
await reconcile_repo_head_commit(repo_path, head)
run_async(_reconcile())
@@ -726,26 +735,50 @@ def _refresh_workspace_editor_project_files(
whole refresh: doing so froze the CLAUDE.md stamp for every workspace user
who never passed ``--agents-md`` (the default), making the index look stale
long after it was current. Mirrors the single-repo update path.
+
+ A repo whose fingerprint has not moved since its last refresh is skipped
+ (see :mod:`.member_refresh`), so a no-change update costs O(changed repos).
+ An explicit ``agents_md`` refreshes every repo, as it may change the files.
"""
from repowise.cli.commands._index_outcome import refresh_read_snapshots
from repowise.cli.editor_integrations.defaults import get_default_project_file_overrides
from repowise.cli.editor_setup import EditorSetupOptions, refresh_editor_project_files
+ from .member_refresh import (
+ is_unchanged,
+ load_member_stamps,
+ member_fingerprint,
+ save_member_stamps,
+ )
+
options: EditorSetupOptions | None = None
if agents_md is not None:
options = EditorSetupOptions(
project_file_overrides=get_default_project_file_overrides(agents_md=agents_md),
)
+ stamps = load_member_stamps(ws_root)
+ recorded = dict(stamps)
for entry in ws_config.repos:
if repo_filter and entry.alias != repo_filter:
continue
repo_path = (ws_root / entry.path).resolve()
if not (repo_path / ".repowise").is_dir():
continue
- refresh_read_snapshots(repo_path)
+ if options is None and is_unchanged(repo_path, stamps):
+ continue
+ # A failed step drops the stamp, so the next update retries this repo.
+ stamps.pop(str(repo_path), None)
+ snapshots_written = refresh_read_snapshots(repo_path)
try:
refresh_editor_project_files(console, repo_path, options=options)
except Exception as exc:
console.print(
f" [yellow]{entry.alias}: editor project-file refresh skipped: {exc}[/yellow]"
)
+ continue
+ # Taken after the writes, so it describes the state they left.
+ fingerprint = member_fingerprint(repo_path) if snapshots_written else None
+ if fingerprint is not None:
+ stamps[str(repo_path)] = fingerprint
+ if stamps != recorded:
+ save_member_stamps(ws_root, stamps)
diff --git a/packages/core/src/repowise/core/persistence/database.py b/packages/core/src/repowise/core/persistence/database.py
index c8cb5701c..d3833a236 100644
--- a/packages/core/src/repowise/core/persistence/database.py
+++ b/packages/core/src/repowise/core/persistence/database.py
@@ -11,6 +11,8 @@ Call init_db() once at startup to create all tables and the FTS index.
from __future__ import annotations
+import functools
+import hashlib
import os
import sqlite3
import warnings
@@ -681,6 +683,49 @@ def _reconcile_schema(connection: object) -> None:
raise failures[0][1]
+#: Bump when ``_reconcile_schema`` learns a repair the model shape alone does
+#: not reveal, so stores stamped by the old code reconcile again.
+_RECONCILE_LOGIC_VERSION = 1
+
+
+def _model_signature() -> str:
+ """What ``create_all`` and ``_reconcile_schema`` act on, as text.
+
+ Tables, column names, types, lengths and nullability, and index names.
+ """
+ parts = [f"logic={_RECONCILE_LOGIC_VERSION}"]
+ for name in sorted(Base.metadata.tables):
+ table = Base.metadata.tables[name]
+ columns = sorted(
+ (c.name, type(c.type).__name__, str(getattr(c.type, "length", None)), str(c.nullable))
+ for c in table.columns
+ )
+ indexes = sorted(str(i.name) for i in table.indexes)
+ parts.append(f"{name}|{columns}|{indexes}")
+ return "\n".join(parts)
+
+
+def schema_stamp(schema_cookie: int) -> int:
+ """The ``PRAGMA user_version`` a store reconciled by these models carries.
+
+ Folds in SQLite's ``schema_version`` cookie, which SQLite itself bumps on
+ every DDL statement, so any schema change made after the stamp (an older
+ repowise, a ``VACUUM``, a hand edit) reads as unstamped and reconciles.
+ A positive 31-bit int: 0 is what every unstamped store reads.
+ """
+ signature = f"{_model_signature()}\ncookie={schema_cookie}"
+ digest = hashlib.sha256(signature.encode()).digest()
+ return int.from_bytes(digest[:4], "big") % (2**31 - 1) + 1
+
+
+async def _sqlite_stamp_state(conn: Any) -> tuple[int, int]:
+ """``(user_version, schema_version)`` of the store behind *conn*."""
+ user_version = (await conn.execute(text("PRAGMA user_version"))).scalar()
+ cookie = (await conn.execute(text("PRAGMA schema_version"))).scalar()
+ return int(user_version or 0), int(cookie or 0)
+
+
async def init_db(engine: AsyncEngine) -> None:
"""Create all SQLAlchemy tables and the FTS index for the given engine.
@@ -689,10 +734,23 @@ async def init_db(engine: AsyncEngine) -> None:
missing columns/indexes back-filled in place rather than hitting a
cryptic ``no such column`` error from the ORM.
+ On SQLite a complete pass records :func:`schema_stamp` in
+ ``PRAGMA user_version``, and a store still carrying it skips the table
+ walk: two header reads in place of reflecting every table, which cost
+ about 150ms per open of an unchanged store. Another repowise's models, or
+ any schema change since the stamp, reads as unstamped and reconciles as
+ before. Other backends reconcile on every call.
+
Safe to call on an already-initialised database (idempotent).
"""
+ sqlite = engine.dialect.name == "sqlite"
async with engine.begin() as conn:
+ if sqlite:
+ stamped, cookie = await _sqlite_stamp_state(conn)
+ if stamped == schema_stamp(cookie):
+ return
await conn.run_sync(Base.metadata.create_all)
+ # Raises when the walk is incomplete, so a partial reconcile is never stamped.
await conn.run_sync(_reconcile_schema)
# SQLite-only: create FTS5 virtual table for full-text search.
@@ -706,6 +764,27 @@ async def init_db(engine: AsyncEngine) -> None:
from repowise.core.persistence.search import PAGE_FTS_DDL
await conn.execute(text(PAGE_FTS_DDL))
+ # Last, so the cookie read covers every statement above.
+ _, cookie = await _sqlite_stamp_state(conn)
+ await _write_stamp(conn, schema_stamp(cookie))
+
+
+async def _write_stamp(conn: Any, stamp: int) -> None:
+ """Record *stamp*, giving up at once on a read-only or locked store.
+
+ A store already on the current schema was opened without any write before
+ the stamp existed, so the stamp must not make such an open wait on another
+ writer's lock or fail on a read-only file. Unstamped, the next open simply
+ reconciles again.
+ """
+ timeout = (await conn.execute(text("PRAGMA busy_timeout"))).scalar()
+ await conn.execute(text("PRAGMA busy_timeout = 0"))
+ try:
+ await conn.execute(text(f"PRAGMA user_version = {stamp}"))
+ except DBAPIError as exc:
+ log.debug("schema_stamp_not_written", error=str(exc))
+ finally:
+ await conn.execute(text(f"PRAGMA busy_timeout = {int(timeout or 0)}"))
# A table whose row count moved past this factor of the count ANALYZE recorded
diff --git a/packages/core/src/repowise/core/pipeline/__init__.py b/packages/core/src/repowise/core/pipeline/__init__.py
index 03cc8616d..b58ab6396 100644
--- a/packages/core/src/repowise/core/pipeline/__init__.py
+++ b/packages/core/src/repowise/core/pipeline/__init__.py
@@ -8,24 +8,46 @@ Usage::
result = asyncio.run(run_pipeline(Path("/path/to/repo"), generate_docs=False))
print(f"Indexed {result.file_count} files, {result.symbol_count} symbols")
+
+The phase timer is imported eagerly; everything else loads on first use, so a
+command that only times its phases (every ``repowise update``, including the
+no-change workspace path) does not pay for the whole generation stack.
"""
-from .orchestrator import PipelineResult, run_generation, run_pipeline
-from .persist import (
- _sweep_stale_generated_pages as sweep_stale_generated_pages,
-)
-from .persist import (
- persist_analysis,
- persist_generation,
- persist_git,
- persist_ingestion,
- persist_pipeline_result,
- tombstone_absent_file_pages,
-)
+from __future__ import annotations
+
+import importlib
+from typing import Any
+
from .phase_timing import PhaseTimingRecorder, PhaseTimings, timed
-from .progress import LoggingProgressCallback, ProgressCallback
-from .reparse import reparse_repo
-from .upgrade import rehydrate_graph_builder
+
+#: Lazily exported name -> (submodule, attribute in it).
+_LAZY = {
+ "PipelineResult": ("orchestrator", "PipelineResult"),
+ "run_generation": ("orchestrator", "run_generation"),
+ "run_pipeline": ("orchestrator", "run_pipeline"),
+ "sweep_stale_generated_pages": ("persist", "_sweep_stale_generated_pages"),
+ "persist_analysis": ("persist", "persist_analysis"),
+ "persist_generation": ("persist", "persist_generation"),
+ "persist_git": ("persist", "persist_git"),
+ "persist_ingestion": ("persist", "persist_ingestion"),
+ "persist_pipeline_result": ("persist", "persist_pipeline_result"),
+ "tombstone_absent_file_pages": ("persist", "tombstone_absent_file_pages"),
+ "LoggingProgressCallback": ("progress", "LoggingProgressCallback"),
+ "ProgressCallback": ("progress", "ProgressCallback"),
+ "reparse_repo": ("reparse", "reparse_repo"),
+ "rehydrate_graph_builder": ("upgrade", "rehydrate_graph_builder"),
+}
+
+
+def __getattr__(name: str) -> Any:
+ target = _LAZY.get(name)
+ if target is None:
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
+ value = getattr(importlib.import_module(f".{target[0]}", __name__), target[1])
+ globals()[name] = value
+ return value
+
__all__ = [
"LoggingProgressCallback",
diff --git a/tests/unit/cli/test_workspace_member_refresh.py b/tests/unit/cli/test_workspace_member_refresh.py
new file mode 100644
index 000000000..e2f538ade
--- /dev/null
+++ b/tests/unit/cli/test_workspace_member_refresh.py
@@ -0,0 +1,180 @@
+"""A no-change workspace update refreshes only the members that moved."""
+
+from __future__ import annotations
+
+import os
+import types
+from pathlib import Path
+
+import pytest
+
+from repowise.cli.commands.update_cmd import member_refresh
+from repowise.cli.commands.update_cmd import workspace as ws_mod
+
+
+def _ws(tmp_path: Path, *aliases: str) -> types.SimpleNamespace:
+ for alias in aliases:
+ dot = tmp_path / alias / ".repowise"
+ dot.mkdir(parents=True)
+ (dot / "wiki.db").write_bytes(b"db")
+ (dot / "state.json").write_text("{}", encoding="utf-8")
+ return types.SimpleNamespace(
+ repos=[types.SimpleNamespace(alias=a, path=a) for a in aliases]
+ )
+
+
+def refreshed(monkeypatch: pytest.MonkeyPatch) -> list[str]:
+ calls: list[str] = []
+ monkeypatch.delenv("REPOWISE_DB_URL", raising=False)
+ monkeypatch.delenv("REPOWISE_DATABASE_URL", raising=False)
+ monkeypatch.setattr(
+ "repowise.cli.editor_setup.refresh_editor_project_files",
+ lambda console, repo_path, *, options=None: calls.append(Path(repo_path).name),
+ )
+ monkeypatch.setattr(
+ "repowise.cli.commands._index_outcome.refresh_read_snapshots", lambda _path: True
+ )
+ return calls
+
+
+def _refresh(tmp_path: Path, ws_config: types.SimpleNamespace, agents_md: bool | None = None):
+ ws_mod._refresh_workspace_editor_project_files(
+ ws_root=tmp_path, ws_config=ws_config, repo_filter=None, agents_md=agents_md
+ )
+
+
+def _touch(path: Path) -> None:
+ path.write_bytes(path.read_bytes() + b"+")
+
+
+def test_second_refresh_skips_every_unchanged_member(tmp_path, refreshed):
+ ws_config = _ws(tmp_path, "api", "web")
+ _refresh(tmp_path, ws_config)
+ assert sorted(refreshed) == ["api", "web"]
+
+ refreshed.clear()
+ _refresh(tmp_path, ws_config)
+ assert refreshed == []
+
+
+def test_a_write_to_one_store_refreshes_only_that_member(tmp_path, refreshed):
+ ws_config = _ws(tmp_path, "api", "web")
+ _refresh(tmp_path, ws_config)
+ refreshed.clear()
+
+ _touch(tmp_path / "web" / ".repowise" / "wiki.db")
+ _refresh(tmp_path, ws_config)
+ assert refreshed == ["web"]
+
+
+def test_a_deleted_editor_file_is_written_again(tmp_path, refreshed):
+ ws_config = _ws(tmp_path, "api")
+ claude_md = tmp_path / "api" / ".claude" / "CLAUDE.md"
+ claude_md.parent.mkdir()
+ claude_md.write_text("x", encoding="utf-8")
+ _refresh(tmp_path, ws_config)
+ refreshed.clear()
+
+ claude_md.unlink()
+ _refresh(tmp_path, ws_config)
+ assert refreshed == ["api"]
+
+
+def test_a_template_or_version_change_refreshes_every_member(tmp_path, refreshed, monkeypatch):
+ ws_config = _ws(tmp_path, "api", "web")
+ _refresh(tmp_path, ws_config)
+ refreshed.clear()
+
+ monkeypatch.setattr(member_refresh, "_code_stamp", lambda: "another release")
+ _refresh(tmp_path, ws_config)
+ assert sorted(refreshed) == ["api", "web"]
+
+
+def test_a_new_day_refreshes_so_the_indexed_at_stamp_advances(tmp_path, refreshed, monkeypatch):
+ ws_config = _ws(tmp_path, "api")
+ _refresh(tmp_path, ws_config)
+ refreshed.clear()
+
+ real = member_refresh.datetime
+
+ class _Tomorrow:
+ @staticmethod
+ def now(tz):
+ from datetime import timedelta
+
+ return real.now(tz) + timedelta(days=1)
+
+ monkeypatch.setattr(member_refresh, "datetime", _Tomorrow)
+ _refresh(tmp_path, ws_config)
+ assert refreshed == ["api"]
+
+
+def test_a_failed_refresh_is_retried(tmp_path, refreshed, monkeypatch):
+ ws_config = _ws(tmp_path, "api")
+ monkeypatch.setattr(
+ "repowise.cli.commands._index_outcome.refresh_read_snapshots", lambda _path: False
+ )
+ _refresh(tmp_path, ws_config)
+ _refresh(tmp_path, ws_config)
+ assert refreshed == ["api", "api"]
+
+
+def test_an_explicit_agents_md_refreshes_every_member(tmp_path, refreshed):
+ ws_config = _ws(tmp_path, "api")
+ _refresh(tmp_path, ws_config)
+ refreshed.clear()
+
+ _refresh(tmp_path, ws_config, agents_md=True)
+ assert refreshed == ["api"]
+
+
+def test_a_configured_database_always_refreshes(tmp_path, refreshed, monkeypatch):
+ ws_config = _ws(tmp_path, "api")
+ monkeypatch.setenv("REPOWISE_DB_URL", "sqlite:///" + os.fspath(tmp_path / "shared.db"))
+ _refresh(tmp_path, ws_config)
+ _refresh(tmp_path, ws_config)
+ assert refreshed == ["api", "api"]
+
+
+def test_up_to_date_restamp_opens_only_moved_members(tmp_path, refreshed, monkeypatch):
+ ws_config = _ws(tmp_path, "api", "web")
+ _refresh(tmp_path, ws_config)
+ _touch(tmp_path / "web" / ".repowise" / "state.json")
+
+ stamped: list[str] = []
+
+ async def _reconcile(repo_path: Path, head: str | None) -> None:
+ stamped.append(repo_path.name)
+
+ monkeypatch.setattr("repowise.core.workspace.reconcile_repo_head_commit", _reconcile)
+ ws_mod._reconcile_up_to_date(
+ tmp_path,
+ [((tmp_path / a).resolve(), "abc") for a in ("api", "web")],
+ )
+ assert stamped == ["web"]
+
+
+def test_a_member_whose_store_cannot_be_opened_is_not_stamped(tmp_path, monkeypatch):
+ """No store or no repository row writes no views, so the member is retried."""
+ from contextlib import asynccontextmanager
+
+ monkeypatch.delenv("REPOWISE_DB_URL", raising=False)
+ monkeypatch.delenv("REPOWISE_DATABASE_URL", raising=False)
+ calls: list[str] = []
+ monkeypatch.setattr(
+ "repowise.cli.editor_setup.refresh_editor_project_files",
+ lambda console, repo_path, *, options=None: calls.append(Path(repo_path).name),
+ )
+
+ @asynccontextmanager
+ async def _unopenable(_root):
+ yield None
+
+ monkeypatch.setattr("repowise.cli.helpers.repo_index_session", _unopenable)
+ ws_config = _ws(tmp_path, "api")
+ _refresh(tmp_path, ws_config)
+ assert member_refresh.load_member_stamps(tmp_path) == {}
+
+ _refresh(tmp_path, ws_config)
+ assert calls == ["api", "api"]
diff --git a/tests/unit/persistence/test_schema_reconciliation.py b/tests/unit/persistence/test_schema_reconciliation.py
index 8b7f22c91..488f38c12 100644
--- a/tests/unit/persistence/test_schema_reconciliation.py
+++ b/tests/unit/persistence/test_schema_reconciliation.py
@@ -602,3 +602,79 @@ def test_postgres_reconcile_ignores_pgvector_type_warning(monkeypatch: pytest.Mo
with warnings.catch_warnings():
warnings.simplefilter("error")
db_module._reconcile_schema(connection)
+
+
+async def _init(db_path: Path) -> None:
+ engine = create_engine(f"sqlite+aiosqlite:///{db_path}")
+ try:
+ await init_db(engine)
+ finally:
+ await engine.dispose()
+
+
+def _stamp_state(db_path: Path) -> tuple[int, int]:
+ (user_version,) = _fetchall(db_path, "PRAGMA user_version")[0]
+ (cookie,) = _fetchall(db_path, "PRAGMA schema_version")[0]
+ return user_version, cookie
+
+
+async def test_stamped_store_skips_the_reconcile(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A store carrying the current stamp opens without reflecting a table."""
+ from repowise.core.persistence import database as db_module
+
+ db_path = tmp_path / "wiki.db"
+ await _init(db_path)
+ user_version, cookie = _stamp_state(db_path)
+ assert user_version == db_module.schema_stamp(cookie)
+
+ def _walked(_connection: Any) -> None:
+ raise AssertionError("reconciled a store already on the current schema")
+
+ monkeypatch.setattr(db_module, "_reconcile_schema", _walked)
+ await _init(db_path)
+
+
+async def test_store_stamped_by_other_models_is_reconciled(tmp_path: Path) -> None:
+ """A stamp another release wrote (an upgrade, a downgrade) reconciles and restamps."""
+ from repowise.core.persistence import database as db_module
+
+ db_path = tmp_path / "wiki.db"
+ await _init(db_path)
+ try:
+ _execute(db_path, 'ALTER TABLE "decision_records" DROP COLUMN "verification"')
+ except sqlite3.OperationalError as exc:
+ pytest.skip(f"SQLite build doesn't support DROP COLUMN: {exc}")
+ # Stamped after the drop, as a release whose models lack the column would.
+ _, cookie = _stamp_state(db_path)
+ _execute(db_path, f"PRAGMA user_version = {db_module.schema_stamp(cookie) % 1000 + 1}")
+
+ await _init(db_path)
+
+ assert "verification" in _table_columns(db_path, "decision_records")
+ user_version, cookie = _stamp_state(db_path)
+ assert user_version == db_module.schema_stamp(cookie)
+
+
+async def test_a_locked_store_opens_without_waiting_for_its_stamp(tmp_path: Path) -> None:
+ """Stamping is the one write a current store's open adds; it must not block."""
+ import time
+
+ db_path = tmp_path / "wiki.db"
+ await _init(db_path)
+ _execute(db_path, "PRAGMA user_version = 0") # current schema, never stamped
+
+ writer = sqlite3.connect(db_path, isolation_level=None)
+ try:
+ writer.execute("BEGIN IMMEDIATE") # another update holding the write lock
+ started = time.monotonic()
+ await _init(db_path)
+ assert time.monotonic() - started < 10
+ finally:
+ writer.execute("ROLLBACK")
+ writer.close()
+ assert _stamp_state(db_path)[0] == 0
diff --git a/tests/unit/pipeline/test_lazy_exports.py b/tests/unit/pipeline/test_lazy_exports.py
new file mode 100644
index 000000000..e65bf5e1d
--- /dev/null
+++ b/tests/unit/pipeline/test_lazy_exports.py
@@ -0,0 +1,24 @@
+"""The pipeline package resolves every public name without loading it eagerly."""
+
+from __future__ import annotations
+
+import subprocess
+import sys
+
+import repowise.core.pipeline as pipeline
+
+
+def test_every_exported_name_resolves() -> None:
+ for name in pipeline.__all__:
+ assert getattr(pipeline, name) is not None, name
+
+
+def test_the_phase_timer_does_not_load_the_generation_stack() -> None:
+ probe = (
+ "import sys; from repowise.core.pipeline import PhaseTimings, timed; "
+ "print('repowise.core.pipeline.orchestrator' in sys.modules)"
+ )
+ out = subprocess.run(
+ [sys.executable, "-c", probe], capture_output=True, text=True, check=True
+ ).stdout.strip()
+ assert out == "False"