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(mcp): mark served targets with uncommitted edits instead of calling them fresh (#3100)

Raghav Chamadiyaee2afff890a0
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.md
index 89881a5e3..94e8b926e 100644
--- a/docs/agent/MCP_TOOLS.md
+++ b/docs/agent/MCP_TOOLS.md
@@ -87,7 +87,7 @@ Every tool returns a JSON object with a `_meta` envelope. Most fields appear onl
| Field | What to do with it |
|-------|--------------------|
-| `stale_warning` | Present only when the index is behind in a way that changed served files. Run `repowise update` before trusting file-level detail. Its absence means current. |
+| `stale_warning` | Present only when the index is behind in a way that changed served files, or a served file has uncommitted edits or was indexed from edits since reverted (`working_tree_dirty` counts the edited ones; run `repowise update --working-tree`). Run `repowise update` before trusting file-level detail. Its absence means current. |
| `indexed_commit`, `live_head`, `index_behind` | Which commit the answer describes and whether HEAD has moved since. |
| `complete` | Symbol bodies or whole files served verified against the live file. Do not re-read them. |
| `state` | `degraded`, `partial` or `truncated` when something fired, with reasons. A degraded empty result is a failed read, not an empty repository. |
diff --git a/docs/reference/MCP_RESPONSE_FIELDS.md b/docs/reference/MCP_RESPONSE_FIELDS.md
index 186ac2708..be5371392 100644
--- a/docs/reference/MCP_RESPONSE_FIELDS.md
+++ b/docs/reference/MCP_RESPONSE_FIELDS.md
@@ -29,7 +29,8 @@ Routine responses carry a lean envelope. `get_overview`, called once per session
| `indexed_commit` | When a repository is resolved | Short SHA the index was built from |
| `live_head` | When `.git/HEAD` is readable | Short SHA of the current checkout; equal to `indexed_commit` when current |
| `index_behind` | When the live-versus-indexed comparison ran | `true` if HEAD moved, `false` if it matches. Absent means the comparison could not run |
-| `stale_warning` | Only on a real signal | HEAD moved and the move changed files this response serves, or the index is very old and git is unreachable. Two commits with identical trees set `index_behind` with no warning |
+| `stale_warning` | Only on a real signal | HEAD moved and the move changed files this response serves, a file this response serves has uncommitted edits the index has not seen or was indexed from uncommitted edits since reverted, or the index is very old and git is unreachable. Two commits with identical trees set `index_behind` with no warning |
+| `working_tree_dirty` | Only when above zero | How many served targets have uncommitted edits no `repowise update --working-tree` has indexed. Source reads are live; graph and index facts for those files predate the edit. A dirty tree elsewhere never sets it |
| `index_scope` | When the index records it and its `status` is not `complete` (whole object on `get_overview`, or everywhere with `REPOWISE_MCP_INDEX_SCOPE=full`) | Compact description of how the index was built: run mode, provenance, git tier, whether it is whole |
| `embedder_degraded` | When an embedder is resolved | `true` or `false` |
| `embedder`, `embedder_warning` | Only when the embedder fell back to a mock or degraded mode, or the semantic index on disk could not be opened | Which embedder, and why |
diff --git a/packages/server/src/repowise/server/mcp_server/_meta.py b/packages/server/src/repowise/server/mcp_server/_meta.py
index 24e6656fd..9a26c5b58 100644
--- a/packages/server/src/repowise/server/mcp_server/_meta.py
+++ b/packages/server/src/repowise/server/mcp_server/_meta.py
@@ -18,7 +18,10 @@ Rules of thumb baked into the hint generators:
from __future__ import annotations
+import json
import os
+import sys
+import time
from datetime import UTC, datetime
from pathlib import Path
from typing import Any
@@ -274,6 +277,197 @@ def targets_hit_by_changes(targets: list[str], changed: frozenset[str]) -> bool:
return False
+# local_path -> (monotonic read time, dirty paths or None). Short-lived so a
+# burst of tool calls shares one ``git status`` while a fresh edit still shows;
+# a failed read is kept longer so a slow repo is not re-asked every call.
+_dirty_paths_cache: dict[str, tuple[float, frozenset[str] | None]] = {}
+_DIRTY_PATHS_TTL_S = 3.0
+_DIRTY_PATHS_FAILED_TTL_S = 60.0
+_DIRTY_PATHS_CACHE_MAX = 32
+# Runs inline on the event loop from build_meta, so the bound is tight; a slow
+# repo times out once and reads as "not evaluated" for the failed TTL.
+_DIRTY_PATHS_TIMEOUT_S = 0.5
+_UNTRACKED_DIR_FILE_CAP = 200
+
+
+def _working_tree_dirty_paths(local_path: str) -> frozenset[str] | None:
+ """Paths with staged, unstaged or untracked changes; ``None`` when unknown.
+
+ An untracked directory is reported once, with a trailing ``/``. Paths are
+ git-root relative; the ``.git`` gate below makes that root ``local_path``.
+ """
+ now = time.monotonic()
+ hit = _dirty_paths_cache.get(local_path)
+ if hit is not None:
+ ttl = _DIRTY_PATHS_TTL_S if hit[1] is not None else _DIRTY_PATHS_FAILED_TTL_S
+ if now - hit[0] < ttl:
+ return hit[1]
+ dirty: frozenset[str] | None = None
+ # Only at a repository root: ``git -C`` on a plain directory would answer
+ # for whatever repository happens to enclose it.
+ if (Path(local_path) / ".git").exists():
+ try:
+ import subprocess
+
+ res = subprocess.run(
+ [
+ "git",
+ "-C",
+ local_path,
+ "--no-pager",
+ "status",
+ "--porcelain",
+ "-z",
+ "--untracked-files=normal",
+ ],
+ capture_output=True,
+ timeout=_DIRTY_PATHS_TIMEOUT_S,
+ stdin=subprocess.DEVNULL,
+ )
+ if res.returncode == 0:
+ entries = res.stdout.decode("utf-8", errors="replace").split("\0")
+ paths: set[str] = set()
+ i = 0
+ while i < len(entries):
+ entry = entries[i]
+ i += 1
+ if len(entry) < 4:
+ continue
+ paths.add(entry[3:])
+ if entry[0] in "RC" and i < len(entries):
+ # The rename or copy source follows; it is gone or
+ # changed in the working tree too.
+ paths.add(entries[i])
+ i += 1
+ dirty = frozenset(paths)
+ except Exception:
+ dirty = None
+ if len(_dirty_paths_cache) >= _DIRTY_PATHS_CACHE_MAX:
+ _dirty_paths_cache.clear()
+ _dirty_paths_cache[local_path] = (now, dirty)
+ return dirty
+
+
+def _working_tree_record(local_path: str) -> tuple[frozenset[str], float] | None:
+ """Paths the last ``update --working-tree`` indexed, and when state.json was written."""
+ state_path = Path(local_path) / ".repowise" / "state.json"
+ try:
+ paths = json.loads(state_path.read_text(encoding="utf-8")).get("working_tree_paths")
+ written = state_path.stat().st_mtime
+ except (OSError, ValueError, AttributeError):
+ return None
+ if not isinstance(paths, list):
+ return None
+ return frozenset(_fold(p) for p in paths if isinstance(p, str)), written
+
+
+def _fold(path: str) -> str:
+ # Case-insensitive filesystems: a target and git's spelling may differ in case.
+ return path.casefold() if sys.platform in ("win32", "darwin") else path
+
+
+def _indexed_from_working_tree(
+ local_path: str, path: str, record: tuple[frozenset[str], float] | None
+) -> bool:
+ # Only paths are recorded, so the state.json write time stands in for the
+ # run's. Ceiling: a later commit-anchored update rewrites state.json and
+ # would cover a re-edit made in between; recording per-path stamps at
+ # update time lifts it.
+ if record is None:
+ return False
+ target = Path(local_path) / path
+ if path.endswith("/"):
+ # An untracked directory: its own mtime misses edits to files inside,
+ # so it is covered only when every file under it is.
+ from itertools import islice
+
+ from repowise.core.fs_walk import iter_glob
+
+ try:
+ files = [
+ f
+ for f in islice(iter_glob(target, "*"), _UNTRACKED_DIR_FILE_CAP + 1)
+ if f.is_file()
+ ]
+ except OSError:
+ return False
+ if len(files) > _UNTRACKED_DIR_FILE_CAP:
+ # Too large to check inline; stays marked rather than guessed covered.
+ return False
+ return bool(files) and all(
+ _indexed_from_working_tree(local_path, f.relative_to(local_path).as_posix(), record)
+ for f in files
+ )
+ if _fold(path) not in record[0]:
+ return False
+ # A deleted file has no mtime; its directory's changes when it goes.
+ probe = target if target.exists() else target.parent
+ try:
+ return probe.stat().st_mtime <= record[1]
+ except OSError:
+ return False
+
+
+def uncommitted_targets(local_path: str | None, targets: list[str] | None) -> list[str]:
+ """Served targets whose uncommitted edits the index has not seen.
+
+ Empty when git cannot answer: that is "not evaluated", never an error.
+ """
+ if not local_path or not targets:
+ return []
+ dirty = _working_tree_dirty_paths(local_path)
+ if not dirty:
+ return []
+ record = _working_tree_record(local_path)
+ folded = [(d, _fold(d)) for d in dirty]
+ out: list[str] = []
+ for raw in targets:
+ path = _normalize_target_path(raw)
+ if not path or path in out:
+ continue
+ key = _fold(path)
+ if any(
+ (fd == key or fd.startswith(key + "/") or (fd.endswith("/") and key.startswith(fd)))
+ and not _indexed_from_working_tree(local_path, d, record)
+ for d, fd in folded
+ ):
+ out.append(path)
+ return out
+
+
+def reverted_targets(local_path: str | None, targets: list[str] | None) -> list[str]:
+ """Served targets indexed from working-tree edits that are no longer there.
+
+ A reverted edit leaves git status clean while the index still holds it.
+ Only meaningful while HEAD equals the indexed commit; the caller checks.
+ """
+ if not local_path or not targets:
+ return []
+ record = _working_tree_record(local_path)
+ if not record or not record[0]:
+ return []
+ dirty = _working_tree_dirty_paths(local_path)
+ if dirty is None:
+ return []
+ dirty_keys = {_fold(d) for d in dirty}
+
+ def _still_dirty(rec: str) -> bool:
+ return rec in dirty_keys or any(d.endswith("/") and rec.startswith(d) for d in dirty_keys)
+
+ out: list[str] = []
+ for raw in targets:
+ path = _normalize_target_path(raw)
+ if not path or path in out:
+ continue
+ key = _fold(path)
+ if any(
+ (rec == key or rec.startswith(key + "/")) and not _still_dirty(rec)
+ for rec in record[0]
+ ):
+ out.append(path)
+ return out
+
+
def freshness_from_repo(repository: Any | None, targets: list[str] | None = None) -> dict[str, Any]:
"""Return a minimal freshness dict for the given Repository row.
@@ -315,6 +509,10 @@ def freshness_from_repo(repository: Any | None, targets: list[str] | None = None
commit), so absence means "not evaluated", never "false". Emitting the
false case matters downstream: a field that is only ever present as
``true`` makes every consumer-side rate read 100%.
+ * ``working_tree_dirty``: count of served targets with uncommitted edits
+ no ``repowise update --working-tree`` has indexed; those also set
+ ``stale_warning`` when nothing else has. A served file indexed from
+ uncommitted edits that were since reverted sets ``stale_warning`` alone.
Defensive throughout: any missing piece is dropped rather than raised so
an upstream change to the Repository model can never poison a tool result.
@@ -384,6 +582,25 @@ def freshness_from_repo(repository: Any | None, targets: list[str] | None = None
"results may be stale. Run `repowise update`."
)
+ # Freshness above is commit-anchored, so an uncommitted edit to a served
+ # file would otherwise read as current. Served targets only: a dirty tree
+ # elsewhere is no reason to warn.
+ if targets:
+ modified = uncommitted_targets(local_path, targets)
+ if modified:
+ out["working_tree_dirty"] = len(modified)
+ out.setdefault(
+ "stale_warning",
+ "A file this response serves has uncommitted edits: source reads are live, "
+ "but graph and index facts for it predate the edit. "
+ "Run `repowise update --working-tree`.",
+ )
+ elif live_full and live_full == indexed_full and reverted_targets(local_path, targets):
+ out["stale_warning"] = (
+ "A file this response serves was indexed from uncommitted edits that are "
+ "no longer in the working tree. Run `repowise update --working-tree`."
+ )
+
return out
diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/projection.py b/packages/server/src/repowise/server/mcp_server/tool_answer/projection.py
index 0a112f31f..e8190614d 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_answer/projection.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/projection.py
@@ -545,6 +545,7 @@ async def _refresh_freshness(payload: dict[str, Any], repo: str | None) -> None:
"live_head",
"index_behind",
"stale_warning",
+ "working_tree_dirty",
"scope_hint",
):
meta.pop(key, None)
diff --git a/packages/server/src/repowise/server/mcp_server/tool_context/targets.py b/packages/server/src/repowise/server/mcp_server/tool_context/targets.py
index 62c7c7a77..a61dc6077 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_context/targets.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_context/targets.py
@@ -53,6 +53,7 @@ from repowise.server.mcp_server._helpers import (
read_repo_file_text,
)
from repowise.server.mcp_server._index_state import index_state_key
+from repowise.server.mcp_server._meta import uncommitted_targets
from repowise.server.mcp_server._references import path_identity, symbol_identity
from repowise.server.mcp_server._symbol_lookup import resolve_symbol_rows, symbol_id_variants
from repowise.server.mcp_server.tool_context.enrichment import (
@@ -1231,6 +1232,10 @@ async def _resolve_one_target(
freshness["confidence_score"] = None
freshness["freshness_status"] = None
freshness["is_stale"] = None
+ if file_path_for_git and uncommitted_targets(
+ getattr(repository, "local_path", None), [file_path_for_git]
+ ):
+ freshness["working_tree"] = "modified"
result_data["freshness"] = freshness
# --- KG layer + tour context (Phase 9) ---
diff --git a/tests/unit/server/mcp/test_working_tree_freshness.py b/tests/unit/server/mcp/test_working_tree_freshness.py
new file mode 100644
index 000000000..f2d002f9f
--- /dev/null
+++ b/tests/unit/server/mcp/test_working_tree_freshness.py
@@ -0,0 +1,354 @@
+"""Served targets with uncommitted edits are marked, never called fresh.
+
+A real keyless index of a tmp git repo, then uncommitted edits: a rename of a
+function and its caller, an added function, a deleted function and a body
+edit. Every tool response about an affected target either reflects the live
+tree or carries the stale marker; a response that does neither is a silent
+wrong answer, and there must be none. ``repowise update --working-tree``
+then indexes the edits, and the marker clears.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+from pathlib import Path
+
+from click.testing import CliRunner
+
+from repowise.cli.main import cli
+from repowise.server.mcp_server import _meta, _server, _state
+from tests.unit.cli.test_update_e2e import _git, _index_full
+
+_FILES = {
+ "billing.py": "def compute_total(items):\n return sum(items)\n",
+ "checkout.py": (
+ "from billing import compute_total\n\n\n"
+ "def place_order(items):\n return compute_total(items) + 1\n"
+ ),
+ "growth.py": "def existing_metric():\n return 7\n",
+ "legacy.py": (
+ "def kept_helper():\n return 1\n\n\n"
+ "def retired_exporter():\n return 'csv'\n"
+ ),
+ "pricing.py": "def base_price():\n return 41\n",
+}
+
+_EDITS = {
+ "billing.py": "def sum_line_amounts(items):\n return sum(items)\n",
+ "checkout.py": (
+ "from billing import sum_line_amounts\n\n\n"
+ "def place_order(items):\n return sum_line_amounts(items) + 1\n"
+ ),
+ "growth.py": (
+ "def existing_metric():\n return 7\n\n\n"
+ "def weekly_signup_rate():\n return 0.5\n"
+ ),
+ "legacy.py": "def kept_helper():\n return 1\n",
+ "pricing.py": "def base_price():\n return 99173\n",
+}
+
+# (case, file, symbol an agent would ask for, tokens only the old code has,
+# tokens only the live code has)
+_CASES = [
+ ("rename", "billing.py", "sum_line_amounts", ["compute_total"], ["sum_line_amounts"]),
+ ("rename_caller", "checkout.py", "place_order", ["compute_total"], ["sum_line_amounts"]),
+ ("add", "growth.py", "weekly_signup_rate", [], ["weekly_signup_rate"]),
+ ("delete", "legacy.py", "retired_exporter", ["retired_exporter"], []),
+ ("body", "pricing.py", "base_price", ["return 41"], ["99173"]),
+]
+
+
+def _make_repo(tmp_path: Path) -> Path:
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ _git(repo, "init")
+ _git(repo, "config", "user.email", "[email protected]")
+ _git(repo, "config", "user.name", "Test")
+ for name, body in _FILES.items():
+ (repo / name).write_text(body)
+ _git(repo, "add", ".")
+ _git(repo, "commit", "-m", "initial")
+ return repo
+
+
+def _body(response: dict) -> str:
+ # The caller's own words are echoed back; they say nothing about the index.
+ return json.dumps(
+ {k: v for k, v in response.items() if k not in {"_meta", "query", "question"}},
+ default=str,
+ )
+
+
+def _marked(response: dict) -> bool:
+ return bool((response.get("_meta") or {}).get("stale_warning"))
+
+
+async def _responses(case_file: str, symbol: str) -> dict[str, dict]:
+ from repowise.server.mcp_server.tool_answer.answer import get_answer
+ from repowise.server.mcp_server.tool_context.context import get_context
+ from repowise.server.mcp_server.tool_risk.get_risk import get_risk
+ from repowise.server.mcp_server.tool_search import search_codebase
+ from repowise.server.mcp_server.tool_symbol import get_symbol
+
+ return {
+ "get_context": await get_context(targets=[case_file]),
+ "get_symbol": await get_symbol(f"{case_file}::{symbol}"),
+ "search_codebase": await search_codebase(symbol),
+ "get_answer": await get_answer(f"what does {symbol} in {case_file} do"),
+ "get_risk": await get_risk(targets=[case_file]),
+ }
+
+
+async def _serve(repo: Path) -> dict[tuple[str, str], dict]:
+ _meta._dirty_paths_cache.clear()
+ _state._repo_path = str(repo)
+ _state._force_single_repo = True
+ out: dict[tuple[str, str], dict] = {}
+ try:
+ async with _server._lifespan(_server.mcp):
+ for case, case_file, symbol, _old, _new in _CASES:
+ for tool, response in (await _responses(case_file, symbol)).items():
+ out[(case, tool)] = response
+ finally:
+ _state._repo_path = None
+ _state._force_single_repo = False
+ return out
+
+
+_TOOLS = ("get_context", "get_symbol", "search_codebase", "get_answer", "get_risk")
+
+
+def _silent_wrong(
+ responses: dict[tuple[str, str], dict], *, reverted: bool = False
+) -> list[tuple[str, str]]:
+ """Unmarked responses that serve the target or an old fact but not the live code.
+
+ A reply that names neither the file nor anything the edit removed (a
+ retrieval miss) makes no claim about the target, so it is not counted.
+ ``reverted`` swaps the sides: the edits are what is gone.
+ """
+ wrong = []
+ for case, case_file, _symbol, old, new in _CASES:
+ if reverted:
+ old, new = new, old
+ for tool in _TOOLS:
+ response = responses[(case, tool)]
+ body = _body(response)
+ stale_fact = any(t in body for t in old)
+ live = all(t in body for t in new) and not stale_fact
+ about_target = case_file in body or stale_fact
+ if about_target and not live and not _marked(response):
+ wrong.append((case, tool))
+ return wrong
+
+
+def test_uncommitted_edits_are_marked_and_cleared_by_working_tree_update(
+ tmp_path: Path, monkeypatch
+) -> None:
+ from repowise.cli.helpers import release_update_lock, save_state
+
+ monkeypatch.setenv("REPOWISE_EMBEDDER", "mock")
+ for name in ("REPOWISE_DB_URL", "REPOWISE_DATABASE_URL"):
+ monkeypatch.delenv(name, raising=False)
+ repo = _make_repo(tmp_path)
+ _index_full(repo)
+ save_state(repo, {"last_sync_commit": _git(repo, "rev-parse", "HEAD"), "docs_enabled": False})
+ for name, body in _EDITS.items():
+ (repo / name).write_text(body)
+
+ before = asyncio.run(_serve(repo))
+ assert _silent_wrong(before) == []
+ context = before[("rename", "get_context")]
+ assert context["_meta"]["working_tree_dirty"] == 1
+ assert "repowise update --working-tree" in context["_meta"]["stale_warning"]
+ card = context["targets"]["billing.py"]
+ assert card["freshness"]["working_tree"] == "modified"
+
+ result = CliRunner().invoke(cli, ["update", str(repo), "--no-workspace", "--working-tree"])
+ assert result.exit_code == 0, result.output
+
+ after = asyncio.run(_serve(repo))
+ _assert_clear(after)
+ card = after[("rename", "get_context")]["targets"]["billing.py"]
+ assert "working_tree" not in card["freshness"]
+
+ # Revert without committing: git status is clean, but the index still
+ # holds the edits, so every served target is marked until the next update.
+ _git(repo, "checkout", "--", ".")
+ reverted = asyncio.run(_serve(repo))
+ assert _silent_wrong(reverted, reverted=True) == []
+ meta = reverted[("rename", "get_context")]["_meta"]
+ assert "no longer in the working tree" in meta["stale_warning"]
+ assert "working_tree_dirty" not in meta
+
+ # The update lock is released at process exit; this run shares the process.
+ release_update_lock(repo)
+ result = CliRunner().invoke(cli, ["update", str(repo), "--no-workspace", "--working-tree"])
+ assert result.exit_code == 0, result.output
+ recorded = json.loads((repo / ".repowise" / "state.json").read_text())["working_tree_paths"]
+ assert not set(recorded) & set(_EDITS)
+ _assert_clear(asyncio.run(_serve(repo)), reverted=True)
+
+
+def _assert_clear(responses: dict[tuple[str, str], dict], *, reverted: bool = False) -> None:
+ """Covered: no marker, and nothing that is gone is served as current."""
+ for case, _file, _symbol, old, new in _CASES:
+ gone = new if reverted else old
+ for tool in _TOOLS:
+ response = responses[(case, tool)]
+ assert "working_tree_dirty" not in response["_meta"], (case, tool)
+ assert not _marked(response), (case, tool, response["_meta"])
+ # A not-found reply echoes the name it was asked for; that is the
+ # live answer for a deleted symbol, not a served fact.
+ if response.get("error") or response.get("results") == []:
+ continue
+ body = _body(response)
+ assert not any(t in body for t in gone), (case, tool, body[:1500])
+
+
+# The cases below need git only, no index: the freshness logic on its own.
+
+
+def _state_repo(tmp_path: Path):
+ import types
+
+ repo = _make_repo(tmp_path)
+ (repo / ".repowise").mkdir()
+ head = _git(repo, "rev-parse", "HEAD")
+ (repo / ".repowise" / "state.json").write_text(json.dumps({"last_sync_commit": head}))
+ row = types.SimpleNamespace(updated_at=None, local_path=str(repo), head_commit=head)
+ _meta._dirty_paths_cache.clear()
+ return repo, row
+
+
+def _record(repo: Path, paths: list[str]) -> None:
+ state_path = repo / ".repowise" / "state.json"
+ state = json.loads(state_path.read_text())
+ state["working_tree_paths"] = paths
+ state_path.write_text(json.dumps(state))
+ _meta._dirty_paths_cache.clear()
+
+
+def test_a_clean_tree_adds_nothing(tmp_path: Path) -> None:
+ _repo, row = _state_repo(tmp_path)
+ out = _meta.freshness_from_repo(row, targets=["billing.py::compute_total"])
+ assert "working_tree_dirty" not in out
+ assert "stale_warning" not in out
+ assert out["index_behind"] is False
+
+
+def test_only_served_dirty_targets_warn(tmp_path: Path) -> None:
+ repo, row = _state_repo(tmp_path)
+ (repo / "pricing.py").write_text(_EDITS["pricing.py"])
+
+ unrelated = _meta.freshness_from_repo(row, targets=["billing.py"])
+ assert "working_tree_dirty" not in unrelated
+ assert "stale_warning" not in unrelated
+ # A repo-level response never warns just because the tree is dirty.
+ assert "stale_warning" not in _meta.freshness_from_repo(row, targets=None)
+
+ served = _meta.freshness_from_repo(row, targets=["pricing.py::base_price", "billing.py"])
+ assert served["working_tree_dirty"] == 1
+ assert "repowise update --working-tree" in served["stale_warning"]
+
+
+def test_untracked_files_and_directories_count(tmp_path: Path) -> None:
+ repo, _row = _state_repo(tmp_path)
+ (repo / "fresh").mkdir()
+ (repo / "fresh" / "new.py").write_text("def brand_new():\n return 1\n")
+ (repo / "loose.py").write_text("x = 1\n")
+ assert _meta.uncommitted_targets(str(repo), ["fresh/new.py", "loose.py", "fresh"]) == [
+ "fresh/new.py",
+ "loose.py",
+ "fresh",
+ ]
+
+
+def test_a_recorded_working_tree_update_covers_until_the_next_edit(tmp_path: Path) -> None:
+ import os
+
+ repo, row = _state_repo(tmp_path)
+ (repo / "pricing.py").write_text(_EDITS["pricing.py"])
+ (repo / "legacy.py").unlink()
+ stamp = (repo / "pricing.py").stat().st_mtime
+ os.utime(repo / "pricing.py", (stamp - 10, stamp - 10))
+ os.utime(repo, (stamp - 10, stamp - 10))
+ _record(repo, ["legacy.py", "pricing.py"])
+
+ out = _meta.freshness_from_repo(row, targets=["pricing.py", "legacy.py"])
+ assert "working_tree_dirty" not in out
+ assert "stale_warning" not in out
+
+ later = (repo / ".repowise" / "state.json").stat().st_mtime + 10
+ os.utime(repo / "pricing.py", (later, later))
+ _meta._dirty_paths_cache.clear()
+ assert _meta.freshness_from_repo(row, targets=["pricing.py"])["working_tree_dirty"] == 1
+
+
+def test_git_failure_is_not_evaluated(tmp_path: Path, monkeypatch) -> None:
+ import subprocess
+
+ repo, row = _state_repo(tmp_path)
+ (repo / "pricing.py").write_text(_EDITS["pricing.py"])
+
+ def _boom(*_a, **_k):
+ raise subprocess.TimeoutExpired("git", 2)
+
+ monkeypatch.setattr(subprocess, "run", _boom)
+ out = _meta.freshness_from_repo(row, targets=["pricing.py"])
+ assert "working_tree_dirty" not in out
+ assert "stale_warning" not in out
+
+
+def test_an_untracked_directory_is_covered_only_file_by_file(tmp_path: Path) -> None:
+ import os
+
+ repo, _row = _state_repo(tmp_path)
+ (repo / "fresh").mkdir()
+ new = repo / "fresh" / "new.py"
+ new.write_text("def brand_new():\n return 1\n")
+ old = new.stat().st_mtime - 10
+ os.utime(new, (old, old))
+ os.utime(repo / "fresh", (old, old))
+
+ # The directory alone in the record covers nothing inside it.
+ _record(repo, ["fresh"])
+ assert _meta.uncommitted_targets(str(repo), ["fresh/new.py"]) == ["fresh/new.py"]
+
+ _record(repo, ["fresh/new.py"])
+ assert _meta.uncommitted_targets(str(repo), ["fresh/new.py", "fresh"]) == []
+
+ # Editing a file inside leaves the directory's own mtime alone.
+ later = (repo / ".repowise" / "state.json").stat().st_mtime + 10
+ os.utime(new, (later, later))
+ os.utime(repo / "fresh", (old, old))
+ _meta._dirty_paths_cache.clear()
+ assert _meta.uncommitted_targets(str(repo), ["fresh/new.py"]) == ["fresh/new.py"]
+
+
+def test_target_case_is_folded_where_the_filesystem_folds_it(tmp_path: Path, monkeypatch) -> None:
+ repo, _row = _state_repo(tmp_path)
+ (repo / "pricing.py").write_text(_EDITS["pricing.py"])
+ monkeypatch.setattr(_meta.sys, "platform", "win32")
+ assert _meta.uncommitted_targets(str(repo), ["Pricing.py"]) == ["Pricing.py"]
+ monkeypatch.setattr(_meta.sys, "platform", "linux")
+ assert _meta.uncommitted_targets(str(repo), ["Pricing.py"]) == []
+
+
+def test_a_reverted_working_tree_edit_is_stale_until_head_moves(tmp_path: Path) -> None:
+ repo, row = _state_repo(tmp_path)
+ _record(repo, ["pricing.py"])
+
+ out = _meta.freshness_from_repo(row, targets=["pricing.py", "billing.py"])
+ assert "no longer in the working tree" in out["stale_warning"]
+ assert "working_tree_dirty" not in out
+ assert "stale_warning" not in _meta.freshness_from_repo(row, targets=["billing.py"])
+ assert "stale_warning" not in _meta.freshness_from_repo(row, targets=None)
+
+ # Still dirty means the dirty rule applies, not this one.
+ (repo / "pricing.py").write_text(_EDITS["pricing.py"])
+ _meta._dirty_paths_cache.clear()
+ assert "uncommitted edits:" in _meta.freshness_from_repo(row, targets=["pricing.py"])[
+ "stale_warning"
+ ]