Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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`, 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.
4 changes: 2 additions & 2 deletions dokimi/dokimi/repos/export_skips.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
4 changes: 2 additions & 2 deletions dokimi/dokimi/repos/guidance_history.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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, [])


Expand Down
9 changes: 5 additions & 4 deletions dokimi/dokimi/repos/held_guidance.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
27 changes: 14 additions & 13 deletions dokimi/dokimi/repos/links.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)."""


Expand All @@ -34,8 +34,9 @@
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:]
Expand Down Expand Up @@ -64,7 +65,7 @@
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, True) else "" # ``Path`` drops it; it still means a directory (#1272)
if lexical.is_relative_to(root):
Expand All @@ -82,27 +83,27 @@
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, True)) 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], native: bool = False) -> bool:
def names_dir(seen: bool, text: str, rest: list[str], native: bool = False) -> 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, native) 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."""
Expand All @@ -129,14 +130,14 @@
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, True)
need_dir = names_dir(need_dir, text, pending, True)

Check warning on line 140 in dokimi/dokimi/repos/links.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant inconclusive: a candidate test file for it did not run
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)

Check warning on line 142 in dokimi/dokimi/repos/links.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant inconclusive: a candidate test file for it did not run
return root.joinpath(*walked)
10 changes: 5 additions & 5 deletions dokimi/dokimi/repos/manifest.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@
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 {
Expand Down Expand Up @@ -426,7 +426,7 @@
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"
Expand All @@ -435,7 +435,7 @@
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):

Check warning on line 438 in dokimi/dokimi/repos/manifest.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant inconclusive: a candidate test file for it did not run
report.errors.append(
f"explore_tasks {manifest.explore_tasks} is outside eval_dir {eval_dir}; "
"its reference answers would be visible to the agent"
Expand Down Expand Up @@ -464,7 +464,7 @@

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"
Expand Down Expand Up @@ -723,5 +723,5 @@
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("/") + "/")
19 changes: 5 additions & 14 deletions dokimi/dokimi/repos/overlay_paths.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from pathlib import Path

from .errors import PrepError
from .links import link_text


def _canon(path: Path) -> Path:
Expand All @@ -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,
Expand All @@ -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:
Expand All @@ -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."""
Expand All @@ -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())
14 changes: 7 additions & 7 deletions dokimi/dokimi/repos/source.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -132,8 +132,8 @@
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

Expand Down Expand Up @@ -187,13 +187,13 @@
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:
Expand Down Expand Up @@ -353,15 +353,15 @@
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
if hops > 40:
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)

Check warning on line 364 in dokimi/dokimi/repos/source.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant inconclusive: a candidate test file for it did not run
return "/".join(walked) or "."

def resolve(self, path: str, dirs: bool = False) -> str:
Expand Down
Loading
Loading