Skip to content

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

fix(cli): record a repository's real default branch and credential-free remote url (#4381)

Raghav Chamadiyae48f6f7a2c93
diff --git a/docs/reference/API_REFERENCE.md b/docs/reference/API_REFERENCE.md
index c81caa287..cba89efdc 100644
--- a/docs/reference/API_REFERENCE.md
+++ b/docs/reference/API_REFERENCE.md
@@ -438,6 +438,14 @@ client routing cannot collide with real ids; passing one to
`GET /api/search` returns an empty list rather than falling back to the primary
repo (`routers/search.py`).
+`POST /api/repos` on a path that is already registered updates that row, and a
+`url` or `default_branch` the body leaves out keeps its stored value, as with
+`PATCH`. A new row takes an omitted value from the path's registry row, else
+from git: the remote url (credentials removed) and default branch. The schema
+defaults (`""`, `"main"`) fill only what git cannot name. Each index replaces
+both with what git reports (`routers/repos.py`, `crud/repository.py`), so a
+value set by `PATCH` or `POST` holds until the next index whose git names one.
+
### 5.4 Pagination
`limit`/`offset` is the convention (41 operations take `limit`, 18 take
diff --git a/packages/core/src/repowise/core/git_refs.py b/packages/core/src/repowise/core/git_refs.py
index 5510ff165..5b259d0ba 100644
--- a/packages/core/src/repowise/core/git_refs.py
+++ b/packages/core/src/repowise/core/git_refs.py
@@ -27,6 +27,7 @@ __all__ = [
"commit_file_sets",
"current_branch",
"default_base",
+ "default_branch",
"files_by_ref",
"find_path_removal",
"is_ancestor",
@@ -149,6 +150,16 @@ def default_base(repo_path: str) -> str:
return "HEAD"
+def default_branch(repo_path: str) -> str | None:
+ """The repository's default branch name, ``None`` when git cannot name one.
+
+ :func:`default_base` without the remote prefix: ``origin/HEAD``'s target,
+ else a local trunk. A detached checkout with neither has no answer.
+ """
+ base = default_base(repo_path)
+ return None if base == "HEAD" else base.removeprefix("origin/")
+
+
def _parse_ref_line(line: str) -> BranchRef | None:
"""One ``for-each-ref`` row, or ``None`` when it names no usable branch."""
parts = line.split("\t")
diff --git a/packages/core/src/repowise/core/persistence/crud/repository.py b/packages/core/src/repowise/core/persistence/crud/repository.py
index f56edb31d..d386d90ca 100644
--- a/packages/core/src/repowise/core/persistence/crud/repository.py
+++ b/packages/core/src/repowise/core/persistence/crud/repository.py
@@ -6,13 +6,15 @@ every public name, so existing imports are unaffected.
from __future__ import annotations
+import asyncio
import json
from datetime import UTC, datetime
from sqlalchemy import delete, select
from sqlalchemy.ext.asyncio import AsyncSession
-from ...git_head import read_head_commit
+from ...forges import read_remote_url, strip_credentials
+from ...git_head import read_head_commit, resolve_git_dir
from ..models import (
GenerationJob,
Page,
@@ -55,7 +57,11 @@ async def upsert_repository(
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"``.
+ has one. When the call creates the row or records a sync and leaves either
+ one unset, it is read from git: the remote url (``origin``, else
+ ``upstream``) with credentials removed, and the default branch. A value
+ git cannot give keeps the stored one, and a new row defaults to ``""``
+ and ``"main"``.
``head_commit`` records the git commit the index was built against — the
value the MCP ``_meta`` freshness check compares to the live HEAD. A new
@@ -73,6 +79,11 @@ async def upsert_repository(
stamping = repo is None or stamp_head or head_commit is not None
resolved_head = (head_commit or _read_head_commit(local_path)) if stamping else None
+ if stamping and (url is None or not default_branch):
+ # Off the event loop: the branch read runs git, and the server awaits this.
+ git_url, git_branch = await asyncio.to_thread(_read_git_remote, local_path)
+ url = git_url if url is None else url
+ default_branch = default_branch or git_branch
if repo is None:
repo = Repository(
@@ -178,6 +189,19 @@ def _read_head_commit(local_path: str) -> str | None:
return read_head_commit(local_path)
+def _read_git_remote(local_path: str) -> tuple[str | None, str | None]:
+ """``(remote url without credentials, default branch)``, ``None`` where git has no answer."""
+ git_dir = resolve_git_dir(local_path)
+ # Without a HEAD git would search parent directories and answer for another repo.
+ if git_dir is None or not (git_dir / "HEAD").is_file():
+ return None, None
+ # Deferred: git_refs pulls in the change-risk stack, which a session open never needs.
+ from ...git_refs import default_branch
+
+ remote = read_remote_url(local_path)
+ return (strip_credentials(remote) if remote else None), default_branch(local_path)
+
+
async def set_repo_function_mod_p80(session: AsyncSession, repo_id: str, value: int) -> None:
"""Store the repo-wide function-mod p80 a full index measured.
diff --git a/packages/server/src/repowise/server/repo_db.py b/packages/server/src/repowise/server/repo_db.py
index 3a1582947..7b5d22613 100644
--- a/packages/server/src/repowise/server/repo_db.py
+++ b/packages/server/src/repowise/server/repo_db.py
@@ -81,8 +81,8 @@ async def ensure_repo_registration(
*,
local_path: str,
name: str,
- url: str = "",
- default_branch: str = "main",
+ url: str | None = None,
+ default_branch: str | None = None,
settings: dict | None = None,
repo_id: str | None = None,
):
@@ -92,7 +92,8 @@ async def ensure_repo_registration(
with ``repo_id`` when given, so the primary-DB registry row and the
canonical row share one id — and registers the session factory plus a
per-repo FTS instance on ``app_state``. Idempotent: an already-registered
- repo returns its existing factory.
+ repo returns its existing factory. A ``None`` url or branch on a new row
+ is read from git (:func:`upsert_repository`).
Returns ``(session_factory, repo_id)`` for the canonical row.
"""
@@ -158,8 +159,8 @@ async def _ensure_repo_row(
*,
name: str,
local_path: str,
- url: str,
- default_branch: str,
+ url: str | None,
+ default_branch: str | None,
settings: dict | None,
repo_id: str | None,
) -> str:
diff --git a/packages/server/src/repowise/server/routers/overview.py b/packages/server/src/repowise/server/routers/overview.py
index b343d2183..5e27e65dd 100644
--- a/packages/server/src/repowise/server/routers/overview.py
+++ b/packages/server/src/repowise/server/routers/overview.py
@@ -37,9 +37,9 @@ HEALTH_HISTORY_POINTS = 12
def _remote_url(stored_url: str | None, local_path: str | None) -> str | None:
"""Best-effort git remote for a repo, with any credentials removed.
- ``repositories.url`` is client-supplied and empty for most CLI-registered
- repos, so fall back to reading ``origin`` out of ``.git/config``. Parsed
- rather than shelled out to: this runs on a page load, and ``git remote
+ ``repositories.url`` is empty when the last sync found no remote, so fall
+ back to reading one added since out of ``.git/config``. Parsed rather than
+ shelled out to: this runs on a page load, and ``git remote
get-url`` would cost a process spawn per request for a string sitting in a
file we can read.
diff --git a/packages/server/src/repowise/server/routers/repos.py b/packages/server/src/repowise/server/routers/repos.py
index 91cad0c4b..772d29973 100644
--- a/packages/server/src/repowise/server/routers/repos.py
+++ b/packages/server/src/repowise/server/routers/repos.py
@@ -76,6 +76,38 @@ async def _get_repo_or_404(session: AsyncSession, repo_id: str) -> Repository:
return repo
+def _sent_metadata(body: RepoCreate) -> tuple[str | None, str | None]:
+ """``(url, default_branch)`` the client sent; ``None`` for an omitted one.
+
+ An existing row keeps what the body leaves out, as PATCH does; a new row
+ reads an omitted one from git, else takes the schema default
+ (:func:`crud.upsert_repository`).
+ """
+ sent = body.model_fields_set
+ return (
+ body.url if "url" in sent else None,
+ body.default_branch if "default_branch" in sent else None,
+ )
+
+
+async def _new_row_metadata(
+ session: AsyncSession, body: RepoCreate
+) -> tuple[str | None, str | None]:
+ """``(url, default_branch)`` for a canonical row ``POST`` may create.
+
+ What the body omits comes from the registry row an earlier ``index=false``
+ call stored; ``None`` (read from git) when there is none.
+ """
+ url, branch = _sent_metadata(body)
+ registered = await crud.get_repository_by_path(session, body.local_path)
+ if registered is None:
+ return url, branch
+ return (
+ registered.url if url is None else url,
+ registered.default_branch if branch is None else branch,
+ )
+
+
@router.post("", response_model=RepoResponse, status_code=201)
async def create_repo(
body: RepoCreate,
@@ -93,12 +125,13 @@ async def create_repo(
"""
if not body.index:
# Metadata-only registration: per-repo storage is created on first index.
+ url, branch = _sent_metadata(body)
repo = await crud.upsert_repository(
session,
name=body.name,
local_path=body.local_path,
- url=body.url,
- default_branch=body.default_branch,
+ url=url,
+ default_branch=branch,
settings=body.settings,
)
return RepoResponse.from_orm(repo)
@@ -107,13 +140,16 @@ async def create_repo(
app_state = request.app.state
+ sent_url, sent_branch = _sent_metadata(body)
+ url, branch = await _new_row_metadata(session, body)
+
# Canonical row in the repo-local DB; the factory routes all later access.
repo_factory, repo_id = await ensure_repo_registration(
app_state,
local_path=body.local_path,
name=body.name,
- url=body.url,
- default_branch=body.default_branch,
+ url=url,
+ default_branch=branch,
settings=body.settings,
)
@@ -123,8 +159,10 @@ async def create_repo(
repo = await crud.get_repository(repo_session, repo_id)
if repo is not None:
repo.name = body.name
- repo.url = body.url
- repo.default_branch = body.default_branch
+ if sent_url is not None:
+ repo.url = sent_url
+ if sent_branch is not None:
+ repo.default_branch = sent_branch
if body.settings is not None:
import json as _json
@@ -133,6 +171,7 @@ async def create_repo(
)
await repo_session.flush()
response = RepoResponse.from_orm(repo)
+ stored_url, stored_branch = repo.url, repo.default_branch
else: # pragma: no cover — the row was created two lines above
raise HTTPException(status_code=500, detail="Repository registration failed")
@@ -143,8 +182,8 @@ async def create_repo(
repo_id=repo_id,
name=body.name,
local_path=body.local_path,
- url=body.url,
- default_branch=body.default_branch,
+ url=stored_url,
+ default_branch=stored_branch,
settings=body.settings,
)
await session.commit()
diff --git a/tests/unit/persistence/test_repository_row_fields.py b/tests/unit/persistence/test_repository_row_fields.py
index 695a6a9d2..bd4426010 100644
--- a/tests/unit/persistence/test_repository_row_fields.py
+++ b/tests/unit/persistence/test_repository_row_fields.py
@@ -7,9 +7,26 @@ path; a default of ``""`` / ``"main"`` there reset a ``master`` repo to
from __future__ import annotations
+import subprocess
+from pathlib import Path
+
from repowise.core.persistence import crud
+def _git(repo: Path, *args: str) -> None:
+ subprocess.run(["git", *args], cwd=repo, check=True, capture_output=True)
+
+
+def _checkout(tmp_path: Path, branch: str) -> Path:
+ root = tmp_path / "repo"
+ root.mkdir()
+ _git(root, "init", "-b", branch)
+ (root / "a.txt").write_text("a\n", encoding="utf-8")
+ _git(root, "add", "a.txt")
+ _git(root, "-c", "user.email=t@t", "-c", "user.name=t", "commit", "-m", "a")
+ return root
+
+
async def test_callers_without_url_or_branch_keep_the_stored_values(async_session) -> None:
await crud.upsert_repository(
async_session,
@@ -58,3 +75,87 @@ async def test_a_new_row_without_values_gets_the_defaults(async_session) -> None
assert repo.url == ""
assert repo.default_branch == "main"
+
+
+async def test_a_sync_records_the_branch_and_a_credential_free_remote(
+ async_session, tmp_path: Path
+) -> None:
+ root = _checkout(tmp_path, "master")
+ _git(root, "remote", "add", "origin", "https://user:[email protected]/acme/legacy.git")
+
+ repo = await crud.upsert_repository(
+ async_session, name="legacy", local_path=str(root), stamp_head=True
+ )
+
+ assert repo.default_branch == "master"
+ assert repo.url == "https://github.com/acme/legacy.git"
+
+
+async def test_a_sync_passing_an_empty_branch_reads_it_from_git(
+ async_session, tmp_path: Path
+) -> None:
+ root = _checkout(tmp_path, "master")
+
+ repo = await crud.upsert_repository(
+ async_session, name="r", local_path=str(root), default_branch="", stamp_head=True
+ )
+
+ assert repo.default_branch == "master"
+
+
+async def test_the_origin_head_target_wins_over_a_local_trunk(
+ async_session, tmp_path: Path
+) -> None:
+ root = _checkout(tmp_path, "main")
+ _git(root, "update-ref", "refs/remotes/origin/trunk", "HEAD")
+ _git(root, "symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/trunk")
+
+ repo = await crud.upsert_repository(async_session, name="r", local_path=str(root))
+
+ assert repo.default_branch == "trunk"
+
+
+async def test_a_sync_git_cannot_answer_keeps_the_stored_values(
+ async_session, tmp_path: Path
+) -> None:
+ root = _checkout(tmp_path, "topic") # no remote, no origin/HEAD, no trunk
+ await crud.upsert_repository(
+ async_session,
+ name="r",
+ local_path=str(root),
+ url="https://example.com/r.git",
+ default_branch="develop",
+ )
+
+ repo = await crud.upsert_repository(
+ async_session, name="r", local_path=str(root), stamp_head=True
+ )
+
+ assert repo.url == "https://example.com/r.git"
+ assert repo.default_branch == "develop"
+
+
+async def test_a_call_that_only_needs_the_row_does_not_read_git(
+ async_session, tmp_path: Path
+) -> None:
+ root = _checkout(tmp_path, "master")
+ await crud.upsert_repository(
+ async_session, name="r", local_path=str(root), default_branch="release"
+ )
+
+ repo = await crud.upsert_repository(async_session, name="r", local_path=str(root))
+
+ assert repo.default_branch == "release"
+
+
+async def test_a_broken_git_dir_never_answers_for_a_parent_repo(
+ async_session, tmp_path: Path
+) -> None:
+ parent = _checkout(tmp_path, "master")
+ child = parent / "child"
+ (child / ".git").mkdir(parents=True)
+
+ repo = await crud.upsert_repository(async_session, name="c", local_path=str(child))
+
+ assert repo.default_branch == "main"
+ assert repo.url == ""
diff --git a/tests/unit/server/test_repos.py b/tests/unit/server/test_repos.py
index 1c50dc467..b4ef7b0e2 100644
--- a/tests/unit/server/test_repos.py
+++ b/tests/unit/server/test_repos.py
@@ -254,3 +254,130 @@ async def test_stats_file_count_excludes_symbol_nodes(client: AsyncClient, sessi
assert data["symbol_count"] == 10
assert overview["stats"]["symbol_count"] == 10
assert symbols["total"] == 10
+
+
+async def test_create_on_a_registered_path_keeps_omitted_url_and_branch(
+ client: AsyncClient,
+) -> None:
+ repo_dir = Path(tempfile.mkdtemp()) / "legacy"
+ repo_dir.mkdir()
+ (repo_dir / ".git").mkdir()
+ first = {"index": False, "name": "legacy", "local_path": str(repo_dir)}
+ await client.post(
+ "/api/repos",
+ json={**first, "url": "https://github.com/acme/legacy", "default_branch": "master"},
+ )
+
+ again = await client.post("/api/repos", json={**first, "name": "renamed"})
+
+ data = again.json()
+ assert data["name"] == "renamed"
+ assert data["url"] == "https://github.com/acme/legacy"
+ assert data["default_branch"] == "master"
+
+ sent = await client.post("/api/repos", json={**first, "url": "", "default_branch": "dev"})
+ assert sent.json()["url"] == ""
+ assert sent.json()["default_branch"] == "dev"
+
+
+async def test_indexed_create_on_a_registered_path_keeps_omitted_fields_in_both_rows(
+ client: AsyncClient, app, tmp_path, monkeypatch
+) -> None:
+ from sqlalchemy import select
+
+ from repowise.core.persistence.models import Repository
+ from repowise.server.routers import repos as repos_module
+
+ async def _noop(job_id, app_state, session_factory_override=None):
+ return None
+
+ monkeypatch.setattr(repos_module, "execute_job", _noop)
+ repo_dir = tmp_path / "legacy"
+ repo_dir.mkdir()
+ (repo_dir / ".git").mkdir()
+ body = {"name": "legacy", "local_path": str(repo_dir), "index": True}
+ await client.post(
+ "/api/repos",
+ json={**body, "url": "https://github.com/acme/legacy", "default_branch": "master"},
+ )
+
+ data = (await client.post("/api/repos", json=body)).json()
+
+ assert (data["url"], data["default_branch"]) == ("https://github.com/acme/legacy", "master")
+ async with app.state.session_factory() as session:
+ row = (await session.execute(select(Repository))).scalar_one()
+ assert (row.url, row.default_branch) == ("https://github.com/acme/legacy", "master")
+
+
+async def test_indexed_create_after_a_metadata_only_one_keeps_its_fields(
+ client: AsyncClient, app, tmp_path, monkeypatch
+) -> None:
+ from sqlalchemy import select
+
+ from repowise.core.persistence.models import Repository
+ from repowise.server.routers import repos as repos_module
+
+ async def _noop(job_id, app_state, session_factory_override=None):
+ return None
+
+ monkeypatch.setattr(repos_module, "execute_job", _noop)
+ repo_dir = tmp_path / "legacy"
+ repo_dir.mkdir()
+ (repo_dir / ".git").mkdir()
+ body = {"name": "legacy", "local_path": str(repo_dir)}
+ await client.post(
+ "/api/repos",
+ json={
+ **body,
+ "index": False,
+ "url": "https://github.com/acme/legacy",
+ "default_branch": "master",
+ },
+ )
+
+ data = (await client.post("/api/repos", json={**body, "index": True})).json()
+
+ assert (data["url"], data["default_branch"]) == ("https://github.com/acme/legacy", "master")
+ async with app.state.session_factory() as session:
+ row = (await session.execute(select(Repository))).scalar_one()
+ assert (row.url, row.default_branch) == ("https://github.com/acme/legacy", "master")
+
+
+def _checkout(root: Path, branch: str) -> Path:
+ import subprocess
+
+ def git(*args: str) -> None:
+ subprocess.run(["git", *args], cwd=root, check=True, capture_output=True)
+
+ root.mkdir()
+ git("init", "-b", branch)
+ git("remote", "add", "origin", f"https://user:[email protected]/acme/{root.name}.git")
+ (root / "a.txt").write_text("a\n", encoding="utf-8")
+ git("add", "a.txt")
+ git("-c", "user.email=t@t", "-c", "user.name=t", "commit", "-m", "a")
+ return root
+
+
[email protected]("index", [False, True])
+async def test_create_without_url_or_branch_reads_them_from_git(
+ client: AsyncClient, tmp_path, monkeypatch, index: bool
+) -> None:
+ from repowise.server.routers import repos as repos_module
+
+ async def _noop(job_id, app_state, session_factory_override=None):
+ return None
+
+ monkeypatch.setattr(repos_module, "execute_job", _noop)
+ root = _checkout(tmp_path / "legacy", "master")
+
+ body = {"name": "legacy", "local_path": str(root), "index": index}
+ data = (await client.post("/api/repos", json=body)).json()
+
+ assert (data["url"], data["default_branch"]) == (
+ "https://github.com/acme/legacy.git",
+ "master",
+ )
diff --git a/tests/unit/test_git_refs.py b/tests/unit/test_git_refs.py
index 33cccb2bd..bb40d747c 100644
--- a/tests/unit/test_git_refs.py
+++ b/tests/unit/test_git_refs.py
@@ -15,6 +15,7 @@ from repowise.core.git_refs import (
commit_file_sets,
current_branch,
default_base,
+ default_branch,
find_path_removal,
list_branches,
remote_name,
@@ -124,6 +125,29 @@ class TestDefaultBase:
assert default_base(str(tmp_path / "nowhere_at_all")) == "HEAD"
+class TestDefaultBranch:
+ def test_is_the_origin_head_target_without_the_remote(self, repo: Path) -> None:
+ _run(repo, "branch", "master", "main")
+ _run(repo, "update-ref", "refs/remotes/origin/master", "master")
+ _run(repo, "symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/master")
+ assert default_branch(str(repo)) == "master"
+
+ def test_falls_back_to_a_local_trunk(self, tmp_path: Path) -> None:
+ root = tmp_path / "legacy"
+ root.mkdir()
+ _run(root, "init", "-b", "master")
+ _commit(root, "a.txt", "a\n", "a")
+ assert default_branch(str(root)) == "master"
+
+ def test_is_none_when_git_cannot_name_one(self, tmp_path: Path) -> None:
+ root = tmp_path / "trunkless"
+ root.mkdir()
+ _run(root, "init", "-b", "topic")
+ _commit(root, "a.txt", "a\n", "a")
+ assert default_branch(str(root)) is None
+ assert default_branch(str(tmp_path / "nowhere_at_all")) is None
+
+
class TestChangedFiles:
def test_three_dot_semantics_exclude_the_base_side(self, repo: Path) -> None:
files = changed_files(str(repo), "main", "feat")