diff --git a/README.md b/README.md
index 32cedf6e..bc053135 100644
--- a/README.md
+++ b/README.md
@@ -80,6 +80,8 @@ uvx srcly report . --out .srcly --verbose
Use `uvx srcly scan . --out .srcly/tree.json` or `uvx srcly report . --include-tree` when you need the full raw tree. Use `--include-dependencies` to add the TypeScript/TSX dependency graph artifact.
+In a Git worktree, the tree, Imports and Symbols start from the same Git-listed files: tracked files stay visible even if they match an ignore rule; ignored untracked files do not. Imports and Symbols then limit the list to supported JavaScript, TypeScript and Python source up to 1 MB, excluding `.d.ts`, entries in hidden or pruned directories such as `node_modules`, and symlinks that leave the selected root. A file can appear in the tree without being eligible for these views. These filters do not define which files changed between revisions.
+
`explain --at` reads one scope of the analysis: the repo or a folder (child folders ranked by their worst file, then the worst files below), a file (its functions and classes), or `file::symbol` (its lines and every measured metric). Commands share the app's analysis cache, so after the first scan each call takes about a second while no file has changed; `--refresh` rescans. Each answer ends with an `Analysis:` line: reused or fresh scan, the Git HEAD and uncommitted files, the checkers that ran, and how many code files none covers. Same-named symbols are `file::name@line`, and any printed "Start at" value (`path:line name`) works as `--at`. A symbol answer splits its CCN into statements and `&&`/`||`/`?:` operators with the deepest lines, so a flat router reads differently from nested control flow, and lists test files that import its module and name it (a name match, not coverage).
Findings rank **code** files. Each file is also classed as test, docs, style (CSS and other stylesheets), fixture, generated, vendored, config or data from its path, and the report names how many of each it left out and why (`--include-class test` ranks one too). A long README or a test snapshot is never a refactor target by accident, and never silently dropped.
diff --git a/client/e2e/symbols.spec.ts b/client/e2e/symbols.spec.ts
index 046792e1..ae0acef4 100644
--- a/client/e2e/symbols.spec.ts
+++ b/client/e2e/symbols.spec.ts
@@ -84,6 +84,15 @@ test.describe("Symbols mode on solid-route", () => {
await page.goto(url({ view: "graph", symbols: "src/components/RecordTable.tsx#Nope" }));
await expect(page.getByText("Not in the index")).toBeVisible({ timeout: 90_000 });
});
+
+ test("explain when a tree file isn't eligible for structural views", async ({ page }) => {
+ await page.goto(url({ view: "graph", at: "README.md" }));
+ const notice = page.locator("[data-imports-excluded]");
+ await expect(notice).toContainText("README.md is in the tree but not in Imports", { timeout: 90_000 });
+ await page.goto(url({ view: "graph", symbols: "README.md" }));
+ await expect(page.getByText("Not in the index")).toBeVisible({ timeout: 90_000 });
+ await expect(page.getByText(/Symbols indexes JavaScript, TypeScript and Python source/)).toBeVisible();
+ });
});
test.describe("Symbols mode paths on solid-route", () => {
diff --git a/client/src/viz/deps/DependencyView.tsx b/client/src/viz/deps/DependencyView.tsx
index 24f1ca27..7261a989 100644
--- a/client/src/viz/deps/DependencyView.tsx
+++ b/client/src/viz/deps/DependencyView.tsx
@@ -24,7 +24,7 @@ import { layoutWithHubs } from "./hubs";
import type { ViewLayout } from "./layout";
import { viewContents, viewMetrics, type MetricsIndex } from "./metrics";
import { buildViewModel, DEFAULT_BUDGET, type ViewNode } from "./viewModel";
-import { folderOf, graphIdFor, isDataFlow, isSymbols } from "../../navigation/location";
+import { folderOf, graphIdFor, isDataFlow, isSymbols, splitAt } from "../../navigation/location";
import { addAnchorPatch, refsPatch, tracePatch } from "../../navigation/nodeActions";
import NodeActionsMenu, { type NodeMenuTarget } from "../../navigation/NodeActionsMenu";
import { go, graphFilters as filters, location, replace, setGraphFilters as setFilters } from "../../navigation/store";
@@ -88,6 +88,15 @@ function ImportView(props: {
return g ? buildIndex(applyFilters(g, filters())) : null;
});
+ const unindexedFile = createMemo(() => {
+ const nodes = graph()?.nodes;
+ const { file } = splitAt(location().at);
+ if (!nodes || !file || !props.metricsIndex) return null;
+ const separator = props.rootPath.includes("\\") ? "\\" : "/";
+ const full = `${props.rootPath.replace(/[\\/]$/, "")}${separator}${file.replaceAll("/", separator)}`;
+ return props.metricsIndex.get(full)?.type === "file" && !nodes.some((n) => n.id === file) ? file : null;
+ });
+
const effectiveFocus = createMemo(() => {
const idx = index();
if (!idx) return null;
@@ -420,6 +429,13 @@ function ImportView(props: {
+
+ {(file) => (
+
+ {file()} is in the tree but not in Imports. Imports covers JavaScript, TypeScript and Python source up to 1 MB. It excludes .d.ts files, hidden or pruned folders, and links outside this root.
+
+ )}
+
diff --git a/client/src/viz/deps/symbols/SymbolsView.tsx b/client/src/viz/deps/symbols/SymbolsView.tsx
index a9c66bdf..991c8a7e 100644
--- a/client/src/viz/deps/symbols/SymbolsView.tsx
+++ b/client/src/viz/deps/symbols/SymbolsView.tsx
@@ -406,7 +406,7 @@ export default function SymbolsView(props: { rootPath: string; onOpen: (at: stri
setPalette(true)} title="Find a symbol (/)">
diff --git a/docs/CODE_MAP.md b/docs/CODE_MAP.md
index c6afe636..959a36cf 100644
--- a/docs/CODE_MAP.md
+++ b/docs/CODE_MAP.md
@@ -55,7 +55,7 @@ Browser
| Feature | Where |
| --- | --- |
| Scan orchestration (walk, filter, analyze, build tree) | `server/app/services/analysis.py` (`scan_codebase`) |
-| File discovery (scan + landing-page estimate): `git ls-files` in repos, walk fallback | `server/app/services/analysis.py` (`discover_files`); estimate in `server/app/routers/analysis.py` (`_estimate_counts`) |
+| File discovery: Tree and the landing-page estimate share `discover_files`; Imports and Symbols share its Git candidates, then apply their structural source filters | `server/app/services/analysis.py` (`discover_files`, `git_inventory_files`); `server/app/services/deps/common.py` (`walk_source_files`); estimate in `server/app/routers/analysis.py` (`_estimate_counts`) |
| Ignore rules: built-in dirs/files/extensions, binary + minified skips | `server/app/config.py`; `analysis.py` (`classify_candidate`) |
| Ignore rules: nested `.gitignore` translation (walk fallback only) | `server/app/services/analysis.py` (`_load_gitignore_spec`, `_translate_gitignore_pattern`) |
| Worker pool: reuse, hard per-file timeouts, crash recovery | `server/app/services/scan_workers.py` (`run_file_analyses`), wrapped by `analysis.py` (`_run_file_analyses_with_hard_timeouts`) |
diff --git a/server/app/services/analysis.py b/server/app/services/analysis.py
index 9e32cb56..fd2205d0 100644
--- a/server/app/services/analysis.py
+++ b/server/app/services/analysis.py
@@ -562,22 +562,27 @@ class _GitListing:
"""Ignored entries relative to the root; wholly ignored trees end in "/"."""
-def _list_with_git(root_path: Path, cancel: CancelToken | None = None) -> _GitListing | None:
+def _list_with_git(
+ root_path: Path, cancel: CancelToken | None = None, *, include_ignored: bool = True
+) -> _GitListing | None:
"""
List ``root_path`` with ``git ls-files --cached --others --exclude-standard``.
Returns None if git cannot list the tree. Nested repositories and
submodules show up as directories and are returned in ``nested``.
"""
- with ThreadPoolExecutor(max_workers=1) as pool:
- # --directory collapses wholly ignored trees (node_modules, build output)
- # into one "dir/" entry; listing every file in them costs seconds on big
- # repos. (--no-empty-directory is avoided: some git versions then list nothing.)
- ignored_future = pool.submit(
- _git_ls_files, root_path, "--others", "--ignored", "--exclude-standard", "--directory"
- )
+ if include_ignored:
+ with ThreadPoolExecutor(max_workers=1) as pool:
+ # --directory collapses wholly ignored trees (node_modules, build output)
+ # into one "dir/" entry; listing every file in them costs seconds on big repos.
+ ignored_future = pool.submit(
+ _git_ls_files, root_path, "--others", "--ignored", "--exclude-standard", "--directory"
+ )
+ listed = _git_ls_files(root_path, "--cached", "--others", "--exclude-standard")
+ ignored = ignored_future.result()
+ else:
listed = _git_ls_files(root_path, "--cached", "--others", "--exclude-standard")
- ignored = ignored_future.result()
+ ignored = []
if listed is None:
return None
@@ -619,6 +624,27 @@ def _list_with_git(root_path: Path, cancel: CancelToken | None = None) -> _GitLi
return listing
+def git_inventory_files(root_path: Path) -> list[str] | None:
+ """The tree scan's Git candidates, before per-view analysis filters.
+
+ Tracked files stay visible even when they match an ignore rule. Structural
+ views don't need the tree's ignored counts or its binary/minified sniff.
+ None signals that callers should use their non-Git discovery fallback.
+ """
+ root_path = root_path.resolve()
+ if not _is_inside_git_work_tree(root_path):
+ return None
+ pending = [root_path]
+ files: list[str] = []
+ while pending:
+ listing = _list_with_git(pending.pop(), include_ignored=False)
+ if listing is None:
+ return None
+ files.extend(listing.files)
+ pending.extend(listing.nested)
+ return files
+
+
def _discover_with_git(
root_path: Path,
result: DiscoveryResult,
diff --git a/server/app/services/deps/common.py b/server/app/services/deps/common.py
index c41ff529..7de52320 100644
--- a/server/app/services/deps/common.py
+++ b/server/app/services/deps/common.py
@@ -11,6 +11,7 @@
from app.config import IGNORE_DIRS
MAX_SOURCE_BYTES = 1_000_000
+SourceSignature = tuple[tuple[Path, int, int], ...]
_TEST_DIRS = {"test", "tests", "__tests__", "__mocks__", "spec", "e2e"}
_TEST_FILE = re.compile(
@@ -51,8 +52,36 @@ def _gitignore_spec(root: Path):
def walk_source_files(root: Path, extensions: Set[str]) -> List[Path]:
- """Source files under root, skipping ignored, hidden and gitignored paths."""
+ """Eligible Imports/Symbols source files, with the tree's Git visibility."""
+ from app.services.analysis import git_inventory_files
+
root = root.resolve()
+ inventory = git_inventory_files(root)
+ if inventory is not None:
+ out: list[Path] = []
+ for name in inventory:
+ path = Path(name)
+ if any(part.startswith(".") for part in path.relative_to(root).parts[:-1]):
+ continue
+ source = _eligible_source(root, path, extensions)
+ if source is not None:
+ out.append(source)
+ return sorted(set(out))
+ return _walk_source_files(root, extensions)
+
+
+def _eligible_source(root: Path, path: Path, extensions: Set[str]) -> Path | None:
+ if path.name.endswith(".d.ts") or path.suffix not in extensions:
+ return None
+ try:
+ source = path.resolve()
+ return source if source.is_relative_to(root) and source.stat().st_size <= MAX_SOURCE_BYTES else None
+ except OSError:
+ return None
+
+
+def _walk_source_files(root: Path, extensions: Set[str]) -> List[Path]:
+ """Keep the existing pathspec discovery for folders without a Git listing."""
repo_root, spec = _gitignore_spec(root)
def ignored(p: Path, is_dir: bool) -> bool:
@@ -73,19 +102,25 @@ def ignored(p: Path, is_dir: bool) -> bool:
if d not in IGNORE_DIRS and not d.startswith(".") and not ignored(base / d, True)
)
for name in sorted(filenames):
- if name.endswith(".d.ts"):
- continue
p = base / name
if ignored(p, False):
continue
- if p.suffix in extensions:
- try:
- if p.stat().st_size > MAX_SOURCE_BYTES:
- continue
- except OSError:
- continue
- out.append(p.resolve())
- return out
+ source = _eligible_source(root, p, extensions)
+ if source is not None:
+ out.append(source)
+ return list(dict.fromkeys(out))
+
+
+def source_signature(files: List[Path]) -> SourceSignature:
+ """Exact source identities and file stats, independent of inventory order."""
+ stamps = []
+ for path in sorted(files):
+ try:
+ st = path.stat()
+ stamps.append((path, st.st_mtime_ns, st.st_size))
+ except OSError:
+ stamps.append((path, -1, -1))
+ return tuple(stamps)
@dataclass
diff --git a/server/app/services/deps/graph.py b/server/app/services/deps/graph.py
index c767dd8e..72e344a3 100644
--- a/server/app/services/deps/graph.py
+++ b/server/app/services/deps/graph.py
@@ -7,12 +7,12 @@
from typing import Dict, List, Optional, Tuple
from app.models import DepGraph, DepGraphEdge, DepGraphNode
-from app.services.deps.common import DepEdge, is_test_path, unique, walk_source_files
+from app.services.deps.common import DepEdge, SourceSignature, is_test_path, source_signature, unique, walk_source_files
from app.services.deps.typescript_deps import TS_EXTENSIONS, build_ts_edges
EXTERNAL_ROOT_ID = "ext:"
-_cache: Dict[Path, Tuple[Tuple[int, int], DepGraph]] = {}
+_cache: Dict[Path, Tuple[SourceSignature, DepGraph]] = {}
_lock = threading.Lock()
@@ -24,22 +24,11 @@ def _language(path: Path) -> str:
return "other"
-def _signature(files: List[Path]) -> Tuple[int, int]:
- total = 0
- for f in files:
- try:
- total ^= hash((str(f), f.stat().st_mtime_ns))
- except OSError:
- continue
- return len(files), total
-
-
-def collect_edges(root: Path) -> Tuple[List[Path], List[DepEdge], Dict[str, list]]:
- """Run every language extractor. Returns files, edges and per-file symbol defs."""
- ts_files = walk_source_files(root, TS_EXTENSIONS)
+def collect_edges(root: Path, files: List[Path]) -> Tuple[List[DepEdge], Dict[str, list]]:
+ """Run every language extractor against one inventory snapshot."""
+ ts_files = [f for f in files if f.suffix in TS_EXTENSIONS]
edges: List[DepEdge] = []
symbols: Dict[str, list] = {}
- files: List[Path] = list(ts_files)
if ts_files:
ts_edges, ts_infos = build_ts_edges(root, ts_files)
@@ -53,26 +42,26 @@ def collect_edges(root: Path) -> Tuple[List[Path], List[DepEdge], Dict[str, list
build_py_edges = None
PY_EXTENSIONS = set()
if build_py_edges is not None:
- py_files = walk_source_files(root, PY_EXTENSIONS)
+ py_files = [f for f in files if f.suffix in PY_EXTENSIONS]
if py_files:
py_edges, py_symbols, _infos, _index = build_py_edges(root, py_files)
edges.extend(py_edges)
symbols.update(py_symbols)
- files.extend(py_files)
- return files, edges, symbols
+ return edges, symbols
def build_dependency_graph(root: Path, use_cache: bool = True) -> DepGraph:
root = root.resolve()
+ files = walk_source_files(root, TS_EXTENSIONS | {".py"})
if use_cache:
- files_now = walk_source_files(root, TS_EXTENSIONS | {".py"})
- sig = _signature(files_now)
+ sig = source_signature(files)
with _lock:
hit = _cache.get(root)
if hit is not None and hit[0] == sig:
return hit[1]
- files, edges, symbols = collect_edges(root)
- graph = _assemble(root, files, edges, symbols)
+ edges, symbols = collect_edges(root, files)
+ # Keep the existing TS-first language order in the graph payload.
+ graph = _assemble(root, sorted(files, key=lambda f: f.suffix == ".py"), edges, symbols)
if use_cache:
with _lock:
_cache[root] = (sig, graph)
diff --git a/server/app/services/symbols/index.py b/server/app/services/symbols/index.py
index 7f229707..895b9071 100644
--- a/server/app/services/symbols/index.py
+++ b/server/app/services/symbols/index.py
@@ -14,7 +14,7 @@
from typing import Dict, Iterable, List, Optional, Set, Tuple
from app.models import SymbolGraph, SymbolGraphEdge, SymbolGraphNode, SymbolIndexInfo, SymbolPath, SymbolSearchHit, SymbolStats
-from app.services.deps.common import is_test_path, walk_source_files
+from app.services.deps.common import SourceSignature, is_test_path, source_signature, walk_source_files
from app.services.deps.typescript_deps import TS_EXTENSIONS
from app.services.symbols.model import BUILTIN_MEMBERS, REF_KINDS, FileSymbols, PendingMember, RefKind, Reference, Symbol
@@ -550,27 +550,17 @@ def _demote(kind: RefKind) -> RefKind:
return "write" if kind == "write" else "read"
-_cache: Dict[Path, Tuple[Tuple[int, int], SymbolIndex]] = {}
+_cache: Dict[Path, Tuple[SourceSignature, SymbolIndex]] = {}
_lock = threading.Lock()
SOURCE_EXTENSIONS = TS_EXTENSIONS | {".py"}
-def _signature(files: List[Path]) -> Tuple[int, int]:
- total = 0
- for f in files:
- try:
- total ^= hash((str(f), f.stat().st_mtime_ns))
- except OSError:
- continue
- return len(files), total
-
-
def build_symbol_index(root: Path, use_cache: bool = True) -> SymbolIndex:
root = root.resolve()
files = walk_source_files(root, SOURCE_EXTENSIONS)
- sig = _signature(files)
if use_cache:
+ sig = source_signature(files)
with _lock:
hit = _cache.get(root)
if hit is not None and hit[0] == sig:
diff --git a/server/tests/test_source_inventory.py b/server/tests/test_source_inventory.py
new file mode 100644
index 00000000..a199a59b
--- /dev/null
+++ b/server/tests/test_source_inventory.py
@@ -0,0 +1,164 @@
+"""The tree and both structural views agree on Git visibility, not eligibility."""
+
+import os
+import subprocess
+from pathlib import Path
+
+import pytest
+
+from app.models import DepGraph
+from app.services.analysis import git_inventory_files, scan_codebase
+from app.services.cache import fingerprint
+from app.services.deps.common import walk_source_files
+from app.services.deps.graph import build_dependency_graph
+from app.services.symbols.index import SymbolIndex, build_symbol_index
+
+HELPER = "src/lib/notes.ts"
+CALLEE = f"{HELPER}#toDetail"
+CALLER = "src/app.ts#showNote"
+IGNORED = "src/lib/private.ts"
+
+
+def git(root: Path, *args: str) -> None:
+ subprocess.run(["git", *args], cwd=root, check=True, capture_output=True)
+
+
+def fixture(root: Path) -> None:
+ for path, contents in {
+ ".gitignore": "lib/\n",
+ "src/app.ts": 'import { toDetail } from "./lib/notes";\nexport function showNote() { return toDetail(); }\n',
+ HELPER: "export function toDetail() { return 42; }\n",
+ IGNORED: "export function privateOnly() {}\n",
+ "src/types.d.ts": "export declare function typesOnly(): void;\n",
+ "src/page.md": "# Not a structural source file\n",
+ "src/node_modules/pkg/index.ts": "export function vendor() {}\n",
+ "src/.project/hidden.ts": "export function hidden() {}\n",
+ }.items():
+ target = root / path
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text(contents, encoding="utf-8")
+
+
+def scanned_paths(root: Path) -> set[str]:
+ tree = scan_codebase(root, verbose=False)
+ pending = [tree]
+ paths: set[str] = set()
+ while pending:
+ node = pending.pop()
+ if node.type == "file":
+ paths.add(Path(node.path).relative_to(root).as_posix())
+ elif node.type == "folder":
+ pending.extend(node.children or [])
+ return paths
+
+
+def assert_views(root: Path, *, visible: bool) -> tuple[DepGraph, SymbolIndex]:
+ tree = scanned_paths(root)
+ imports = build_dependency_graph(root)
+ symbols = build_symbol_index(root)
+ imported_files = {n.id for n in imports.nodes if n.kind == "file"}
+ assert (HELPER in tree) is visible
+ assert (HELPER in imported_files) is visible
+ assert ((CALLER, CALLEE) in {(e.source, e.target) for e in imports.edges}) is visible
+ assert [hit.id for hit in symbols.search("toDetail")] == ([CALLEE] if visible else [])
+ assert ((CALLER, "call", CALLEE) in {(r.source, r.kind, r.target) for r in symbols.references}) is visible
+ assert "src/app.ts" in tree & imported_files and CALLER in symbols.symbols
+ assert IGNORED not in tree | imported_files and not symbols.search("privateOnly")
+ for path in ("src/types.d.ts", "src/page.md", "src/.project/hidden.ts", "src/node_modules/pkg/index.ts"):
+ assert path not in imported_files and path not in symbols.symbols
+ assert {"src/types.d.ts", "src/page.md", "src/.project/hidden.ts"} <= tree
+ return imports, symbols
+
+
+def test_tracked_ignored_source_and_index_only_invalidation(tmp_path: Path) -> None:
+ git(tmp_path, "init", "-q")
+ fixture(tmp_path)
+ git(tmp_path, "add", "-f", "--", HELPER, "src/node_modules/pkg/index.ts")
+ before = fingerprint(tmp_path)
+ imports, symbols = assert_views(tmp_path, visible=True)
+ stat = (tmp_path / HELPER).stat()
+
+ # Removing the tracked entry does not touch the source file on disk.
+ git(tmp_path, "rm", "--cached", "-f", "--", HELPER)
+ assert (tmp_path / HELPER).stat().st_mtime_ns == stat.st_mtime_ns
+ ignored = fingerprint(tmp_path)
+ assert ignored != before
+ next_imports, next_symbols = assert_views(tmp_path, visible=False)
+ assert next_imports is not imports and next_symbols is not symbols
+
+ git(tmp_path, "add", "-f", "--", HELPER)
+ assert fingerprint(tmp_path) == before
+ restored_imports, restored_symbols = assert_views(tmp_path, visible=True)
+ assert restored_imports is not next_imports and restored_symbols is not next_symbols
+
+ path = tmp_path / HELPER
+ path.write_text("export function renamedDetail() { return 42; }\n", encoding="utf-8")
+ os.utime(path, ns=(stat.st_atime_ns, stat.st_mtime_ns + 1_000_000_000))
+ assert fingerprint(tmp_path) != before
+ assert not any(e.target == CALLEE for e in build_dependency_graph(tmp_path).edges)
+ assert not build_symbol_index(tmp_path).search("toDetail")
+
+
+def test_non_git_source_inventory_still_honors_gitignore(tmp_path: Path, monkeypatch) -> None:
+ # Isolate this control even if the executor's temp directory is under Git.
+ monkeypatch.setenv("GIT_CEILING_DIRECTORIES", str(tmp_path.parent))
+ fixture(tmp_path)
+ assert git_inventory_files(tmp_path) is None
+ assert_views(tmp_path, visible=False)
+
+
+def assert_cached_sources(root: Path, *paths: str) -> None:
+ imports = build_dependency_graph(root)
+ assert {n.id for n in imports.nodes if n.kind == "file"} == set(paths)
+ assert {s.file for s in build_symbol_index(root).symbols.values()} == set(paths)
+
+
+def test_cache_notices_equal_mtime_source_swap(tmp_path: Path) -> None:
+ git(tmp_path, "init", "-q")
+ (tmp_path / ".gitignore").write_text("*.ts\n", encoding="utf-8")
+ stamp = 1_700_000_000_000_000_000
+ for name in ("a", "b"):
+ source = tmp_path / f"{name}.ts"
+ source.write_text(f"export function {name}() {{}}\n", encoding="utf-8")
+ os.utime(source, ns=(stamp, stamp))
+ git(tmp_path, "add", "-f", "--", "a.ts")
+ assert_cached_sources(tmp_path, "a.ts")
+ git(tmp_path, "rm", "--cached", "-f", "--", "a.ts")
+ git(tmp_path, "add", "-f", "--", "b.ts")
+ assert (tmp_path / "a.ts").stat().st_mtime_ns == (tmp_path / "b.ts").stat().st_mtime_ns == stamp
+ assert_cached_sources(tmp_path, "b.ts")
+
+
+@pytest.mark.skipif(os.name == "nt", reason="requires Git worktree symlinks")
+def test_structural_sources_do_not_follow_symlink_outside_root(tmp_path: Path) -> None:
+ root = tmp_path / "repo"
+ root.mkdir()
+ git(root, "init", "-q")
+ (root / ".gitignore").write_text("lib/\n", encoding="utf-8")
+ outside = tmp_path / "outside.ts"
+ outside.write_text("export function outside() {}\n", encoding="utf-8")
+ (root / "lib").mkdir()
+ (root / "lib/external.ts").symlink_to(outside)
+ git(root, "add", "-f", "--", "lib/external.ts")
+ assert outside not in walk_source_files(root, {".ts"})
+ assert_cached_sources(root)
+
+
+@pytest.mark.skipif(os.name == "nt", reason="requires Git worktree symlinks")
+def test_in_root_symlinks_do_not_alias_cache_keys(tmp_path: Path) -> None:
+ root = tmp_path
+ git(root, "init", "-q")
+ (root / ".gitignore").write_text("alias*.ts\n", encoding="utf-8")
+ # In-root links keep pointing at the resolved source. Two aliases for each
+ # target used to cancel out in each graph's XOR cache signature.
+ sources = root / ".sources"
+ sources.mkdir()
+ for name in ("a", "b"):
+ (sources / f"{name}.ts").write_text(f"export function {name}() {{}}\n", encoding="utf-8")
+ for number in (1, 2):
+ (root / f"alias-{name}{number}.ts").symlink_to(f".sources/{name}.ts")
+ git(root, "add", "-f", "--", "alias-a1.ts", "alias-a2.ts")
+ assert_cached_sources(root, ".sources/a.ts")
+ git(root, "rm", "--cached", "-f", "--", "alias-a1.ts", "alias-a2.ts")
+ git(root, "add", "-f", "--", "alias-b1.ts", "alias-b2.ts")
+ assert_cached_sources(root, ".sources/b.ts")