Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(freshness): every surface reports the index's last sync time (#4360)
Raghav Chamadiya36607ce1fdbe
diff --git a/docs/reference/MCP_RESPONSE_FIELDS.md b/docs/reference/MCP_RESPONSE_FIELDS.mdindex 0f7d29fc4..4f3459d02 100644--- a/docs/reference/MCP_RESPONSE_FIELDS.md+++ b/docs/reference/MCP_RESPONSE_FIELDS.md@@ -26,7 +26,7 @@ Routine responses carry a lean envelope. `get_overview` (called once per session| `timing_ms` | `get_overview`, or debug meta | Tool wall time || `hint` | Sometimes | A short follow-up suggestion || `cached` | Only when `true` | The response came from cache |-| `index_age_days` | A repository is resolved | Days since the last `repowise update` |+| `index_age_days` | A repository is resolved | Whole days since the index last synced (`repowise init` or `repowise update`), the same time `repowise status`, the dashboard and CLAUDE.md report || `indexed_commit` | A repository is resolved | Short SHA the index was built from || `live_head` | `.git/HEAD` is readable | Short SHA of the checkout; equals `indexed_commit` when current || `index_behind` | The comparison ran | `true` if HEAD moved, `false` if not; absent if it could not run |diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py b/packages/cli/src/repowise/cli/commands/init_cmd/workspace.pyindex bdb71b2a5..a0720d399 100644--- a/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py+++ b/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py@@ -13,7 +13,6 @@ import osimport sysimport timefrom dataclasses import dataclass, field, replace-from datetime import UTC, datetimefrom pathlib import Pathfrom typing import Any@@ -68,6 +67,7 @@ from repowise.core.decision_lanes import record_decision_lanesfrom repowise.core.docs_mode import docs_mode_state_fieldsfrom repowise.core.generation.styles import DEFAULT_STYLEfrom repowise.core.index_scope import MODEL_COMMAND+from repowise.core.workspace.update import stamp_workspace_entryfrom ._exit import COST_UNCONFIRMED_BUILT, exit_on_gapsfrom ._ingest import structural_generation_config@@ -396,8 +396,7 @@ def _ingest_and_generate_repo(repo: Any, idx: int, total: int, ctx: _WorkspaceCtentry = ctx.ws_config.get_repo(repo.alias)if entry is not None:- entry.indexed_at = datetime.now(UTC).isoformat()- entry.last_commit_at_index = head+ stamp_workspace_entry(entry, repo.path, head)write_editor_project_files(console,diff --git a/packages/cli/src/repowise/cli/commands/status_cmd.py b/packages/cli/src/repowise/cli/commands/status_cmd.pyindex 7f805e4b4..63b6a2c5a 100644--- a/packages/cli/src/repowise/cli/commands/status_cmd.py+++ b/packages/cli/src/repowise/cli/commands/status_cmd.py@@ -495,10 +495,13 @@ def _workspace_rows(target: CommandTarget) -> list[dict]:each consumer branch on ``indexed`` before it may read a field."""from repowise.core.workspace import check_repo_staleness+ from repowise.core.workspace.update import sync_workspace_state_from_diskws_root = target.ws_rootws_config = target.ws_configassert ws_root is not None and ws_config is not None+ # A member updated on its own leaves the config behind its store.+ sync_workspace_state_from_disk(ws_root, ws_config, save_if_changed=False)rows: list[dict] = []for entry in ws_config.repos:diff --git a/packages/cli/src/repowise/cli/commands/workspace_cmd/_index.py b/packages/cli/src/repowise/cli/commands/workspace_cmd/_index.pyindex bdebe6304..246d4c46c 100644--- a/packages/cli/src/repowise/cli/commands/workspace_cmd/_index.py+++ b/packages/cli/src/repowise/cli/commands/workspace_cmd/_index.py@@ -2,7 +2,6 @@from __future__ import annotations-from datetime import UTCfrom pathlib import Pathfrom typing import TYPE_CHECKING, Any@@ -145,7 +144,7 @@ def _run_index_for_repo(_document_added_repo(repo_path, ctx, index, docs)_save_added_repo_config(repo_path, ctx, primary_cfg)head, state = _save_added_repo_state(repo_path, ctx, index, docs)- _record_in_workspace(ws_root, ws_config, alias, head)+ _record_in_workspace(ws_root, ws_config, alias, head, repo_path)_note_missing_docs(alias, state, docs.skip_reason)@@ -361,16 +360,14 @@ def _record_in_workspace(ws_config: WorkspaceConfig, # type: ignore[name-defined]alias: str,head: str | None,+ repo_path: Path,) -> None:"""Stamp the workspace entry and refresh cross-repo hooks (best effort)."""- from datetime import datetime-- from repowise.core.workspace.update import run_cross_repo_hooks+ from repowise.core.workspace.update import run_cross_repo_hooks, stamp_workspace_entryentry = ws_config.get_repo(alias)if entry is not None:- entry.indexed_at = datetime.now(UTC).isoformat()- entry.last_commit_at_index = head+ stamp_workspace_entry(entry, repo_path, head)ws_config.save(ws_root)# Cross-repo hooks — best effort; never fail the add command.diff --git a/packages/cli/src/repowise/cli/commands/workspace_cmd/group.py b/packages/cli/src/repowise/cli/commands/workspace_cmd/group.pyindex e8ca439bf..244896abd 100644--- a/packages/cli/src/repowise/cli/commands/workspace_cmd/group.py+++ b/packages/cli/src/repowise/cli/commands/workspace_cmd/group.py@@ -35,9 +35,12 @@ def workspace_list(path: str | None) -> None:"""Show all repos in the workspace with their status."""from repowise.cli.helpers import get_repowise_dirfrom repowise.core.workspace import check_repo_staleness+ from repowise.core.workspace.update import sync_workspace_state_from_diskstart = resolve_repo_path(path)ws_root, ws_config = _require_workspace(start)+ # A member updated on its own leaves the config behind its store.+ sync_workspace_state_from_disk(ws_root, ws_config, save_if_changed=False)table = Table(title=f"Workspace: {ws_root.name}")table.add_column("Repo", style="cyan", min_width=16)diff --git a/packages/core/src/repowise/core/generation/editor_files/fetcher.py b/packages/core/src/repowise/core/generation/editor_files/fetcher.pyindex 310ad8683..f2cbe8d23 100644--- a/packages/core/src/repowise/core/generation/editor_files/fetcher.py+++ b/packages/core/src/repowise/core/generation/editor_files/fetcher.py@@ -116,10 +116,12 @@ class EditorFileDataFetcher:# below it. Fall back to the shell-out only when the column is empty# (pre-backfill indexes).stored_commit = ((repo.head_commit or "")[:7]) if repo else ""+ # The date likewise is the index's sync time, never the render time.+ synced_at = crud.index_synced_at(repo)return EditorFileData(repo_name=repo_name,- indexed_at=datetime.now(UTC).strftime("%Y-%m-%d"),+ indexed_at=synced_at.strftime("%Y-%m-%d") if synced_at else "unknown",indexed_commit=stored_commit or _get_head_short_sha(self._repo_path),architecture_summary=(await self._get_architecture_summary() if "architecture" in s else ""diff --git a/packages/core/src/repowise/core/persistence/crud/repository.py b/packages/core/src/repowise/core/persistence/crud/repository.pyindex ea31d22ac..5921cceb7 100644--- a/packages/core/src/repowise/core/persistence/crud/repository.py+++ b/packages/core/src/repowise/core/persistence/crud/repository.py@@ -59,7 +59,8 @@ async def upsert_repository(``stamp_head=True`` (read HEAD). Callers that only need the row, such asdecisions, scans and server registration, leave it alone: moving it theremade the database claim an index at HEAD while ``state.json`` still named- the last real sync.+ the last real sync. ``updated_at`` (see :func:`index_synced_at`) moves with+ the commit stamp for the same reason."""result = await session.execute(select(Repository).where(Repository.local_path == local_path))repo = result.scalar_one_or_none()@@ -88,12 +89,30 @@ async def upsert_repository(# out a previously recorded one (e.g. a transient non-checkout path).if resolved_head:repo.head_commit = resolved_head- repo.updated_at = _now_utc()+ if stamping:+ repo.updated_at = _now_utc()await session.flush()return repo+def index_synced_at(repo: Repository | None) -> datetime | None:+ """When *repo*'s index last synced to the checkout, timezone-aware, or ``None``.++ The one "indexed at" every surface reports. Only a sync moves it: an index+ run's stamping :func:`upsert_repository` and git-totals write, and the+ "up to date" re-stamp in ``reconcile_repo_head_commit``.+ """+ return as_utc(getattr(repo, "updated_at", None))+++def as_utc(stamp: datetime | None) -> datetime | None:+ """*stamp* as timezone-aware UTC; SQLite hands these columns back naive."""+ if not isinstance(stamp, datetime):+ return None+ return stamp if stamp.tzinfo else stamp.replace(tzinfo=UTC)++ANALYSIS_RAN_KEY = "analysis_ran_at"@@ -209,6 +228,8 @@ async def update_repo_git_totals(for attr, value in updates.items():if value is not None:setattr(repo, attr, value)+ # Index persist is the only caller, so this is a sync; it also moves the+ # stamp ``index_stamp`` caches whole-history answers on.repo.updated_at = _now_utc()await session.flush()diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.pyindex 0aca27748..2a1b3f34b 100644--- a/packages/core/src/repowise/core/persistence/models.py+++ b/packages/core/src/repowise/core/persistence/models.py@@ -149,8 +149,12 @@ class Repository(Base):created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=_now_utc)+ # When the index last synced to the checkout, read through+ # ``crud.index_synced_at``. No ``onupdate``: only the sync stampers move it,+ # so a settings edit or a command that merely opens the row cannot make a+ # days-old index read as fresh.updated_at: Mapped[datetime] = mapped_column(- DateTime(timezone=True), nullable=False, default=_now_utc, onupdate=_now_utc+ DateTime(timezone=True), nullable=False, default=_now_utc)diff --git a/packages/core/src/repowise/core/workspace/update/__init__.py b/packages/core/src/repowise/core/workspace/update/__init__.pyindex fc469a894..05f01a570 100644--- a/packages/core/src/repowise/core/workspace/update/__init__.py+++ b/packages/core/src/repowise/core/workspace/update/__init__.py@@ -35,12 +35,15 @@ from .state import (commit_exists,count_commits_between,get_head_commit,+ read_index_synced_at,read_repo_state,read_state_commit,reconcile_repo_head_commit,resolve_indexed_commit,restamp_changed_sync_commit,+ stamp_workspace_entry,sync_workspace_state_from_disk,+ synced_at_iso,)from .workspace_pass import (_MAX_CONCURRENT_UPDATES,@@ -71,13 +74,16 @@ __all__ = ["commit_exists","count_commits_between","get_head_commit",+ "read_index_synced_at","read_repo_state","read_state_commit","reconcile_repo_head_commit","resolve_indexed_commit","restamp_changed_sync_commit","run_cross_repo_hooks",+ "stamp_workspace_entry","sync_workspace_state_from_disk",+ "synced_at_iso","update_single_repo_index","update_workspace",]diff --git a/packages/core/src/repowise/core/workspace/update/state.py b/packages/core/src/repowise/core/workspace/update/state.pyindex e2df51d03..ba68347ca 100644--- a/packages/core/src/repowise/core/workspace/update/state.py+++ b/packages/core/src/repowise/core/workspace/update/state.py@@ -6,7 +6,7 @@ import asyncioimport json as _jsonimport loggingimport subprocess-from contextlib import suppress+from contextlib import closing, suppressfrom datetime import UTC, datetimefrom pathlib import Pathfrom typing import Any, NamedTuple@@ -119,6 +119,66 @@ def read_state_commit(repo_path: Path) -> str | None:return str(sha) if sha else None+def read_index_synced_at(repo_path: Path) -> str | None:+ """ISO time *repo_path*'s index last synced (``crud.index_synced_at``), or None.++ Plain ``sqlite3``, read-only, so sync callers and ones already on an event+ loop can ask. ``None`` for a non-SQLite store or an unreadable one.+ """+ import sqlite3++ from sqlalchemy.engine import make_url++ from ...persistence.database import get_configured_db_url, get_repo_db_path++ # Not ``resolve_db_url``: its default creates ``.repowise/``, which would+ # make an unindexed member look indexed.+ configured = get_configured_db_url()+ if configured is None:+ db_file = get_repo_db_path(repo_path)+ else:+ url = make_url(configured)+ if not url.drivername.startswith("sqlite"):+ return None+ db_file = Path(url.database or "")+ if not db_file.is_file():+ return None+ try:+ with closing(sqlite3.connect(f"{db_file.as_uri()}?mode=ro", uri=True)) as conn:+ if configured is None:+ # A repo-local store holds one repository row.+ row = conn.execute("SELECT updated_at FROM repositories LIMIT 1").fetchone()+ else:+ row = conn.execute(+ "SELECT updated_at FROM repositories WHERE local_path = ?",+ (str(repo_path),),+ ).fetchone()+ except (sqlite3.Error, ValueError):+ return None+ return synced_at_iso(row[0] if row else None)+++def synced_at_iso(raw: str | None) -> str | None:+ """A raw ``repositories.updated_at`` cell as the ISO sync time, or None."""+ from ...persistence.crud import as_utc++ try:+ synced_at = as_utc(datetime.fromisoformat(raw)) if raw else None+ except ValueError:+ return None+ return synced_at.isoformat() if synced_at else None+++def stamp_workspace_entry(entry: Any, repo_path: Path, head: str | None) -> None:+ """Record a member's finished sync on its workspace entry.++ The time is the store's own sync stamp so the config and every DB reader+ agree; now only when the store cannot be read.+ """+ entry.indexed_at = read_index_synced_at(repo_path) or datetime.now(UTC).isoformat()+ entry.last_commit_at_index = head++class IndexedCommit(NamedTuple):"""The commit an index describes, or why it cannot be named."""@@ -190,21 +250,18 @@ def sync_workspace_state_from_disk(A child repo can be updated outside the workspace orchestrator (theuser 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.+ drifts ``RepoEntry.last_commit_at_index`` (and ``indexed_at``, from the+ repo's own store) away from the actual values. 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)+ changed = [+ entry.alias+ for entry in ws_config.repos+ if _refresh_entry_from_disk(entry, (workspace_root / entry.path).resolve())+ ]if changed and save_if_changed:try:ws_config.save(workspace_root)@@ -214,6 +271,21 @@ def sync_workspace_state_from_disk(return changed+def _refresh_entry_from_disk(entry: Any, abs_path: Path) -> bool:+ """Copy the member's on-disk commit and sync time onto *entry*; True if either moved."""+ if not abs_path.is_dir():+ return False+ moved = False+ for attr, disk in (+ ("last_commit_at_index", read_state_commit(abs_path)),+ ("indexed_at", read_index_synced_at(abs_path)),+ ):+ if disk is not None and disk != getattr(entry, attr):+ setattr(entry, attr, disk)+ moved = True+ return moved++def check_repo_staleness(repo_path: Path,last_commit: str | None,diff --git a/packages/core/src/repowise/core/workspace/update/workspace_pass.py b/packages/core/src/repowise/core/workspace/update/workspace_pass.pyindex 61af92af8..ba1721d7f 100644--- a/packages/core/src/repowise/core/workspace/update/workspace_pass.py+++ b/packages/core/src/repowise/core/workspace/update/workspace_pass.py@@ -9,7 +9,6 @@ import timefrom collections.abc import Callablefrom contextlib import suppressfrom dataclasses import dataclass-from datetime import UTC, datetimefrom pathlib import Pathfrom typing import Any, NamedTuple@@ -47,6 +46,7 @@ from .state import (clear_stale_update_pending,read_repo_state,reconcile_repo_head_commit,+ stamp_workspace_entry,sync_workspace_state_from_disk,)@@ -334,8 +334,7 @@ async def _update_stale_repo(update_pass: _RepoUpdatePass, repo: _StaleRepo) ->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+ stamp_workspace_entry(entry, path, new_head)except Exception as exc:result = RepoUpdateResult(alias=alias,diff --git a/packages/server/src/repowise/server/mcp_server/_meta.py b/packages/server/src/repowise/server/mcp_server/_meta.pyindex cae392fa6..a283f60a1 100644--- a/packages/server/src/repowise/server/mcp_server/_meta.py+++ b/packages/server/src/repowise/server/mcp_server/_meta.py@@ -505,11 +505,13 @@ def freshness_from_repo(return {}out: dict[str, Any] = {"contract_version": MCP_CONTRACT_VERSION} if full_meta() else {}- updated_at = getattr(repository, "updated_at", None)+ # Deferred: this module's top-level imports stay free of the ORM.+ from repowise.core.persistence.crud import index_synced_at++ synced_at = index_synced_at(repository)age_days: int | None = None- if isinstance(updated_at, datetime):- ua = updated_at if updated_at.tzinfo else updated_at.replace(tzinfo=UTC)- age_days = max(0, (datetime.now(UTC) - ua).days)+ if synced_at is not None:+ age_days = max(0, (datetime.now(UTC) - synced_at).days)out["index_age_days"] = age_days# ``root``: the served checkout (see served_root), resolved here when omitted.diff --git a/packages/server/src/repowise/server/routers/code_health/__init__.py b/packages/server/src/repowise/server/routers/code_health/__init__.pyindex e1bb0f721..ef009a077 100644--- a/packages/server/src/repowise/server/routers/code_health/__init__.py+++ b/packages/server/src/repowise/server/routers/code_health/__init__.py@@ -31,7 +31,6 @@ from . import (from ._router import routerfrom .badge import _badge_fields, _render_badge_svg # noqa: F401from .breakdown import _finding_base_deduction, _score_breakdown_from_findings # noqa: F401-from .overview_routes import _resolve_last_indexed_at # noqa: F401# re-export helpers imported by routers/files.py + tests (keep old import path working)from .serializers import ( # noqa: F401diff --git a/packages/server/src/repowise/server/routers/code_health/overview_routes.py b/packages/server/src/repowise/server/routers/code_health/overview_routes.pyindex 37887e921..86ba5dc47 100644--- a/packages/server/src/repowise/server/routers/code_health/overview_routes.py+++ b/packages/server/src/repowise/server/routers/code_health/overview_routes.py@@ -2,8 +2,6 @@from __future__ import annotations-from datetime import datetime-from fastapi import Depends, HTTPException, Queryfrom sqlalchemy.ext.asyncio import AsyncSession@@ -31,25 +29,6 @@ from .scope import ScopeQuery, narrowfrom .serializers import _finding_to_dict, _leads_by_file, _metric_to_dict, _round_opt-def _resolve_last_indexed_at(- snapshot_taken_at: datetime | None, repo_updated_at: datetime | None-) -> str | None:- """Newest "index brought current" time as an ISO string, or ``None``.-- ``last_indexed_at`` should track the last time the index was synced to the- checkout, not just the last health snapshot. A no-change ``repowise update``- advances ``repositories.updated_at`` but takes no new snapshot, so a- snapshot-only value would report the index as hours stale right after a- refresh. Prefer whichever timestamp is newer (mirrors the overview router's- sync fallback). Both inputs come from the same DB, so their tz-awareness- matches and the comparison is safe.- """- newest = snapshot_taken_at- if repo_updated_at is not None and (newest is None or repo_updated_at > newest):- newest = repo_updated_at- return newest.isoformat() if newest else None--@router.get("/api/repos/{repo_id}/health/overview")async def health_overview(repo_id: str,@@ -107,12 +86,12 @@ async def health_overview(# come from the live rows, so reading it here would make one figure older# than its neighbours. It costs no query — ``metrics`` is in hand and the# hotspot path set is one scalar column. The snapshot is still read, for- # ``taken_at``, and for ``scope`` it would be the wrong population anyway.+ # ``snapshot_count``, and for ``scope`` it would be the wrong population anyway.snapshot = await crud.get_health_snapshot_headline(session, repo_id)hotspot_paths = await crud.get_hotspot_file_paths(session, repo_id)hotspot_health_value = hotspot_health(metrics, hotspot_paths)- last_indexed_at = _resolve_last_indexed_at(snapshot.taken_at, repo.updated_at)+ indexed_at = crud.index_synced_at(repo)# The full row, and its lead, only for the files the response lists. The# distribution and the defect-accuracy stat read path, score and NLOC off@@ -192,7 +171,7 @@ async def health_overview(include_unverified=include_unverified,),"meta": {- "last_indexed_at": last_indexed_at,+ "last_indexed_at": indexed_at.isoformat() if indexed_at else None,# The /api/repos overlay's indexed commit (state.json and the row# reconciled). This is the extension's primary indexed-commit source."head_commit": (diff --git a/packages/server/src/repowise/server/routers/overview.py b/packages/server/src/repowise/server/routers/overview.pyindex 88332b976..b343d2183 100644--- a/packages/server/src/repowise/server/routers/overview.py+++ b/packages/server/src/repowise/server/routers/overview.py@@ -123,7 +123,7 @@ async def overview_summary("total_nloc": sum(int(m.nloc or 0) for m in health_metrics),"deltas": await sections.snapshot_deltas(session, repo_id, snapshot),},- "health": await sections.health_block(session, repo_id, health_metrics, snapshot),+ "health": await sections.health_block(session, repo_id, health_metrics, snapshot, repo),"languages": mix["languages"],"docs_config_languages": mix["docs_config_languages"],**await sections.attention_block(session, repo_id),diff --git a/packages/server/src/repowise/server/routers/workspace.py b/packages/server/src/repowise/server/routers/workspace.pyindex b45d8703c..27c1fa782 100644--- a/packages/server/src/repowise/server/routers/workspace.py+++ b/packages/server/src/repowise/server/routers/workspace.py@@ -15,6 +15,7 @@ from fastapi import APIRouter, Depends, HTTPException, Query, Requestfrom repowise.core.docs_mode import resolve_docs_modefrom repowise.core.workspace import reads+from repowise.core.workspace.update import synced_at_isofrom repowise.server.deps import (get_cross_repo_enricher,get_workspace_config,@@ -112,8 +113,8 @@ def _query_repo_stats(db_path: Path) -> dict:"""Query basic stats from a repo's wiki.db using raw sqlite3.Returns a dict with repo_id, file_count, symbol_count, page_count,- doc_coverage_pct, hotspot_count, health_score, status, docs_enabled, and- docs_skip_reason. All values default to sensible neutrals on error.+ doc_coverage_pct, hotspot_count, health_score, status, docs_enabled,+ docs_skip_reason, and (when the row is read) indexed_at. All values default to sensible neutrals on error.``health_score`` is None when the repo carries no health metrics; callersdecide whether to fall back to a derived score or to render nothing.@@ -151,10 +152,11 @@ def _query_repo_stats(db_path: Path) -> dict:conn = sqlite3.connect(str(db_path))c = conn.cursor()- # repo id- row = c.execute("SELECT id FROM repositories LIMIT 1").fetchone()+ # repo id, and the sync time every other surface reports+ row = c.execute("SELECT id, updated_at FROM repositories LIMIT 1").fetchone()if row:result["repo_id"] = row[0]+ result["indexed_at"] = synced_at_iso(row[1])# file count (graph_nodes)row = c.execute("SELECT COUNT(*) FROM graph_nodes WHERE node_type = 'file'").fetchone()@@ -221,12 +223,15 @@ async def get_workspace(repo_path = (ws_root_path / r.path).resolve()db_path = repo_path / ".repowise" / "wiki.db"stats = _query_repo_stats(db_path)+ # The member's own store first: a repo updated on its own leaves the+ # config's time behind.+ indexed_at = stats.pop("indexed_at", r.indexed_at)repo_entries.append(WorkspaceRepoEntry(alias=r.alias,path=r.path,is_primary=r.is_primary,- indexed_at=r.indexed_at,+ indexed_at=indexed_at,last_commit_at_index=r.last_commit_at_index,**stats,)diff --git a/packages/server/src/repowise/server/services/overview_payload.py b/packages/server/src/repowise/server/services/overview_payload.pyindex 2b55fb2df..3be91fcf4 100644--- a/packages/server/src/repowise/server/services/overview_payload.py+++ b/packages/server/src/repowise/server/services/overview_payload.py@@ -266,7 +266,7 @@ def snapshot_history(snapshot: Any) -> list[dict]:async def health_block(- session: AsyncSession, repo_id: str, health_metrics: list[Any], snapshot: Any+ session: AsyncSession, repo_id: str, health_metrics: list[Any], snapshot: Any, repo: Any) -> dict:"""Health KPIs, the defect-accuracy stat and the snapshot trend.@@ -287,9 +287,7 @@ async def health_block(session, repo_id, metrics=health_metrics, findings=findings)hotspot_paths = await crud.get_hotspot_file_paths(session, repo_id)- last_indexed_at = (- snapshot.taken_at.isoformat() if snapshot.snapshot_count and snapshot.taken_at else None- )+ indexed_at = crud.index_synced_at(repo)return {"average_health": summary.get("average_health"),# Files in a language health has no dialect for: in no figure here.@@ -315,7 +313,7 @@ async def health_block("worst_performance_score": summary.get("worst_performance_score"),"severity_breakdown": health_severity_breakdown(findings),"defect_accuracy": defect_accuracy(health_metrics, findings),- "last_indexed_at": last_indexed_at,+ "last_indexed_at": indexed_at.isoformat() if indexed_at else None,# The true total, not the length of the windowed read."snapshot_count": snapshot.snapshot_count,"history": snapshot_history(snapshot),diff --git a/tests/unit/cli/test_freshness_stamp_fixes.py b/tests/unit/cli/test_freshness_stamp_fixes.pyindex 9aa73562d..744d2cd8c 100644--- a/tests/unit/cli/test_freshness_stamp_fixes.py+++ b/tests/unit/cli/test_freshness_stamp_fixes.py@@ -216,39 +216,17 @@ def test_freshness_self_heals_and_silences_false_stale(tmp_path):# ----------------------------------------------------------------------------# "Indexed at" tracks the last sync, not just the last health snapshot: a-# no-change update advances repositories.updated_at without a new snapshot, so-# the freshness time must not read hours-stale right after a refresh.+# index_age_days is the age of the last sync, read through crud.index_synced_at+# (the server parity test covers the routes that share it).# ----------------------------------------------------------------------------def test_last_indexed_at_prefers_newer_repo_update():- from datetime import datetime+def test_index_age_days_counts_from_the_sync_stamp(tmp_path):+ from datetime import datetime, timedelta- from repowise.server.routers.code_health import _resolve_last_indexed_at-- snapshot = datetime(2026, 7, 2, 11, 48, tzinfo=UTC)- refreshed = datetime(2026, 7, 2, 14, 25, tzinfo=UTC)- # A no-change `repowise update` bumped updated_at past the last snapshot.- assert _resolve_last_indexed_at(snapshot, refreshed) == refreshed.isoformat()---def test_last_indexed_at_keeps_snapshot_when_newer():- from datetime import datetime-- from repowise.server.routers.code_health import _resolve_last_indexed_at-- snapshot = datetime(2026, 7, 2, 14, 25, tzinfo=UTC)- older_update = datetime(2026, 7, 2, 11, 48, tzinfo=UTC)- assert _resolve_last_indexed_at(snapshot, older_update) == snapshot.isoformat()---def test_last_indexed_at_handles_missing_values():- from datetime import datetime-- from repowise.server.routers.code_health import _resolve_last_indexed_at+ from repowise.server.mcp_server._meta import freshness_from_repo- only_update = datetime(2026, 7, 2, 14, 25, tzinfo=UTC)- assert _resolve_last_indexed_at(None, only_update) == only_update.isoformat()- assert _resolve_last_indexed_at(only_update, None) == only_update.isoformat()- assert _resolve_last_indexed_at(None, None) is None+ # SQLite hands the stamp back naive; it is UTC.+ synced = (datetime.now(UTC) - timedelta(days=4, hours=1)).replace(tzinfo=None)+ repo = types.SimpleNamespace(head_commit=None, local_path=str(tmp_path), updated_at=synced)+ assert freshness_from_repo(repo, targets=[])["index_age_days"] == 4diff --git a/tests/unit/cli/test_workspace_index_time.py b/tests/unit/cli/test_workspace_index_time.pynew file mode 100644index 000000000..13bd8b609--- /dev/null+++ b/tests/unit/cli/test_workspace_index_time.py@@ -0,0 +1,39 @@+"""Workspace status reads each member's index time from its own store.++A member updated on its own leaves the workspace config's ``indexed_at`` at+the last workspace pass, which made ``repowise status`` report "2d ago" for a+repo synced hours earlier.+"""++from __future__ import annotations++import sqlite3+from pathlib import Path+from types import SimpleNamespace++from repowise.core.workspace.config import RepoEntry, WorkspaceConfig+++def _store(repo: Path) -> None:+ db = repo / ".repowise" / "wiki.db"+ db.parent.mkdir(parents=True)+ with sqlite3.connect(db) as conn:+ conn.execute("CREATE TABLE repositories (updated_at TEXT)")+ conn.execute("INSERT INTO repositories VALUES ('2026-10-20 19:21:15')")+++def test_status_rows_report_the_store_sync_time(tmp_path, monkeypatch) -> None:+ from repowise.cli.commands import status_cmd++ monkeypatch.delenv("REPOWISE_DB_URL", raising=False)+ monkeypatch.setattr(status_cmd, "_query_repo_counts", lambda _p: (1, 1))+ monkeypatch.setattr(status_cmd, "_query_page_count", lambda _p: 0)+ _store(tmp_path / "api")+ ws = WorkspaceConfig(+ repos=[RepoEntry(path="api", alias="api", indexed_at="2026-10-19T13:57:00+00:00")],+ default_repo="api",+ )++ rows = status_cmd._workspace_rows(SimpleNamespace(ws_root=tmp_path, ws_config=ws))++ assert rows[0]["indexed_at"] == "2026-10-20T19:21:15+00:00"diff --git a/tests/unit/generation/test_editor_file_fetcher.py b/tests/unit/generation/test_editor_file_fetcher.pyindex 2a517b1a2..2765e45f6 100644--- a/tests/unit/generation/test_editor_file_fetcher.py+++ b/tests/unit/generation/test_editor_file_fetcher.py@@ -196,6 +196,15 @@ async def test_fetch_repo_name(session, repo, tmp_path):assert data.repo_name == "test-repo"+async def test_fetch_indexed_at_is_the_sync_date_not_today(session, repo, tmp_path):+ # A re-render without a sync (a rebase hook, `repowise claude-md`) must+ # keep the date the index last synced.+ repo.updated_at = datetime(2026, 10, 18, 23, 30, tzinfo=UTC)+ await session.flush()+ data = await EditorFileDataFetcher(session, repo.id, tmp_path).fetch()+ assert data.indexed_at == "2026-10-18"++async def test_fetch_architecture_summary(session, repo, tmp_path):content = ("## Overview\n\n"diff --git a/tests/unit/persistence/test_index_synced_at.py b/tests/unit/persistence/test_index_synced_at.pynew file mode 100644index 000000000..6293fec1d--- /dev/null+++ b/tests/unit/persistence/test_index_synced_at.py@@ -0,0 +1,86 @@+"""The repository row's sync time moves only when the index syncs.++Every "indexed at" surface reads ``crud.index_synced_at``, so a write that+merely opens the row (a decision command, a settings edit, server+registration) must leave it alone, or a days-old index reads as fresh.+"""++from __future__ import annotations++from datetime import UTC, datetime, timedelta+from types import SimpleNamespace++from repowise.core.persistence import crud++_SYNCED = datetime(2026, 10, 18, 9, 30, tzinfo=UTC)+++async def _synced_repo(session):+ return await _synced_repo_at(session, "/tmp/r")+++def test_accessor_reads_naive_as_utc_and_tolerates_missing() -> None:+ naive = datetime(2026, 10, 18, 9, 30)+ assert crud.index_synced_at(SimpleNamespace(updated_at=naive)) == _SYNCED+ assert crud.index_synced_at(SimpleNamespace(updated_at=_SYNCED)) == _SYNCED+ assert crud.index_synced_at(None) is None+ assert crud.index_synced_at(SimpleNamespace(updated_at=None)) is None+++async def test_non_sync_writes_leave_the_stamp(async_session) -> None:+ repo = await _synced_repo(async_session)++ # Opening the row the way decisions and server registration do, with a+ # changed name and settings, then the stage stamp and a settings edit.+ await crud.upsert_repository(+ async_session, name="renamed", local_path="/tmp/r", settings={"k": 1}+ )+ await crud.stamp_analysis_ran(async_session, repo.id, "dead_code")+ repo.settings_json = '{"edited": true}'+ await async_session.flush()+ await async_session.refresh(repo)++ assert repo.name == "renamed"+ assert crud.index_synced_at(repo) == _SYNCED+++async def test_a_sync_moves_the_stamp(async_session) -> None:+ repo = await _synced_repo(async_session)+ before = datetime.now(UTC) - timedelta(seconds=5)++ await crud.upsert_repository(async_session, name="r", local_path="/tmp/r", head_commit="b" * 40)+ await async_session.refresh(repo)++ assert crud.index_synced_at(repo) >= before+++async def test_up_to_date_restamp_moves_the_stamp(tmp_path, monkeypatch) -> None:+ """The "already up to date" path syncs too, so it advances the stamp."""+ from repowise.core.persistence import create_engine, create_session_factory, get_session+ from repowise.core.persistence.database import init_db+ from repowise.core.workspace.update import reconcile_repo_head_commit++ url = f"sqlite+aiosqlite:///{(tmp_path / 'wiki.db').as_posix()}"+ monkeypatch.setenv("REPOWISE_DB_URL", url)+ engine = create_engine(url)+ await init_db(engine)+ sf = create_session_factory(engine)+ async with get_session(sf) as session:+ await _synced_repo_at(session, str(tmp_path))+ before = datetime.now(UTC) - timedelta(seconds=5)++ await reconcile_repo_head_commit(tmp_path, "a" * 40)++ async with get_session(sf) as session:+ repo = await crud.get_repository_by_path(session, str(tmp_path))+ assert crud.index_synced_at(repo) >= before+ await engine.dispose()+++async def _synced_repo_at(session, local_path: str):+ repo = await crud.upsert_repository(+ session, name="r", local_path=local_path, head_commit="a" * 40+ )+ repo.updated_at = _SYNCED+ await session.flush()+ return repodiff --git a/tests/unit/server/golden/overview_summary.json b/tests/unit/server/golden/overview_summary.jsonindex adb591792..06cb6edf5 100644--- a/tests/unit/server/golden/overview_summary.json+++ b/tests/unit/server/golden/overview_summary.json@@ -65,7 +65,7 @@"low": 0},"defect_accuracy": null,- "last_indexed_at": null,+ "last_indexed_at": "2026-09-02T12:00:00+00:00","snapshot_count": 0,"history": []},diff --git a/tests/unit/server/test_index_age_parity.py b/tests/unit/server/test_index_age_parity.pynew file mode 100644index 000000000..3878b2c7f--- /dev/null+++ b/tests/unit/server/test_index_age_parity.py@@ -0,0 +1,37 @@+"""Every server surface reports one index time: the last sync.++The MCP envelope, the health overview the extension reads, and the Overview+page all read ``crud.index_synced_at``, and a settings edit is not a sync.+"""++from __future__ import annotations++from datetime import UTC, datetime, timedelta++from httpx import AsyncClient++from repowise.core.persistence import crud+from repowise.core.persistence.database import get_session+from repowise.server.mcp_server._meta import freshness_from_repo+from tests.unit.server.conftest import create_test_repo+++async def test_surfaces_agree_on_the_sync_time(client: AsyncClient, app) -> None:+ repo_id = (await create_test_repo(client))["id"]+ synced = (datetime.now(UTC) - timedelta(days=3)).replace(microsecond=0)+ async with get_session(app.state.session_factory) as session:+ (await crud.get_repository(session, repo_id)).updated_at = synced+ await session.commit()++ # Not a sync: must not make the index read as fresh.+ patched = await client.patch(f"/api/repos/{repo_id}", json={"settings": {"k": 1}})+ assert patched.status_code == 200++ health = (await client.get(f"/api/repos/{repo_id}/health/overview")).json()+ overview = (await client.get(f"/api/repos/{repo_id}/overview-summary")).json()+ async with get_session(app.state.session_factory) as session:+ meta = freshness_from_repo(await crud.get_repository(session, repo_id), targets=[])++ assert health["meta"]["last_indexed_at"] == synced.isoformat()+ assert overview["health"]["last_indexed_at"] == synced.isoformat()+ assert meta["index_age_days"] == 3diff --git a/tests/unit/server/test_workspace_router.py b/tests/unit/server/test_workspace_router.pyindex 007ef5b76..5361f7c4a 100644--- a/tests/unit/server/test_workspace_router.py+++ b/tests/unit/server/test_workspace_router.py@@ -239,7 +239,7 @@ def _create_workspace_repo_db(with sqlite3.connect(str(db_path)) as conn:conn.executescript("""- CREATE TABLE repositories (id TEXT PRIMARY KEY);+ CREATE TABLE repositories (id TEXT PRIMARY KEY, updated_at TEXT);CREATE TABLE graph_nodes (id TEXT PRIMARY KEY,node_type TEXT NOT NULL DEFAULT 'file',@@ -257,7 +257,8 @@ def _create_workspace_repo_db(score REAL NOT NULL,nloc INTEGER NOT NULL);- INSERT INTO repositories (id) VALUES ('repo-backend');+ INSERT INTO repositories (id, updated_at)+ VALUES ('repo-backend', '2026-10-20 19:21:15');INSERT INTO graph_nodes (id, node_type, language, symbol_count) VALUES('src/a.py', 'file', 'python', 2),('src/b.py', 'file', 'python', 3),@@ -936,7 +937,7 @@ class TestQueryRepoStats:# a missing table aborts the whole block, so create the minimal set.conn.executescript("""- CREATE TABLE repositories (id TEXT PRIMARY KEY);+ CREATE TABLE repositories (id TEXT PRIMARY KEY, updated_at TEXT);CREATE TABLE graph_nodes (id TEXT PRIMARY KEY,node_type TEXT NOT NULL DEFAULT 'file',@@ -1723,3 +1724,17 @@ class TestGetTestImpact:assert data["unresolved"][0]["consumer_symbol_id"] is Noneassert data["files_analyzed"][0]["state"] == "measured"assert data["summary"]["states"]["measured"] == 1+++async def test_workspace_indexed_at_comes_from_the_member_store(tmp_path: Path) -> None:+ """A member updated on its own leaves the config's time behind the store's."""+ _create_workspace_repo_db(tmp_path, "backend")+ app = _make_workspace_app(ws_config=_make_ws_config(), workspace_root=str(tmp_path))+ transport = ASGITransport(app=app)+ async with AsyncClient(transport=transport, base_url="http://test") as c:+ repos = (await c.get("/api/workspace")).json()["repos"]++ by_alias = {r["alias"]: r["indexed_at"] for r in repos}+ # backend: the store stamp over the config's 2026-04-12; frontend has no store.+ assert by_alias == {"backend": "2026-10-20T19:21:15+00:00", "frontend": None}diff --git a/tests/unit/workspace/test_index_synced_at.py b/tests/unit/workspace/test_index_synced_at.pynew file mode 100644index 000000000..766483730--- /dev/null+++ b/tests/unit/workspace/test_index_synced_at.py@@ -0,0 +1,84 @@+"""A member's index time comes from its own store, never the workspace config.++A repo updated on its own leaves ``indexed_at`` in the workspace config at the+last workspace pass, so every workspace surface reads the store's sync stamp.+"""++from __future__ import annotations++import sqlite3+from pathlib import Path+from types import SimpleNamespace++import pytest++from repowise.core.workspace.config import RepoEntry, WorkspaceConfig+from repowise.core.workspace.update import (+ read_index_synced_at,+ stamp_workspace_entry,+ sync_workspace_state_from_disk,+)++_SYNCED = "2026-10-20T19:21:15.667232+00:00"++[email protected](autouse=True)+def _repo_local_store(monkeypatch):+ monkeypatch.delenv("REPOWISE_DB_URL", raising=False)+++def _store(repo: Path, stamp: str | None = "2026-10-20 19:21:15.667232") -> Path:+ db = repo / ".repowise" / "wiki.db"+ db.parent.mkdir(parents=True)+ with sqlite3.connect(db) as conn:+ conn.execute("CREATE TABLE repositories (updated_at TEXT)")+ if stamp is not None:+ conn.execute("INSERT INTO repositories VALUES (?)", (stamp,))+ return repo+++def test_reads_the_store_stamp_as_utc(tmp_path: Path) -> None:+ assert read_index_synced_at(_store(tmp_path)) == _SYNCED+++def test_no_store_or_no_row_is_none(tmp_path: Path) -> None:+ assert read_index_synced_at(tmp_path) is None+ assert read_index_synced_at(_store(tmp_path, stamp=None)) is None+++def test_reconcile_replaces_a_stale_config_time(tmp_path: Path) -> None:+ _store(tmp_path / "api")+ ws = WorkspaceConfig(+ repos=[RepoEntry(path="api", alias="api", indexed_at="2026-10-19T13:57:00+00:00")]+ )++ assert sync_workspace_state_from_disk(tmp_path, ws, save_if_changed=False) == ["api"]+ assert ws.get_repo("api").indexed_at == _SYNCED+ # Agreeing values are not drift.+ assert sync_workspace_state_from_disk(tmp_path, ws, save_if_changed=False) == []+++def test_stamp_workspace_entry_uses_the_store_time(tmp_path: Path) -> None:+ entry = SimpleNamespace(indexed_at=None, last_commit_at_index=None)+ stamp_workspace_entry(entry, _store(tmp_path), "c" * 40)+ assert (entry.indexed_at, entry.last_commit_at_index) == (_SYNCED, "c" * 40)+++def test_shared_store_reads_this_members_row(tmp_path: Path, monkeypatch) -> None:+ db = tmp_path / "shared.db"+ with sqlite3.connect(db) as conn:+ conn.execute("CREATE TABLE repositories (local_path TEXT, updated_at TEXT)")+ conn.executemany(+ "INSERT INTO repositories VALUES (?, ?)",+ [("/other", "2026-10-01 00:00:00"), (str(tmp_path), "2026-10-20 19:21:15.667232")],+ )+ monkeypatch.setenv("REPOWISE_DB_URL", f"sqlite+aiosqlite:///{db.as_posix()}")+ assert read_index_synced_at(tmp_path) == _SYNCED+++def test_unreadable_stamps_are_none(tmp_path: Path, monkeypatch) -> None:+ from repowise.core.workspace.update import synced_at_iso++ assert synced_at_iso("not a time") is None+ monkeypatch.setenv("REPOWISE_DB_URL", "postgresql://u@h/db")+ assert read_index_synced_at(tmp_path) is None