From 60913d2764918b7c015eedce6dfca0002af5bbee Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Sat, 28 Nov 2026 20:55:21 -0800 Subject: [PATCH 1/3] refactor(repos): one link-text helper, and link-walk helpers public overlay_paths and links each had a _link_target with the same name and different guards: links strips the \\?\ long-path prefix on Windows only, overlay_paths on every OS. A POSIX symlink to \\?\x therefore named the file x for the overlay arm and the held-guidance accounting, and the file \\?\x for the walk. Keep the links one, now public as link_text() and guarded by os.name; overlay_paths and held_guidance call it. Promote the helpers that cross modules to public names in their owning module: links.walk_links, names_dir, require_dir, LinkLoop; overlay_paths.overlay_targets, path_hits, supplies_a_file; manifest.is_within. The workspace re-exports of the overlay helpers go with the rename. Behaviour changes only for a POSIX link whose text starts with \\?\ (now read as written, the file an agent in the workspace reaches); see the changelog fragment. Test-narrowed: the two overlay tests that read a Windows link text by patching os.readlink (the long-path prefix and the UNC share) are removed; the same helper is now pinned at the links level by test_a_windows_extended_prefix_is_dropped_from_a_link_text and test_an_extended_unc_link_text_is_the_share. Signed-off-by: Nikolay Petrov --- .../20261128_100000_link-text-posix-prefix.md | 3 ++ dokimi/dokimi/repos/export_skips.py | 4 +-- dokimi/dokimi/repos/guidance_history.py | 4 +-- dokimi/dokimi/repos/held_guidance.py | 9 +++--- dokimi/dokimi/repos/links.py | 27 +++++++++-------- dokimi/dokimi/repos/manifest.py | 10 +++---- dokimi/dokimi/repos/overlay_paths.py | 19 ++++-------- dokimi/dokimi/repos/source.py | 14 ++++----- dokimi/dokimi/repos/workspace.py | 24 +++++++-------- dokimi/tests/test_repo_overlay.py | 30 +++++++------------ dokimi/tests/test_repo_source_links.py | 21 +++++++++++-- 11 files changed, 83 insertions(+), 82 deletions(-) create mode 100644 dokimi/changelog.d/20261128_100000_link-text-posix-prefix.md diff --git a/dokimi/changelog.d/20261128_100000_link-text-posix-prefix.md b/dokimi/changelog.d/20261128_100000_link-text-posix-prefix.md new file mode 100644 index 0000000000..7c13267406 --- /dev/null +++ b/dokimi/changelog.d/20261128_100000_link-text-posix-prefix.md @@ -0,0 +1,3 @@ +### Fixed + +- **A POSIX symlink whose target starts with `\\?\` is read as written by the guidance overlay arm and the held-guidance accounting** — the guidance overlay arm and the held-guidance accounting stripped the Windows long-path prefix on every OS, so `AGENTS.claude.md -> \\?\x` on Linux named the file `x` and could remove an overlay `x`, while the repository link walk read the same text as written. Both now read the link text through the walk's one helper, which strips the prefix only on Windows; Windows behaviour is unchanged. diff --git a/dokimi/dokimi/repos/export_skips.py b/dokimi/dokimi/repos/export_skips.py index 86c2d0aefa..cae89156a9 100644 --- a/dokimi/dokimi/repos/export_skips.py +++ b/dokimi/dokimi/repos/export_skips.py @@ -9,14 +9,14 @@ from pathlib import Path from .errors import PrepError -from .manifest import _is_within +from .manifest import is_within from .source import RepoTree def refuse_skipped(tree: RepoTree, only: str | None, exclude: str | None, tmp: Path) -> None: """Remove ``tmp`` and raise when a skipped path is inside ``only`` (or a directory above it), not in ``exclude``.""" skipped = [w for p, w in zip(getattr(tree, "skipped_paths", ()), getattr(tree, "skipped", ()), strict=True) - if (not only or _is_within(p, only) or _is_within(only, p)) and not (exclude and _is_within(p, exclude))] + if (not only or is_within(p, only) or is_within(only, p)) and not (exclude and is_within(p, exclude))] if skipped: shutil.rmtree(tmp, ignore_errors=True) raise PrepError(f"{tree.label} has paths that cannot be looked at: " + "; ".join(skipped)) diff --git a/dokimi/dokimi/repos/guidance_history.py b/dokimi/dokimi/repos/guidance_history.py index 6305dcb0ad..e3d3d2d200 100644 --- a/dokimi/dokimi/repos/guidance_history.py +++ b/dokimi/dokimi/repos/guidance_history.py @@ -56,7 +56,7 @@ from .budget import imported_by from .errors import PrepError from .harness_profile import PROFILE_DIR, HarnessProfile, load_profile -from .manifest import _is_within, match_glob +from .manifest import is_within, match_glob from .source import SourceError, WorkTree, is_shallow, isolated_git_env #: At most this many commits in ``guidance_commits``; ``guidance_latest`` is not capped @@ -163,7 +163,7 @@ def _counts_for(path: str, globs: tuple[str, ...], eval_dir: str, linked: dict[s """The guidance paths a change to ``path`` counts for: itself when a glob matches it outside ``eval_dir`` (as :func:`~.workspace._guidance_at` lists them), and each link through it (no chain reaches into ``eval_dir``: :func:`~.workspace._link_chain` refuses one).""" - own = not _is_within(path, eval_dir) and any(match_glob(g, path) for g in globs) + own = not is_within(path, eval_dir) and any(match_glob(g, path) for g in globs) return ([path] if own else []) + linked.get(path, []) diff --git a/dokimi/dokimi/repos/held_guidance.py b/dokimi/dokimi/repos/held_guidance.py index 25953247d6..ec2a6370fa 100644 --- a/dokimi/dokimi/repos/held_guidance.py +++ b/dokimi/dokimi/repos/held_guidance.py @@ -12,8 +12,9 @@ from pathlib import Path from .container import WORKSPACE +from .links import link_text from .manifest import RepoManifest, match_glob -from .overlay_paths import _link_target, _supplies_a_file +from .overlay_paths import supplies_a_file from .workspace import SNAPSHOT_AUTHOR, _git_env, _workspace_files @@ -53,7 +54,7 @@ def unlistable(error: OSError) -> None: for name in (*dirs, *names): path = os.path.join(here, name) if stat.S_ISLNK(os.lstat(path).st_mode): # os.path.islink reads a failed lstat as no link - links[os.path.normcase(path)] = str(_link_target(Path(path))) + links[os.path.normcase(path)] = str(Path(link_text(Path(path)))) elif name in dirs: dirs_here.add(os.path.normcase(path)) return links, frozenset(dirs_here) @@ -100,8 +101,8 @@ def __contains__(self, path: object) -> bool: def held_guidance(run_dir: Path, manifest: RepoManifest) -> HeldGuidance: """The guidance files (``guidance.globs``) ``run_dir/workspace`` holds, as the agent starts: a dangling, cyclic or - directory link (:func:`~dokimi.repos.overlay_paths._supplies_a_file`) supplies no file and is not one.""" + directory link (:func:`~dokimi.repos.overlay_paths.supplies_a_file`) supplies no file and is not one.""" ws = run_dir / "workspace" held = [p for p in _workspace_files(ws, _git_env(SNAPSHOT_AUTHOR)) - if any(match_glob(g, p) for g in manifest.guidance_globs) and _supplies_a_file(ws, p)] + if any(match_glob(g, p) for g in manifest.guidance_globs) and supplies_a_file(ws, p)] return HeldGuidance(ws, held) diff --git a/dokimi/dokimi/repos/links.py b/dokimi/dokimi/repos/links.py index d47300bfef..b8f21b8f4d 100644 --- a/dokimi/dokimi/repos/links.py +++ b/dokimi/dokimi/repos/links.py @@ -15,7 +15,7 @@ _JUNCTION_TAG = 0xA0000003 # IO_REPARSE_TAG_MOUNT_POINT; the stat module has it only on Windows -class _LinkLoop(SourceArgumentError): +class LinkLoop(SourceArgumentError): """More than 40 links followed on one path: no file, as in a checkout (ELOOP).""" @@ -34,8 +34,9 @@ def _is_link(path: Path) -> bool: return stat.S_ISLNK(st.st_mode) or getattr(st, "st_reparse_tag", 0) == _JUNCTION_TAG -def _link_target(path: Path) -> str: - """The link's text; on Windows without the ``\\\\?\\`` prefix, and ``\\\\?\\UNC\\server`` as the share ``\\\\server``.""" +def link_text(path: Path) -> str: + """The text of a symbolic link, as the walk reads it. On Windows the ``\\\\?\\`` long-path prefix is dropped, and + ``\\\\?\\UNC\\server`` is the share ``\\\\server``. On POSIX the text is as written: there ``\\\\?\\x`` is a file name, not a prefix.""" text = os.readlink(path) if os.name == "nt" and text.startswith("\\\\?\\UNC\\"): return "\\\\" + text[8:] @@ -62,7 +63,7 @@ def _start(text: str, here: Path) -> tuple[Path, list[str]]: def _inside(root: Path, text: str) -> str: """The rooted ``text`` as a path relative to ``root``, kept as text so that a link farther along the chain is still walked: by its own words when it lies under ``root``, else walked outside one link at a time (a checkout - alias) up to the first name under ``root``, with the rest of the text left to :func:`_walk_links`.""" + alias) up to the first name under ``root``, with the rest of the text left to :func:`walk_links`.""" lexical = Path(text) # not normalised: a ``..`` after a link goes up from the link's target slash = "/" if _dir_text(text) else "" # ``Path`` drops it; it still means a directory (#1272) if lexical.is_relative_to(root): @@ -80,27 +81,27 @@ def _inside(root: Path, text: str) -> str: continue hops += 1 if hops > 40: - raise _LinkLoop(f"too many levels of symbolic links: {text}") - link = _link_target(here) + raise LinkLoop(f"too many levels of symbolic links: {text}") + link = link_text(here) slash = "/" if slash or (not pending and _dir_text(link)) else "" here, more = _start(link, here.parent) pending = more + pending raise SourceArgumentError(f"path escapes the repository: {text}") -def _names_dir(seen: bool, text: str, rest: list[str]) -> bool: +def names_dir(seen: bool, text: str, rest: list[str]) -> bool: """Whether a path ends in a link whose text ends in ``/`` or ``/.``: it names a directory, as in a checkout (#1272).""" return seen or (_dir_text(text) and all(piece in ("", ".") for piece in rest)) -def _require_dir(need_dir: bool, is_dir: Callable[[], bool], path: str, walked: list[str]) -> None: +def require_dir(need_dir: bool, is_dir: Callable[[], bool], path: str, walked: list[str]) -> None: """:class:`_NoSuchPath` when the path ended in a ``/`` link text and what it reached is not a directory (ENOTDIR).""" if need_dir and walked and not is_dir(): # #1272: ``cat nul.md`` fails with "Not a directory" for ``nul.md -> real.md/`` raise _NoSuchPath(f"{path} links to a file, not a directory: {'/'.join(walked)}") -def _walk_links(root: Path, path: str) -> Path: +def walk_links(root: Path, path: str) -> Path: """``path`` walked one component at a time, as a checkout does: a ``..`` after a link goes up from the link's target. :class:`SourceArgumentError` if a ``..`` has nothing left to go up from, an absolute text lands outside ``root``, or more than 40 links are followed.""" @@ -127,14 +128,14 @@ def _walk_links(root: Path, path: str) -> Path: continue hops += 1 if hops > 40: - raise _LinkLoop(f"too many levels of symbolic links: {path}") - text = _link_target(here) + raise LinkLoop(f"too many levels of symbolic links: {path}") + text = link_text(here) if _rooted(text): text = _inside(root, text) walked = [] else: walked.pop() - need_dir = _names_dir(need_dir, text, pending) + need_dir = names_dir(need_dir, text, pending) pending = _parts(text) + pending - _require_dir(need_dir, lambda: root.joinpath(*walked).is_dir(), path, walked) + require_dir(need_dir, lambda: root.joinpath(*walked).is_dir(), path, walked) return root.joinpath(*walked) diff --git a/dokimi/dokimi/repos/manifest.py b/dokimi/dokimi/repos/manifest.py index c8c30265e4..ffcf6adfe3 100644 --- a/dokimi/dokimi/repos/manifest.py +++ b/dokimi/dokimi/repos/manifest.py @@ -157,7 +157,7 @@ def run_paths(self) -> tuple[str, str]: return self.eval_dir, self.tasks def in_eval_dir(self, path: str) -> bool: - return self.eval_dir is not None and _is_within(path, self.eval_dir) + return self.eval_dir is not None and is_within(path, self.eval_dir) def to_dict(self) -> dict[str, Any]: return { @@ -426,7 +426,7 @@ def _check_eval_paths(tree: RepoTree, manifest: RepoManifest, report: RepoCheckR return if not tree.is_dir(eval_dir): report.errors.append(f"eval_dir does not exist: {eval_dir}") - elif not _is_within(manifest.path, eval_dir): + elif not is_within(manifest.path, eval_dir): report.warnings.append( f"manifest {manifest.path} is outside eval_dir {eval_dir}, " "so it stays visible to the agent" @@ -435,7 +435,7 @@ def _check_eval_paths(tree: RepoTree, manifest: RepoManifest, report: RepoCheckR report.errors.append(f"image/dockerfile does not exist: {manifest.image.dockerfile}") if manifest.explore_tasks and not tree.is_dir(manifest.explore_tasks): report.errors.append(f"explore_tasks does not exist: {manifest.explore_tasks}") - elif manifest.explore_tasks and not _is_within(manifest.explore_tasks, eval_dir): + elif manifest.explore_tasks and not is_within(manifest.explore_tasks, eval_dir): report.errors.append( f"explore_tasks {manifest.explore_tasks} is outside eval_dir {eval_dir}; " "its reference answers would be visible to the agent" @@ -464,7 +464,7 @@ def _check_guidance(tree: RepoTree, manifest: RepoManifest, report: RepoCheckRep def _check_tasks(tree: RepoTree, manifest: RepoManifest, files: list[str], report: RepoCheckReport) -> None: eval_dir, tasks = manifest.run_paths() - if not _is_within(tasks, eval_dir): + if not is_within(tasks, eval_dir): report.errors.append( f"tasks {manifest.tasks} is outside eval_dir {manifest.eval_dir}; " "task content would be visible to the agent" @@ -723,5 +723,5 @@ def _norm(path: str) -> str: return PurePosixPath(path).as_posix().removeprefix("./").rstrip("/") or "." -def _is_within(path: str, directory: str) -> bool: +def is_within(path: str, directory: str) -> bool: return directory == "." or path == directory or path.startswith(directory.rstrip("/") + "/") diff --git a/dokimi/dokimi/repos/overlay_paths.py b/dokimi/dokimi/repos/overlay_paths.py index 4389f185fe..b2d6652db5 100644 --- a/dokimi/dokimi/repos/overlay_paths.py +++ b/dokimi/dokimi/repos/overlay_paths.py @@ -14,6 +14,7 @@ from pathlib import Path from .errors import PrepError +from .links import link_text def _canon(path: Path) -> Path: @@ -24,17 +25,7 @@ def _canon(path: Path) -> Path: _MAX_HOPS = 64 # symbolic links followed by one walk; a cycle runs out -def _link_target(link: Path) -> Path: - """The target of a symbolic link as a path. On Windows ``os.readlink`` gives an absolute target with the ``\\\\?\\`` - long-path prefix, which the canonical paths of the workspace do not carry, so the prefix is dropped; a UNC share - keeps its server name as ``\\\\server\\share`` (``\\\\?\\UNC\\server\\share`` is that share, not a relative path).""" - target = os.readlink(link) - if target.startswith("\\\\?\\UNC\\"): - return Path("\\\\" + target[len("\\\\?\\UNC\\"):]) - return Path(target[len("\\\\?\\"):] if target.startswith("\\\\?\\") else target) - - -def _path_hits(ws: Path, rel: str, gone: set[Path]) -> bool: +def path_hits(ws: Path, rel: str, gone: set[Path]) -> bool: """Whether the workspace path ``rel`` runs through one of the canonical paths ``gone``, a link or a plain name. Walked from the workspace root: each name is checked before it is resolved, so a removed directory link named in the middle of the path is a hit (the path would not exist once it is removed); a link is followed hop by hop, @@ -58,7 +49,7 @@ def _path_hits(ws: Path, rel: str, gone: set[Path]) -> bool: hops += 1 if hops > _MAX_HOPS: return False - target = _link_target(cand) # the native separators: a Windows target splits on backslashes + target = Path(link_text(cand)) # the native separators: a Windows target splits on backslashes if target.is_absolute(): resolved, parts = Path(target.anchor), target.parts[1:] else: @@ -67,7 +58,7 @@ def _path_hits(ws: Path, rel: str, gone: set[Path]) -> bool: return False -def _overlay_targets(ws: Path, listed: list[str], arm: str = "guidance:overlay") -> dict[Path, str]: +def overlay_targets(ws: Path, listed: list[str], arm: str = "guidance:overlay") -> dict[Path, str]: """The overlays of other agents to remove, by canonical path (the directories resolved, so a name under a link is the file it reaches), one name per file: a directory the index lists that a setup patch made a link to another directory names the same file twice, and the first name in order stands for it.""" @@ -79,7 +70,7 @@ def _overlay_targets(ws: Path, listed: list[str], arm: str = "guidance:overlay") return names -def _supplies_a_file(ws: Path, rel: str) -> bool: +def supplies_a_file(ws: Path, rel: str) -> bool: """Whether the workspace path ``rel`` resolves to a regular file inside the workspace.""" real = Path(os.path.realpath(ws / rel)) return real.is_file() and real.is_relative_to(ws.resolve()) diff --git a/dokimi/dokimi/repos/source.py b/dokimi/dokimi/repos/source.py index a50f46cb38..8025944d60 100644 --- a/dokimi/dokimi/repos/source.py +++ b/dokimi/dokimi/repos/source.py @@ -28,7 +28,7 @@ from typing import Callable, Protocol from dokimi import process -from dokimi.repos.links import _LinkLoop, _names_dir, _require_dir, _walk_links +from dokimi.repos.links import LinkLoop, names_dir, require_dir, walk_links from dokimi.repos.source_errors import SourceArgumentError, SourceError, _NoSuchPath from dokimi.utils import key_bytes @@ -132,8 +132,8 @@ def _resolve(self, path: str) -> Path: goes above the root escapes even if it comes back in by the root's own name; an absolute one is followed where it lands inside the root.""" try: - return _walk_links(self.root, path) - except _LinkLoop: + return walk_links(self.root, path) + except LinkLoop: (self.root / path).resolve() # Python before 3.13 raises RuntimeError on a loop, as callers expect raise @@ -187,13 +187,13 @@ def files(self) -> list[str]: def is_file(self, path: str) -> bool: try: return self._resolve(path).is_file() - except (_LinkLoop, _NoSuchPath): + except (LinkLoop, _NoSuchPath): return False def is_dir(self, path: str) -> bool: try: return self._resolve(path).is_dir() - except (_LinkLoop, _NoSuchPath): + except (LinkLoop, _NoSuchPath): return False def _readable(self, path: str) -> Path: @@ -353,7 +353,7 @@ def _follow(self, path: str, follow_last: bool = True) -> str: if here not in links or (not pending and not follow_last): continue text = self._link_text(here) - need_dir = _names_dir(need_dir, text, [piece for piece, _ in pending]) + need_dir = names_dir(need_dir, text, [piece for piece, _ in pending]) if posixpath.isabs(text): raise SourceArgumentError(f"path escapes the repository: {here} -> {text}") hops += 1 @@ -361,7 +361,7 @@ def _follow(self, path: str, follow_last: bool = True) -> str: raise SourceArgumentError(f"too many levels of symbolic links: {path}") walked.pop() pending = [(piece, f"{here} -> {text}") for piece in text.split("/")] + pending - _require_dir(need_dir, lambda: "/".join(walked) in self._dir_set(), path, walked) + require_dir(need_dir, lambda: "/".join(walked) in self._dir_set(), path, walked) return "/".join(walked) or "." def resolve(self, path: str, dirs: bool = False) -> str: diff --git a/dokimi/dokimi/repos/workspace.py b/dokimi/dokimi/repos/workspace.py index 479f3571b1..01146748b1 100644 --- a/dokimi/dokimi/repos/workspace.py +++ b/dokimi/dokimi/repos/workspace.py @@ -59,8 +59,8 @@ from .guidance_format import FORMATS from .guidance_history import arm_rev_history, record_imports from .harness_profile import HarnessProfile -from .manifest import RepoManifest, _is_within, match_glob -from .overlay_paths import _link_target, _overlay_targets, _path_hits, _supplies_a_file # noqa: F401 +from .manifest import RepoManifest, is_within, match_glob +from .overlay_paths import overlay_targets, path_hits, supplies_a_file from .overlays import overlay_names, overlay_of from .skill_dirs import only_empty_dirs from .source import (GitTree, RepoSource, RepoTree, SourceError, cache_path, clone_once, default_cache_dir, @@ -327,7 +327,7 @@ def _export(tree: RepoTree, dest: Path, only: str | None, exclude: str | None) - files = tree.files() # fills ``tree.skipped`` refuse_skipped(tree, only, exclude, tmp) # a workspace that silently lacks files would run an agent on a partial repo for rel in files: - if only and not _is_within(rel, only): + if only and not is_within(rel, only): continue target = tmp / rel target.parent.mkdir(parents=True, exist_ok=True) @@ -499,8 +499,8 @@ def _apply_arm(ws: Path, env: dict[str, str], git_dir: Path, manifest: RepoManif def _dropped_overlays(ws: Path, env: dict[str, str], matched: list[str], arm: str) -> dict[Path, str]: """The overlays the globs miss (a setup patch's too), by canonical path; refused before any unlink.""" - return _overlay_targets(ws, [p for p in _workspace_files(ws, env) - if overlay_of(p) is not None and p not in matched], arm) + return overlay_targets(ws, [p for p in _workspace_files(ws, env) + if overlay_of(p) is not None and p not in matched], arm) def _apply_removal(ws: Path, env: dict[str, str], git_dir: Path, manifest: RepoManifest, arm: Arm, @@ -595,7 +595,7 @@ def _kept_overlays(ws: Path, tracked: list[str], own: str) -> list[str]: if not kept: raise PrepError(f"guidance:overlay: the base has no AGENTS.{own}.md to keep") for rel in kept: # the arm keeps it, so it must supply a file: a dangling, cyclic or directory link does not - if not _supplies_a_file(ws, rel): + if not supplies_a_file(ws, rel): raise PrepError(f"guidance:overlay: {rel} does not resolve to a usable file in the workspace") return kept @@ -603,14 +603,14 @@ def _kept_overlays(ws: Path, tracked: list[str], own: str) -> list[str]: def _refuse_dangling(ws: Path, tracked: list[str], listed: set[str], gone: set[Path]) -> None: """Refuse a path of the base that runs through an overlay the arm removes: the base would dangle.""" for rel in tracked: - if rel not in listed and _path_hits(ws, rel, gone): + if rel not in listed and path_hits(ws, rel, gone): raise PrepError(f"guidance:overlay: {rel} resolves through an overlay the arm removes; " "the base would dangle") def _check_removable(ws: Path, targets: dict[Path, str]) -> None: """Refuse a removal that leaves the base without a file, or that would remove a directory.""" - if not _supplies_a_file(ws, "AGENTS.md"): # the base is kept too, so it must supply a file as well + if not supplies_a_file(ws, "AGENTS.md"): # the base is kept too, so it must supply a file as well raise PrepError("guidance:overlay: AGENTS.md does not resolve to a usable file in the workspace") for canon, rel in targets.items(): # all checks before the first unlink: a refusal leaves the workspace as it was if canon.is_dir() and not canon.is_symlink(): @@ -622,7 +622,7 @@ def _apply_overlay(ws: Path, tracked: list[str], own: str) -> tuple[list[str], d either (the arm's cell would be the base alone, or an overlay with no base to sit beside).""" kept = _kept_overlays(ws, tracked, own) listed = [p for p in tracked if overlay_of(p) not in (None, own)] - targets = _overlay_targets(ws, listed) + targets = overlay_targets(ws, listed) if targets: # the walk is only needed when some overlay is removed _refuse_dangling(ws, tracked, set(listed), set(targets)) _check_removable(ws, targets) @@ -647,7 +647,7 @@ def _guidance_at(git_dir: Path, manifest: RepoManifest, # a name Windows cannot decode would take the key of the real file its replacement characters spell if kind == "blob" and (path := exact_path_text(raw_path)) is not None: entries[path] = (mode, oid) - found = sorted(p for p in entries if not _is_within(p, eval_dir) + found = sorted(p for p in entries if not is_within(p, eval_dir) and any(match_glob(g, p) for g in manifest.guidance_globs)) links, chains = {}, {} for path in found: @@ -672,7 +672,7 @@ def _link_chain(git_dir: Path, entries: dict[str, tuple[str, str]], path: str, s target = posixpath.normpath(posixpath.join(posixpath.dirname(target), dest)) if dest.startswith("/") or target == ".." or target.startswith("../"): raise PrepError(f"guidance {path} at {sha[:12]} links out of the tree ({dest})") - if _is_within(target, eval_dir): + if is_within(target, eval_dir): raise PrepError(f"guidance {path} at {sha[:12]} links into eval_dir {eval_dir}") chain.append(target) # the final entry is a file: still a link after the loop is a cycle, no entry a dangling link @@ -699,7 +699,7 @@ def _apply_patch(ws: Path, env: dict[str, str], manifest: RepoManifest, arm: Arm changed = sorted(p for p in status[1::2] if p) eval_dir = manifest.run_paths()[0] # the patch's own paths too: a file .gitignore hides is written but never staged - inside = sorted(p for p in set(changed) | touched if _is_within(p, eval_dir)) + inside = sorted(p for p in set(changed) | touched if is_within(p, eval_dir)) if inside: # the agent must not see an eval_dir, not even a patched-in one raise PrepError(f"arm {arm}: patch {arm.patch_path} writes into eval_dir {eval_dir}: {', '.join(inside)}") # a written file .gitignore hides is in the workspace, not in start_sha: still a file the arm wrote diff --git a/dokimi/tests/test_repo_overlay.py b/dokimi/tests/test_repo_overlay.py index 3b422c8916..f9270b31eb 100644 --- a/dokimi/tests/test_repo_overlay.py +++ b/dokimi/tests/test_repo_overlay.py @@ -19,6 +19,7 @@ from dokimi.repos import RepoSource, load_manifest, open_source from dokimi.repos.guidance_format import to_format from dokimi.repos.harness_profile import PROFILE_DIR, ProfileError, load_profile, parse_profile +from dokimi.repos.overlay_paths import path_hits from dokimi.repos.overlays import native_names, overlay_of from dokimi.repos.reach import format_matrix, native_in_probe, overlay_report, probe_files from dokimi.repos.workspace import ( @@ -29,8 +30,6 @@ _apply_arm, _apply_overlay, _git_env, - _link_target, - _path_hits, export_eval_dir, load_tasks, parse_arm, @@ -259,23 +258,21 @@ def test_overlay_arm_keeps_a_base_link_whose_target_a_removed_link_also_names(tm assert (tmp_path / "AGENTS.md").read_text(encoding="utf-8") == "shared\n" -def test_a_link_target_with_the_windows_long_path_prefix_is_read_without_it(tmp_path, monkeypatch): - (tmp_path / "docs").mkdir() - target = Path(os.path.realpath(tmp_path / "docs" / "shared.md")) - target.write_text("shared\n", encoding="utf-8") - (tmp_path / "AGENTS.claude.md").symlink_to(Path("docs", "shared.md")) - real_readlink = os.readlink - # os.readlink on Windows gives the absolute target with the \\?\ long-path prefix - monkeypatch.setattr(os, "readlink", lambda p: "\\\\?\\" + str(target) if Path(p).name == "AGENTS.claude.md" - else real_readlink(p)) - assert _path_hits(tmp_path, "AGENTS.claude.md", {target}) is True +@pytest.mark.skipif(os.name == "nt", reason="on Windows the prefix is stripped; this pins the POSIX file name") +def test_a_posix_link_text_that_starts_with_the_long_path_prefix_names_that_file(tmp_path): + """On POSIX ``\\\\?\\x`` is a file name, not the Windows long-path prefix: the link reaches the file of that name, + and an overlay that removed ``x`` does not hit it (the prefix was stripped on every OS, so it did).""" + (tmp_path / "x").write_text("x\n", encoding="utf-8") + (tmp_path / "AGENTS.claude.md").symlink_to("\\\\?\\x") + gone = {Path(os.path.realpath(tmp_path)) / "x"} + assert path_hits(tmp_path, "AGENTS.claude.md", gone) is False def test_the_path_walk_runs_only_when_an_overlay_is_removed(tmp_path, monkeypatch): for name in ("AGENTS.md", "AGENTS.claude.md"): (tmp_path / name).write_text("x\n", encoding="utf-8") walked = [] - monkeypatch.setattr("dokimi.repos.workspace._path_hits", lambda *args: walked.append(args) or False) + monkeypatch.setattr("dokimi.repos.workspace.path_hits", lambda *args: walked.append(args) or False) _apply_overlay(tmp_path, ["AGENTS.md", "AGENTS.claude.md"], "claude") assert walked == [] # no other agent's overlay to remove: nothing can dangle (tmp_path / "AGENTS.codex.md").write_text("x\n", encoding="utf-8") @@ -283,13 +280,6 @@ def test_the_path_walk_runs_only_when_an_overlay_is_removed(tmp_path, monkeypatc assert walked and not (tmp_path / "AGENTS.codex.md").exists() -def test_a_link_target_on_a_windows_unc_share_keeps_the_server_name(tmp_path, monkeypatch): - """\\\\?\\UNC\\server\\share\\x is the share \\\\server\\share\\x; without the UNC rule it is the relative UNC\\server.""" - link = tmp_path / "AGENTS.codex.md" - monkeypatch.setattr(os, "readlink", lambda p: "\\\\?\\UNC\\server\\share\\ws\\AGENTS.codex.md") - assert str(_link_target(link)) == "\\\\server\\share\\ws\\AGENTS.codex.md" - - @pytest.mark.skipif(os.name != "nt", reason="a backslash in a link target separates names on Windows only") def test_overlay_arm_refuses_a_backslash_base_link_through_a_removed_directory_link(tmp_path): (tmp_path / "docs").mkdir() diff --git a/dokimi/tests/test_repo_source_links.py b/dokimi/tests/test_repo_source_links.py index 8c7899943b..43d8d5a6e8 100644 --- a/dokimi/tests/test_repo_source_links.py +++ b/dokimi/tests/test_repo_source_links.py @@ -216,10 +216,25 @@ def test_an_extended_unc_link_text_is_the_share(monkeypatch): with monkeypatch.context() as m: m.setattr(os, "readlink", lambda p: "\\\\?\\UNC\\server\\share\\repo\\real.yaml") m.setattr(os, "name", "nt") - text = links._link_target(link) + text = links.link_text(link) assert text == "\\\\server\\share\\repo\\real.yaml" +def test_a_windows_extended_prefix_is_dropped_from_a_link_text(monkeypatch): + link = Path("link") # made before ``os.name`` changes: Python 3.11 cannot build a WindowsPath on POSIX + with monkeypatch.context() as m: + m.setattr(os, "readlink", lambda p: "\\\\?\\repo\\real.yaml") + m.setattr(os, "name", "nt") + assert links.link_text(link) == "repo\\real.yaml" + + +@pytest.mark.skipif(os.name == "nt", reason="on Windows the prefix is the long-path prefix and is dropped") +def test_a_posix_link_text_with_the_prefix_is_kept_as_written(monkeypatch): + """On POSIX ``\\\\?\\x`` is a file name: the walk reads the link text as written, as the overlay now does.""" + monkeypatch.setattr(os, "readlink", lambda p: "\\\\?\\x") + assert links.link_text(Path("link")) == "\\\\?\\x" + + def test_an_alias_to_the_checkout_root_itself_resolves_to_dot(tmp_path, monkeypatch): """A link whose target is only an anchor (``\\\\server\\share\\`` as the checkout root) leaves nothing to walk: it is the root.""" root = _repo(tmp_path, {}) @@ -227,7 +242,7 @@ def test_an_alias_to_the_checkout_root_itself_resolves_to_dot(tmp_path, monkeypa alias.symlink_to(root, target_is_directory=True) start = links._start with monkeypatch.context() as m: - m.setattr(links, "_link_target", lambda p: "ROOT") + m.setattr(links, "link_text", lambda p: "ROOT") m.setattr(links, "_start", lambda text, here: (root, []) if text == "ROOT" else start(text, here)) assert links._inside(root, str(alias)) == "." assert links._inside(root, str(alias) + "/sub") == "./sub" @@ -245,7 +260,7 @@ def test_a_dotdot_after_a_missing_name_or_a_file_is_no_path_in_both_trees(tmp_pa def test_the_link_walk_lives_apart_so_source_stays_under_the_line_cap(): """The walk is in ``links``; ``source`` re-exports the errors, and its 800-line cap (scripts/check_growth.py) holds.""" - assert source._walk_links is links._walk_links + assert source.walk_links is links.walk_links assert source.SourceArgumentError.__module__ == "dokimi.repos.source_errors" assert len(Path(source.__file__).read_text(encoding="utf-8").splitlines()) <= 800 From b09f05f90543ff632af0785d87c20a82ec73f73d Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Mon, 30 Nov 2026 03:47:48 -0700 Subject: [PATCH 2/3] test(repos): held guidance keeps a POSIX link text that starts with \\?\ Signed-off-by: Vladislav Perevezentsev --- dokimi/tests/test_repo_run_guidance.py | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/dokimi/tests/test_repo_run_guidance.py b/dokimi/tests/test_repo_run_guidance.py index 4eb2b63309..058d2c9c5d 100644 --- a/dokimi/tests/test_repo_run_guidance.py +++ b/dokimi/tests/test_repo_run_guidance.py @@ -129,6 +129,17 @@ def test_a_windows_alias_leads_to_the_held_file_through_the_drive(monkeypatch): assert held.resolved("ext/AGENTS.md") is None and "ext/AGENTS.md" not in held # D: has no path from C:\repo\workspace +@pytest.mark.skipif(os.name == "nt", reason="on Windows the prefix is the long-path prefix and is dropped") +def test_a_posix_link_text_that_starts_with_the_long_path_prefix_leads_to_that_file(tmp_path): + """On POSIX ``\\\\?\\AGENTS.md`` is a file name: a link to it does not lead to the held ``AGENTS.md``.""" + (tmp_path / "AGENTS.md").write_text("held\n") + (tmp_path / "\\\\?\\AGENTS.md").write_text("other\n") + (tmp_path / "AGENTS.claude.md").symlink_to("\\\\?\\AGENTS.md") + held = HeldGuidance(tmp_path, ["AGENTS.md"]) + assert held.resolved("AGENTS.claude.md") == "\\\\?\\AGENTS.md" + assert "AGENTS.claude.md" not in held and "AGENTS.md" in held + + def test_the_metrics_count_a_search_and_a_read_through_a_directory_link_but_not_a_dangling_one(tmp_path): ctx = SimpleNamespace(manifest=parse_manifest(MANIFEST)) events = [{"kind": "read", "path": "alias/AGENTS.md", "rc": 0}, From f7f226333081a46f445b3c500702de3f703c5228 Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Mon, 30 Nov 2026 03:48:00 -0700 Subject: [PATCH 3/3] docs(changelog): the old prefix reading refused a link, it removed nothing Signed-off-by: Vladislav Perevezentsev --- dokimi/changelog.d/20261128_100000_link-text-posix-prefix.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dokimi/changelog.d/20261128_100000_link-text-posix-prefix.md b/dokimi/changelog.d/20261128_100000_link-text-posix-prefix.md index 7c13267406..222876d95a 100644 --- a/dokimi/changelog.d/20261128_100000_link-text-posix-prefix.md +++ b/dokimi/changelog.d/20261128_100000_link-text-posix-prefix.md @@ -1,3 +1,3 @@ ### Fixed -- **A POSIX symlink whose target starts with `\\?\` is read as written by the guidance overlay arm and the held-guidance accounting** — the guidance overlay arm and the held-guidance accounting stripped the Windows long-path prefix on every OS, so `AGENTS.claude.md -> \\?\x` on Linux named the file `x` and could remove an overlay `x`, while the repository link walk read the same text as written. Both now read the link text through the walk's one helper, which strips the prefix only on Windows; Windows behaviour is unchanged. +- **A POSIX symlink whose target starts with `\\?\` is read as written by the guidance overlay arm and the held-guidance accounting** — the guidance overlay arm and the held-guidance accounting stripped the Windows long-path prefix on every OS, so `AGENTS.claude.md -> \\?\x` on Linux named the file `x`, so the overlay arm could refuse a base link as dangling through a removed overlay `x` and held guidance counted `x` as the file it reaches, while the repository link walk read the same text as written. Both now read the link text through the walk's one helper, which strips the prefix only on Windows; Windows behaviour is unchanged.