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: keep a repository's url and branch on read-only writes, and report the true last sync (#4374)
Raghav Chamadiya38cd3aeaf44c
diff --git a/packages/core/src/repowise/core/persistence/_interfaces/_meta.py b/packages/core/src/repowise/core/persistence/_interfaces/_meta.pyindex e26d82d64..5087b919d 100644--- a/packages/core/src/repowise/core/persistence/_interfaces/_meta.py+++ b/packages/core/src/repowise/core/persistence/_interfaces/_meta.py@@ -39,8 +39,8 @@ class MetaIndexStore(ABC):*,name: str,local_path: str,- url: str = "",- default_branch: str = "main",+ url: str | None = None,+ default_branch: str | None = None,settings: dict | None = None,) -> Repository: ...diff --git a/packages/core/src/repowise/core/persistence/crud/repository.py b/packages/core/src/repowise/core/persistence/crud/repository.pyindex 5921cceb7..f56edb31d 100644--- a/packages/core/src/repowise/core/persistence/crud/repository.py+++ b/packages/core/src/repowise/core/persistence/crud/repository.py@@ -34,8 +34,8 @@ async def upsert_repository(*,name: str,local_path: str,- url: str = "",- default_branch: str = "main",+ url: str | None = None,+ default_branch: str | None = None,settings: dict | None = None,head_commit: str | None = None,stamp_head: bool = False,@@ -51,6 +51,12 @@ async def upsert_repository(per-repo session routing keyed by that id resolves consistently. Ignoredwhen a row for ``local_path`` already exists (the existing id wins).+ ``url``, ``default_branch`` and ``settings`` overwrite an existing row only+ when passed; ``None`` keeps the stored value, so a command that only needs+ the row never resets a ``master`` branch to ``main``. Pass ``""`` to clear+ the url. An empty branch counts as not passed, since a repository always+ has one. A new row defaults to ``""`` and ``"main"``.+``head_commit`` records the git commit the index was built against — thevalue the MCP ``_meta`` freshness check compares to the live HEAD. A newrow always gets one: the passed value, else ``local_path``'s git HEAD read@@ -73,16 +79,18 @@ async def upsert_repository(id=repo_id or _new_uuid(),name=name,local_path=local_path,- url=url,- default_branch=default_branch,+ url=url or "",+ default_branch=default_branch or "main",settings_json=json.dumps(settings or {}),head_commit=resolved_head,)session.add(repo)else:repo.name = name- repo.url = url- repo.default_branch = default_branch+ if url is not None:+ repo.url = url+ if default_branch:+ repo.default_branch = default_branchif settings is not None:repo.settings_json = json.dumps(keep_analysis_ran(repo.settings_json, settings))# Only advance the stamp when we could read a real commit; never blankdiff --git a/packages/core/src/repowise/core/persistence/stores/_sql_meta.py b/packages/core/src/repowise/core/persistence/stores/_sql_meta.pyindex 551cf2784..398179e96 100644--- a/packages/core/src/repowise/core/persistence/stores/_sql_meta.py+++ b/packages/core/src/repowise/core/persistence/stores/_sql_meta.py@@ -33,8 +33,8 @@ class _SqlMetaMixin(MetaIndexStore):*,name: str,local_path: str,- url: str = "",- default_branch: str = "main",+ url: str | None = None,+ default_branch: str | None = None,settings: dict | None = None,) -> Repository:return await crud.upsert_repository(diff --git a/packages/server/src/repowise/server/services/overview_payload.py b/packages/server/src/repowise/server/services/overview_payload.pyindex 5dc9a178b..77d486ee6 100644--- a/packages/server/src/repowise/server/services/overview_payload.py+++ b/packages/server/src/repowise/server/services/overview_payload.py@@ -392,47 +392,53 @@ async def savings_block(repo_local_path: str | None) -> dict:}-def sync_times(job_rows: list[Any], repo_updated_at: Any) -> dict:- """Last sync, last full re-index, its model and any active job id.+def _job_mode(job: Any) -> str | None:+ try:+ return json.loads(job.config_json or "{}").get("mode")+ except Exception:+ return None- ``job_rows`` are newest first.- """- last_sync_at: str | None = None- last_resync_at: str | None = None- last_resync_dt = None- last_sync_model: str | None = None++def _scan_jobs(job_rows: list[Any]) -> tuple[Any, Any, str | None]:+ """Newest completed sync job, newest completed full re-index, active job id."""+ sync_job = resync_job = Noneactive_job_id: str | None = Nonefor j in job_rows:- try:- mode = json.loads(j.config_json or "{}").get("mode")- except Exception:- mode = Noneif j.status in ("pending", "running") and active_job_id is None:active_job_id = j.id- if j.status == "completed" and j.finished_at:- if mode == "full_resync" and last_resync_at is None:- last_resync_at = j.finished_at.isoformat()- last_resync_dt = j.finished_at- elif mode != "full_resync" and last_sync_at is None:- last_sync_at = j.finished_at.isoformat()- last_sync_model = j.model_name or None-- # Fall back to the repository's own ``updated_at`` when no completed- # server-side sync job exists. CLI / git-hook auto-syncs (``repowise- # update``) refresh the index and bump ``repositories.updated_at`` via- # ``upsert_repository``, but never create a GenerationJob row, so a- # job-only derivation reports "never synced" even though the index is- # current. Only adopt it when it is newer than the last full re-index so a- # re-index is not relabelled as a sync.- if (- last_sync_at is None- and repo_updated_at is not None- and (last_resync_dt is None or repo_updated_at > last_resync_dt)- ):- last_sync_at = repo_updated_at.isoformat()+ if j.status != "completed" or not j.finished_at:+ continue+ if _job_mode(j) == "full_resync":+ resync_job = resync_job or j+ else:+ sync_job = sync_job or j+ return sync_job, resync_job, active_job_id+++def sync_times(job_rows: list[Any], repo_updated_at: Any) -> dict:+ """Last sync, last full re-index, its model and any active job id.++ ``job_rows`` are newest first. ``repo_updated_at`` is the repository's+ sync stamp (:func:`crud.index_synced_at`), which CLI and git-hook syncs+ move without writing a GenerationJob row; the later of it and the newest+ completed sync job is the last sync.+ """+ sync_job, resync_job, active_job_id = _scan_jobs(job_rows)+ job_times = [crud.as_utc(j.finished_at) for j in (sync_job, resync_job) if j is not None]+ # A job stamps the row before it finishes, so the stamp wins only for a+ # sync made outside the server, and only when newer than the last full+ # re-index so a re-index is not relabelled as a sync. That sync's model+ # is unknown, so the job's model is not carried over to it.+ stamp = crud.as_utc(repo_updated_at)+ if stamp is not None and all(stamp > t for t in job_times):+ last_sync_at, last_sync_model = repo_updated_at.isoformat(), None+ elif sync_job is not None:+ last_sync_at, last_sync_model = sync_job.finished_at.isoformat(), sync_job.model_name or None+ else:+ last_sync_at, last_sync_model = None, Nonereturn {"last_sync_at": last_sync_at,- "last_resync_at": last_resync_at,+ "last_resync_at": resync_job.finished_at.isoformat() if resync_job else None,"last_sync_model": last_sync_model,"active_job_id": active_job_id,}diff --git a/tests/unit/persistence/test_repository_row_fields.py b/tests/unit/persistence/test_repository_row_fields.pynew file mode 100644index 000000000..695a6a9d2--- /dev/null+++ b/tests/unit/persistence/test_repository_row_fields.py@@ -0,0 +1,60 @@+"""upsert_repository keeps a stored url and default branch unless one is passed.++Most callers (decision commands, status, update passes) pass only name and+path; a default of ``""`` / ``"main"`` there reset a ``master`` repo to+``main`` and blanked its url on every call.+"""++from __future__ import annotations++from repowise.core.persistence import crud+++async def test_callers_without_url_or_branch_keep_the_stored_values(async_session) -> None:+ await crud.upsert_repository(+ async_session,+ name="r",+ local_path="/tmp/r",+ url="https://example.com/r.git",+ default_branch="master",+ )++ repo = await crud.upsert_repository(async_session, name="r", local_path="/tmp/r")++ assert repo.url == "https://example.com/r.git"+ assert repo.default_branch == "master"+++async def test_passed_values_overwrite_and_empty_url_clears(async_session) -> None:+ await crud.upsert_repository(+ async_session, name="r", local_path="/tmp/r", url="https://a", default_branch="master"+ )++ repo = await crud.upsert_repository(+ async_session, name="r", local_path="/tmp/r", url="", default_branch="develop"+ )++ assert repo.url == ""+ assert repo.default_branch == "develop"+++async def test_an_empty_branch_is_never_stored(async_session) -> None:+ new = await crud.upsert_repository(+ async_session, name="r", local_path="/tmp/e", default_branch=""+ )+ assert new.default_branch == "main"++ await crud.upsert_repository(+ async_session, name="r", local_path="/tmp/e", default_branch="master"+ )+ kept = await crud.upsert_repository(+ async_session, name="r", local_path="/tmp/e", default_branch=""+ )+ assert kept.default_branch == "master"+++async def test_a_new_row_without_values_gets_the_defaults(async_session) -> None:+ repo = await crud.upsert_repository(async_session, name="r", local_path="/tmp/new")++ assert repo.url == ""+ assert repo.default_branch == "main"diff --git a/tests/unit/server/test_overview_payload_sections.py b/tests/unit/server/test_overview_payload_sections.pyindex f65f3bee0..b9f0d6f3e 100644--- a/tests/unit/server/test_overview_payload_sections.py+++ b/tests/unit/server/test_overview_payload_sections.py@@ -54,6 +54,25 @@ def test_sync_times_falls_back_to_repo_updated_at_only_after_resync() -> None:assert sync_times([], _T0)["last_sync_at"] == _T0.isoformat()+def test_sync_times_reports_the_later_of_the_sync_job_and_the_row_stamp() -> None:+ # A CLI sync after the last server job: the stamp is the last sync, and the+ # job's model does not describe it.+ newer_cli = sync_times([_job("completed", "incremental", _T0, model_name="m1")], _T2)+ assert newer_cli["last_sync_at"] == _T2.isoformat()+ assert newer_cli["last_sync_model"] is None++ # A server job after the stamp (a job stamps the row before it finishes).+ newer_job = sync_times([_job("completed", "incremental", _T2, model_name="m1")], _T1)+ assert newer_job["last_sync_at"] == _T2.isoformat()+ assert newer_job["last_sync_model"] == "m1"+++def test_sync_times_compares_a_naive_row_stamp_as_utc() -> None:+ naive_stamp = datetime(2026, 9, 3)+ jobs = [_job("completed", "incremental", _T1)]+ assert sync_times(jobs, naive_stamp)["last_sync_at"] == naive_stamp.isoformat()++def test_defect_accuracy_survives_a_malformed_details_blob() -> None:metric = SimpleNamespace(file_path="a.py", score=3.0, nloc=10, has_test_file=False, module="a")bad = SimpleNamespace(diff --git a/tests/unit/server/test_overview_sync.py b/tests/unit/server/test_overview_sync.pyindex 80132becf..6aef2b85d 100644--- a/tests/unit/server/test_overview_sync.py+++ b/tests/unit/server/test_overview_sync.py@@ -81,6 +81,20 @@ async def test_completed_sync_job_wins_over_fallback(client: AsyncClient, app) -assert body["sync"]["last_sync_at"] != body["repo"]["updated_at"]+async def test_newer_cli_sync_wins_over_an_older_sync_job(client: AsyncClient, app) -> None:+ """A server sync job from 2020 does not hide a later CLI sync of the row."""+ repo = await create_test_repo(client)+ await _complete_job(app, repo["id"], mode="sync", finished_at=datetime(2020, 1, 1))++ resp = await client.get(f"/api/repos/{repo['id']}/overview-summary")+ assert resp.status_code == 200+ body = resp.json()++ assert body["sync"]["last_sync_at"] == body["repo"]["updated_at"]+ assert body["sync"]["last_sync_model"] is None++@pytest.mark.asyncioasync def test_head_commit_heals_from_state_json(client: AsyncClient, app, tmp_path) -> None:"""overview-summary serves state.json's last_sync_commit when the DB row was