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(persistence): read HEAD through a worktree's .git pointer file (#3293)

Cestercian95c874d5d004
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/command.py b/packages/cli/src/repowise/cli/commands/update_cmd/command.py
index 54562d57b..7bc814f16 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/command.py
@@ -1455,9 +1455,10 @@ def run_update(
save_state(repo_path, updated_state)
# No stamp_head_commit here, which is the behaviour this branch has
# always had: the re-score's `upsert_repository` re-reads HEAD from
- # disk and advances the row itself. It re-reads rather than being told,
- # so it is a no-op in a linked worktree or a non-git checkout — both
- # pre-existing, and neither is what this change is about.
+ # disk and advances the row itself. The re-read follows a worktree
+ # `.git` pointer (the same helper the MCP reader uses). A path that
+ # is not a checkout still leaves a stored commit untouched, because a
+ # missed read never blanks one.
_finish_outcome(repo_path, agents_md)
consume_update_pending(repo_path, head)
if emitter is not None:
diff --git a/packages/core/src/repowise/core/git_head.py b/packages/core/src/repowise/core/git_head.py
new file mode 100644
index 000000000..b0caf8a64
--- /dev/null
+++ b/packages/core/src/repowise/core/git_head.py
@@ -0,0 +1,124 @@
+"""Read a checkout's HEAD commit without spawning git.
+
+``repowise update`` stores this SHA on the repository row, and the MCP
+freshness check reads the live HEAD back, on every index and every tool
+call. Both go through :func:`read_head_commit` so the value written is the
+value compared: a linked worktree, whose ``.git`` is a ``gitdir:`` file
+rather than a directory, records its own commit instead of keeping the
+main checkout's forever.
+
+No ``git`` subprocess and no GitPython. The callers are hot paths.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+
+def resolve_git_dir(local_path: str | Path) -> Path | None:
+ """The git directory a checkout's ``.git`` names, or ``None``.
+
+ A normal checkout's ``.git`` is that directory. A linked worktree or a
+ submodule stores a file, ``gitdir: <path>``; a relative path is resolved
+ against the checkout (the directory that holds the file). The returned
+ path is not required to exist — a dangling pointer still has a parent,
+ which is how the overview remote lookup climbs out of
+ ``.git/worktrees/<name>`` — so callers that need a readable directory
+ check :meth:`~pathlib.Path.is_dir` themselves.
+
+ ``None`` for a missing ``.git``, a file that is not a ``gitdir:``
+ pointer, or an empty path.
+ """
+ root = Path(local_path)
+ git_path = root / ".git"
+ if git_path.is_dir():
+ return git_path
+ if not git_path.is_file():
+ return None
+ try:
+ pointer = git_path.read_text(encoding="utf-8").strip()
+ except OSError:
+ return None
+ if not pointer.startswith("gitdir:"):
+ return None
+ raw = pointer.split(":", 1)[1].strip()
+ if not raw:
+ return None
+ resolved = Path(raw)
+ try:
+ if not resolved.is_absolute():
+ resolved = (root / resolved).resolve()
+ except OSError:
+ return None
+ return resolved
+
+
+def read_head_commit(local_path: str | Path | None) -> str | None:
+ """The checkout's HEAD SHA, or ``None`` when it cannot be resolved.
+
+ Reads ``HEAD`` from :func:`resolve_git_dir`. A detached HEAD is the SHA
+ already in that file. A symbolic ``ref:`` is resolved against the common
+ directory — ``commondir`` (relative to the gitdir) when the file exists,
+ otherwise the gitdir itself, which is a normal checkout and a submodule.
+ The loose ref is tried first, then ``packed-refs`` (``#`` comments and
+ ``^`` peeled lines skipped). One ref is followed, never a chain.
+
+ Unknown layouts and unresolvable refs return ``None`` rather than a
+ guess. An empty *local_path* returns ``None`` without touching the
+ filesystem.
+ """
+ if not local_path:
+ return None
+ try:
+ git_dir = resolve_git_dir(local_path)
+ if git_dir is None or not git_dir.is_dir():
+ return None
+ head = (git_dir / "HEAD").read_text(encoding="utf-8").strip()
+ except OSError:
+ return None
+ if head.startswith("ref: "):
+ return _resolve_symbolic_ref(git_dir, head[5:].strip())
+ return head or None
+
+
+def _common_dir(git_dir: Path) -> Path:
+ """Where shared refs live for *git_dir*.
+
+ A linked worktree records this in ``commondir`` (``../..`` back to the
+ main ``.git``). The path is relative to the gitdir. No file, or an empty
+ one, means the gitdir is its own common dir.
+ """
+ try:
+ raw = (git_dir / "commondir").read_text(encoding="utf-8").strip()
+ except OSError:
+ return git_dir
+ if not raw:
+ return git_dir
+ path = Path(raw)
+ if path.is_absolute():
+ return path
+ return git_dir / path
+
+
+def _resolve_symbolic_ref(git_dir: Path, ref_rel: str) -> str | None:
+ """The SHA *ref_rel* names under *git_dir*'s common dir, or ``None``.
+
+ An empty loose ref is an answer (``None``), not a miss: packed-refs is
+ only the fallback when the loose file cannot be read.
+ """
+ common = _common_dir(git_dir)
+ try:
+ return (common / ref_rel).read_text(encoding="utf-8").strip() or None
+ except OSError:
+ pass
+ try:
+ packed = (common / "packed-refs").read_text(encoding="utf-8")
+ except OSError:
+ return None
+ for raw in packed.splitlines():
+ if raw.startswith("#") or raw.startswith("^"):
+ continue
+ sha, _, name = raw.partition(" ")
+ if name.strip() == ref_rel:
+ return sha.strip() or None
+ return None
diff --git a/packages/core/src/repowise/core/persistence/crud/repository.py b/packages/core/src/repowise/core/persistence/crud/repository.py
index 02f20e101..603570499 100644
--- a/packages/core/src/repowise/core/persistence/crud/repository.py
+++ b/packages/core/src/repowise/core/persistence/crud/repository.py
@@ -8,11 +8,11 @@ from __future__ import annotations
import json
from datetime import UTC, datetime
-from pathlib import Path
from sqlalchemy import delete, select
from sqlalchemy.ext.asyncio import AsyncSession
+from ...git_head import read_head_commit
from ..models import (
GenerationJob,
Page,
@@ -131,40 +131,20 @@ async def stamp_analysis_ran(session: AsyncSession, repository_id: str, stage: s
def _read_head_commit(local_path: str) -> str | None:
"""Return the repo's current git HEAD SHA via plain file I/O, or None.
- Dependency-free (no ``git`` binary, no gitpython): parse ``.git/HEAD`` and
- follow at most one ref, falling back to ``packed-refs``. Returns ``None``
- when *local_path* is not a git checkout (hosted/ephemeral indexes) or the
- ref can't be resolved. Mirrors the MCP ``_meta`` reader so the value we
- write is read back the same way — keeping freshness comparisons honest.
+ Dependency-free (no ``git`` binary, no gitpython). Returns ``None`` when
+ *local_path* is not a git checkout (hosted/ephemeral indexes) or the ref
+ can't be resolved. A linked worktree or submodule keeps ``.git`` as a
+ ``gitdir:`` pointer file; the shared reader follows that pointer and
+ resolves the branch against the common dir, so the stored commit is the
+ worktree's own.
+
+ The MCP ``_meta.read_live_head`` reader calls the same helper. The old
+ ``is_dir()`` guard treated a pointer file as non-git on both sides so the
+ written commit and the read-back comparison stayed symmetric; they still
+ share one implementation, and a ``None`` read still never blanks a
+ commit already stored.
"""
- try:
- git_dir = Path(local_path) / ".git"
- # Linked worktrees use a ``.git`` *file* (gitdir pointer), not a dir;
- # treated as non-git here on purpose so this stays in lockstep with the
- # MCP ``_meta.read_live_head`` reader (same is_dir() guard), keeping
- # the written commit and the read-back comparison symmetric.
- if not git_dir.is_dir():
- return None
- head = (git_dir / "HEAD").read_text(encoding="utf-8").strip()
- except OSError:
- return None
- if head.startswith("ref: "):
- ref_rel = head[5:].strip()
- try:
- return (git_dir / ref_rel).read_text(encoding="utf-8").strip() or None
- except OSError:
- pass
- try:
- for raw in (git_dir / "packed-refs").read_text(encoding="utf-8").splitlines():
- if raw.startswith("#") or raw.startswith("^"):
- continue
- sha, _, name = raw.partition(" ")
- if name.strip() == ref_rel:
- return sha.strip() or None
- except OSError:
- return None
- return None
- return head or None
+ return read_head_commit(local_path)
async def set_repo_function_mod_p80(session: AsyncSession, repo_id: str, value: int) -> None:
diff --git a/packages/server/src/repowise/server/mcp_server/_meta.py b/packages/server/src/repowise/server/mcp_server/_meta.py
index 9a26c5b58..cf5e0e820 100644
--- a/packages/server/src/repowise/server/mcp_server/_meta.py
+++ b/packages/server/src/repowise/server/mcp_server/_meta.py
@@ -26,6 +26,7 @@ from datetime import UTC, datetime
from pathlib import Path
from typing import Any
+from repowise.core.git_head import read_head_commit
from repowise.core.index_scope import (
CANONICAL_INDEX_SCOPE_PROJECTION,
INDEX_SCOPE_ENV,
@@ -73,46 +74,21 @@ _STALE_AGE_FLOOR_DAYS = 90
def read_live_head(local_path: str | None) -> str | None:
"""Read the repo's current git HEAD SHA via plain file I/O.
- Returns a full 40-char SHA, or ``None`` when the repo isn't a git checkout
- on disk (hosted indexes, ephemeral clones). Avoids spawning ``git``: we
- parse ``.git/HEAD`` and follow at most one ref — fast enough to call on
- every MCP tool response without caching, and never blocks the event loop.
+ Returns a full SHA, or ``None`` when the repo isn't a git checkout on
+ disk (hosted indexes, ephemeral clones). Avoids spawning ``git``: the
+ shared reader parses ``HEAD`` and follows at most one ref — fast enough
+ to call on every MCP tool response without caching, and never blocks the
+ event loop. A linked worktree or submodule, whose ``.git`` is a
+ ``gitdir:`` file, resolves the same way.
Detached HEADs are handled (the HEAD file contains the SHA directly).
Unknown ref formats just return ``None`` rather than guessing — staleness
semantics should fail closed (no warning) rather than open (false alarms).
+
+ ``repositories.head_commit`` is written by the same helper, so the
+ freshness comparison stays symmetric with what ``update`` stored.
"""
- if not local_path:
- return None
- git_dir = Path(local_path) / ".git"
- if not git_dir.is_dir():
- return None
- try:
- head = (git_dir / "HEAD").read_text(encoding="utf-8").strip()
- except OSError:
- return None
- if head.startswith("ref: "):
- ref_rel = head[5:].strip()
- # Try the loose ref first, then packed-refs as a fallback. Packed-refs
- # is common right after `git gc` or on freshly cloned repos.
- ref_file = git_dir / ref_rel
- try:
- return ref_file.read_text(encoding="utf-8").strip() or None
- except OSError:
- pass
- packed = git_dir / "packed-refs"
- try:
- for raw in packed.read_text(encoding="utf-8").splitlines():
- if raw.startswith("#") or raw.startswith("^"):
- continue
- sha, _, name = raw.partition(" ")
- if name.strip() == ref_rel:
- return sha.strip() or None
- except OSError:
- return None
- return None
- # Detached HEAD: the file contains the SHA verbatim.
- return head or None
+ return read_head_commit(local_path)
def read_state_sync_commit(local_path: str | None) -> str | None:
diff --git a/tests/integration/test_worktree_head_commit.py b/tests/integration/test_worktree_head_commit.py
new file mode 100644
index 000000000..73ac806b1
--- /dev/null
+++ b/tests/integration/test_worktree_head_commit.py
@@ -0,0 +1,134 @@
+"""A linked worktree's ``update`` stores that worktree's HEAD.
+
+``repositories.head_commit`` used to be read only from a ``.git`` directory.
+In a linked worktree ``.git`` is a ``gitdir:`` file, so the row kept the
+commit it was seeded with and ``impacted-tests`` treated the index as
+untrustworthy. After a commit and ``update``, the row matches
+``git rev-parse HEAD``.
+"""
+
+from __future__ import annotations
+
+import os
+import shutil
+import sqlite3
+import subprocess
+from contextlib import closing
+from pathlib import Path
+
+import pytest
+from click.testing import CliRunner
+
+from repowise.cli.main import cli
+
+pytestmark = pytest.mark.skipif(shutil.which("git") is None, reason="git not installed")
+
+
+def _git(args: list[str], cwd: Path) -> None:
+ env = os.environ.copy()
+ env.update(
+ {
+ "GIT_AUTHOR_NAME": "t",
+ "GIT_AUTHOR_EMAIL": "[email protected]",
+ "GIT_COMMITTER_NAME": "t",
+ "GIT_COMMITTER_EMAIL": "[email protected]",
+ }
+ )
+ subprocess.run(["git", *args], cwd=cwd, check=True, capture_output=True, env=env)
+
+
+def _rev_parse(cwd: Path, *args: str) -> str:
+ return subprocess.check_output(["git", "rev-parse", *args], cwd=cwd, text=True).strip()
+
+
+def _remove_worktree(base_repo: Path, worktree_dir: Path) -> None:
+ subprocess.run(
+ ["git", "worktree", "remove", "--force", str(worktree_dir)],
+ cwd=base_repo,
+ capture_output=True,
+ )
+ shutil.rmtree(worktree_dir, ignore_errors=True)
+ subprocess.run(["git", "worktree", "prune"], cwd=base_repo, capture_output=True)
+
+
+def _head_commit(db_path: Path, local_path: Path) -> str | None:
+ with closing(sqlite3.connect(db_path)) as conn:
+ row = conn.execute(
+ "SELECT head_commit FROM repositories WHERE local_path = ?",
+ (str(local_path),),
+ ).fetchone()
+ return None if row is None else row[0]
+
+
+def test_worktree_update_stores_its_own_head(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ """Seed at the base commit, commit in the worktree, then ``update``.
+
+ A staged edit of the module the one test imports is then selected by
+ ``impacted-tests --staged`` instead of ``:all``.
+ """
+ monkeypatch.delenv("REPOWISE_DB_URL", raising=False)
+ monkeypatch.delenv("REPOWISE_DATABASE_URL", raising=False)
+
+ repo = tmp_path / "repo"
+ (repo / "pkg").mkdir(parents=True)
+ (repo / "pkg" / "calc.py").write_text("def add(a, b):\n return a + b\n", encoding="utf-8")
+ (repo / "tests").mkdir()
+ (repo / "tests" / "test_calc.py").write_text(
+ "from pkg.calc import add\n\ndef test_add():\n assert add(1, 2) == 3\n",
+ encoding="utf-8",
+ )
+ _git(["init", "-b", "main"], repo)
+ _git(["add", "-A"], repo)
+ _git(["commit", "-m", "init"], repo)
+
+ runner = CliRunner()
+ init_base = runner.invoke(cli, ["init", str(repo), "--index-only"], catch_exceptions=False)
+ assert init_base.exit_code == 0, init_base.output
+
+ worktree = tmp_path / "repo-wt"
+ _git(["worktree", "add", "-b", "feat", str(worktree)], repo)
+ try:
+ init_wt = runner.invoke(
+ cli, ["init", str(worktree), "--index-only"], catch_exceptions=False
+ )
+ assert init_wt.exit_code == 0, init_wt.output
+
+ seeded = _head_commit(worktree / ".repowise" / "wiki.db", worktree)
+ assert seeded == _rev_parse(worktree, "HEAD")
+
+ calc = worktree / "pkg" / "calc.py"
+ calc.write_text("def add(a, b):\n return a + b + 0\n", encoding="utf-8")
+ _git(["add", "pkg/calc.py"], worktree)
+ _git(["commit", "-m", "tweak"], worktree)
+ parent = _rev_parse(worktree, "HEAD~1")
+ head = _rev_parse(worktree, "HEAD")
+ assert head != parent
+
+ updated = runner.invoke(
+ cli, ["update", str(worktree), "--index-only"], catch_exceptions=False
+ )
+ assert updated.exit_code == 0, updated.output
+ assert "Already up to date" not in updated.output
+ assert "No changed files detected." not in updated.output
+
+ stored = _head_commit(worktree / ".repowise" / "wiki.db", worktree)
+ assert stored == head, updated.output
+ assert stored != parent
+
+ # The disagreement this bug produced made --staged select every test.
+ # Stage one line of the module the test imports and ask again.
+ calc.write_text("def add(a, b):\n return a + b + 1\n", encoding="utf-8")
+ _git(["add", "pkg/calc.py"], worktree)
+ selected = runner.invoke(
+ cli,
+ ["impacted-tests", "--staged", "--format", "args", "--path", str(worktree)],
+ catch_exceptions=False,
+ )
+ assert selected.exit_code == 0, selected.output
+ # stdout is the runner args; the "1 argument(s)" line is stderr, and
+ # CliRunner reports them together. ``:all`` is the full-run sentinel.
+ assert selected.output.splitlines()[0].strip() == "tests/test_calc.py", selected.output
+ assert ":all" not in selected.output
+ assert "Run every test" not in selected.output
+ finally:
+ _remove_worktree(repo, worktree)
diff --git a/tests/unit/persistence/test_repository_head_commit.py b/tests/unit/persistence/test_repository_head_commit.py
index 67dfc09e6..95eebc138 100644
--- a/tests/unit/persistence/test_repository_head_commit.py
+++ b/tests/unit/persistence/test_repository_head_commit.py
@@ -65,13 +65,111 @@ def test_read_head_commit_unresolvable_ref_returns_none(tmp_path: Path) -> None:
assert _read_head_commit(str(tmp_path)) is None
-def test_read_head_commit_worktree_gitfile_returns_none(tmp_path: Path) -> None:
- # Linked worktrees use a .git FILE; intentionally unsupported (mirrors
- # the MCP _meta reader) so freshness stays symmetric.
+def test_read_head_commit_worktree_missing_gitdir_returns_none(tmp_path: Path) -> None:
+ # A pointer at a directory that is not there is not a checkout.
(tmp_path / ".git").write_text("gitdir: /somewhere/.git/worktrees/wt\n", encoding="utf-8")
assert _read_head_commit(str(tmp_path)) is None
+def test_read_head_commit_garbled_gitfile_returns_none(tmp_path: Path) -> None:
+ (tmp_path / ".git").write_text("not a gitdir\n", encoding="utf-8")
+ assert _read_head_commit(str(tmp_path)) is None
+
+
+_DECOY = "d" * 40
+
+
+def linked_worktree(root: Path, sha: str, *, how: str, relative: bool = False) -> Path:
+ """A hand-built linked worktree. Returns the linked checkout.
+
+ ``<root>/main/.git/worktrees/wt`` has its own ``HEAD`` and a ``commondir``
+ of ``../..``. The branch ref lives in the common dir (loose or packed).
+ A different SHA sitting in the worktree gitdir's own ``refs/`` must be
+ ignored: symbolic refs resolve against the common dir, not the private one.
+ """
+ main = root / "main"
+ common = main / ".git"
+ wt_git = common / "worktrees" / "wt"
+ wt_git.mkdir(parents=True)
+ (wt_git / "commondir").write_text("../..\n", encoding="utf-8")
+ (wt_git / "refs" / "heads").mkdir(parents=True)
+ (wt_git / "refs" / "heads" / "feat").write_text(_DECOY + "\n", encoding="utf-8")
+
+ if how == "detached":
+ (wt_git / "HEAD").write_text(sha + "\n", encoding="utf-8")
+ else:
+ (wt_git / "HEAD").write_text("ref: refs/heads/feat\n", encoding="utf-8")
+ if how == "loose":
+ ref = common / "refs" / "heads"
+ ref.mkdir(parents=True)
+ (ref / "feat").write_text(sha + "\n", encoding="utf-8")
+ # Packed copy of a different SHA: the loose ref wins.
+ (common / "packed-refs").write_text(
+ f"# pack-refs with: peeled fully-peeled sorted\n{_DECOY} refs/heads/feat\n",
+ encoding="utf-8",
+ )
+ elif how == "packed":
+ wrong = "e" * 40
+ (common / "packed-refs").write_text(
+ "# pack-refs with: peeled fully-peeled sorted\n"
+ f"# {wrong} refs/heads/feat\n"
+ f"^{wrong} refs/heads/feat\n"
+ f"{sha} refs/heads/feat\n"
+ f"^{sha}\n",
+ encoding="utf-8",
+ )
+ else:
+ raise ValueError(how)
+
+ checkout = root / "wt"
+ checkout.mkdir()
+ pointer = "../main/.git/worktrees/wt" if relative else str(wt_git)
+ (checkout / ".git").write_text(f"gitdir: {pointer}\n", encoding="utf-8")
+ return checkout
+
+
+def submodule_checkout(root: Path, sha: str) -> Path:
+ """A submodule: ``gitdir:`` is relative and there is no ``commondir``."""
+ modules = root / "main" / ".git" / "modules" / "libs" / "sub"
+ (modules / "refs" / "heads").mkdir(parents=True)
+ (modules / "HEAD").write_text("ref: refs/heads/main\n", encoding="utf-8")
+ (modules / "refs" / "heads" / "main").write_text(sha + "\n", encoding="utf-8")
+ checkout = root / "main" / "libs" / "sub"
+ checkout.mkdir(parents=True)
+ (checkout / ".git").write_text("gitdir: ../../.git/modules/libs/sub\n", encoding="utf-8")
+ return checkout
+
+
+def test_read_head_commit_worktree_loose_ref(tmp_path: Path) -> None:
+ sha = "a" * 40
+ checkout = linked_worktree(tmp_path, sha, how="loose")
+ assert _read_head_commit(str(checkout)) == sha
+
+
+def test_read_head_commit_worktree_packed_refs(tmp_path: Path) -> None:
+ sha = "c" * 40
+ checkout = linked_worktree(tmp_path, sha, how="packed")
+ assert _read_head_commit(str(checkout)) == sha
+
+
+def test_read_head_commit_worktree_detached(tmp_path: Path) -> None:
+ sha = "b" * 40
+ checkout = linked_worktree(tmp_path, sha, how="detached")
+ assert _read_head_commit(str(checkout)) == sha
+
+
+def test_read_head_commit_worktree_relative_gitdir(tmp_path: Path) -> None:
+ sha = "f" * 40
+ checkout = linked_worktree(tmp_path, sha, how="loose", relative=True)
+ assert _read_head_commit(str(checkout)) == sha
+
+
+def test_read_head_commit_submodule_gitdir(tmp_path: Path) -> None:
+ sha = "9" * 40
+ checkout = submodule_checkout(tmp_path, sha)
+ assert _read_head_commit(str(checkout)) == sha
+
+
@pytest.mark.asyncio
async def test_upsert_repository_stamps_and_advances_head(tmp_path: Path) -> None:
sha1 = "1" * 40
@@ -126,3 +224,33 @@ async def test_upsert_repository_keeps_head_when_path_not_git(tmp_path: Path) ->
assert repo.head_commit == sha # preserved, not nulled
finally:
await engine.dispose()
+
+
+async def test_upsert_repository_advances_worktree_head(tmp_path: Path) -> None:
+ """A linked worktree's own commit is stored, and a later miss does not blank it."""
+ sha1 = "a" * 40
+ checkout = linked_worktree(tmp_path, sha1, how="loose")
+
+ engine = create_engine("sqlite+aiosqlite:///:memory:")
+ await init_db(engine)
+ sf = create_session_factory(engine)
+ try:
+ async with get_session(sf) as session:
+ repo = await upsert_repository(session, name="wt", local_path=str(checkout))
+ assert repo.head_commit == sha1
+
+ sha2 = "b" * 40
+ (tmp_path / "main" / ".git" / "refs" / "heads" / "feat").write_text(
+ sha2 + "\n", encoding="utf-8"
+ )
+ async with get_session(sf) as session:
+ repo = await upsert_repository(session, name="wt", local_path=str(checkout))
+ assert repo.head_commit == sha2
+
+ (checkout / ".git").write_text("not a gitdir\n", encoding="utf-8")
+ async with get_session(sf) as session:
+ repo = await upsert_repository(session, name="wt", local_path=str(checkout))
+ assert repo.head_commit == sha2
+ finally:
+ await engine.dispose()
diff --git a/tests/unit/server/mcp/test_meta_freshness.py b/tests/unit/server/mcp/test_meta_freshness.py
index 1bd887bd5..836eeb648 100644
--- a/tests/unit/server/mcp/test_meta_freshness.py
+++ b/tests/unit/server/mcp/test_meta_freshness.py
@@ -20,10 +20,15 @@ from __future__ import annotations
import subprocess
import types
+from pathlib import Path
import pytest
from repowise.server.mcp_server import _meta
+from tests.unit.persistence.test_repository_head_commit import (
+ linked_worktree,
+ submodule_checkout,
+)
_INDEXED = "a" * 40
_LIVE = "b" * 40
@@ -321,3 +326,58 @@ async def test_execution_flows_targets_name_the_traced_files(setup_mcp, monkeypa
assert result["_meta"]["indexed_commit"] == _INDEXED[:12]
assert seen[-1]["repository"] is not None
assert "src/auth/service.py" in seen[-1]["targets"]
+
+
+def test_read_live_head_plain_git_dir(tmp_path: Path) -> None:
+ sha = "a" * 40
+ git = tmp_path / ".git"
+ (git / "refs" / "heads").mkdir(parents=True)
+ (git / "HEAD").write_text("ref: refs/heads/main\n", encoding="utf-8")
+ (git / "refs" / "heads" / "main").write_text(sha + "\n", encoding="utf-8")
+ assert _meta.read_live_head(str(tmp_path)) == sha
+
+
+def test_read_live_head_non_git_and_empty(tmp_path: Path) -> None:
+ assert _meta.read_live_head(str(tmp_path)) is None
+ assert _meta.read_live_head(None) is None
+ assert _meta.read_live_head("") is None
+
+
+def test_read_live_head_worktree_loose_ref(tmp_path: Path) -> None:
+ sha = "a" * 40
+ checkout = linked_worktree(tmp_path, sha, how="loose")
+ assert _meta.read_live_head(str(checkout)) == sha
+
+
+def test_read_live_head_worktree_packed_refs(tmp_path: Path) -> None:
+ sha = "c" * 40
+ checkout = linked_worktree(tmp_path, sha, how="packed")
+ assert _meta.read_live_head(str(checkout)) == sha
+
+
+def test_read_live_head_worktree_detached(tmp_path: Path) -> None:
+ sha = "b" * 40
+ checkout = linked_worktree(tmp_path, sha, how="detached")
+ assert _meta.read_live_head(str(checkout)) == sha
+
+
+def test_read_live_head_worktree_relative_gitdir(tmp_path: Path) -> None:
+ sha = "f" * 40
+ checkout = linked_worktree(tmp_path, sha, how="loose", relative=True)
+ assert _meta.read_live_head(str(checkout)) == sha
+
+
+def test_read_live_head_worktree_missing_gitdir_returns_none(tmp_path: Path) -> None:
+ (tmp_path / ".git").write_text("gitdir: /somewhere/.git/worktrees/wt\n", encoding="utf-8")
+ assert _meta.read_live_head(str(tmp_path)) is None
+
+
+def test_read_live_head_garbled_gitfile_returns_none(tmp_path: Path) -> None:
+ (tmp_path / ".git").write_text("not a gitdir\n", encoding="utf-8")
+ assert _meta.read_live_head(str(tmp_path)) is None
+
+
+def test_read_live_head_submodule_gitdir(tmp_path: Path) -> None:
+ sha = "9" * 40
+ checkout = submodule_checkout(tmp_path, sha)
+ assert _meta.read_live_head(str(checkout)) == sha