From 2ee27671cdf7ee7f04df45dde33580c329045385 Mon Sep 17 00:00:00 2001 From: John Paul Soliva Date: Mon, 28 Sep 2026 19:17:56 +0900 Subject: [PATCH] fix(agent): never contain context files by a root at or above $HOME A dotfiles repo at $HOME made the whole home directory the containment root, so an AGENTS.md in a download the agent unpacked could link to any home file. Subdirectory hints had the same gap when the session's working directory is $HOME or /. Such a root now narrows to the directory the file was found in; the user's own files at the dotfiles root still load. --- agent/prompt_builder.py | 12 ++++---- agent/subdirectory_hints.py | 14 ++++++++- tests/agent/test_prompt_builder.py | 30 +++++++++++++++++++ .../docs/user-guide/features/context-files.md | 2 +- .../user-guide/features/context-files.md | 2 +- 5 files changed, 52 insertions(+), 8 deletions(-) diff --git a/agent/prompt_builder.py b/agent/prompt_builder.py index 446138bb7a..103195c6a3 100644 --- a/agent/prompt_builder.py +++ b/agent/prompt_builder.py @@ -1596,9 +1596,11 @@ def _context_section(content: str, label: str, warn_name: str, path: Path, conte return _truncate_content(body, warn_name, context_length=context_length, read_path=str(path)) -def _project_root(cwd_path: Path) -> Path: - """Containment root for project context files: the git root, else the cwd.""" - return _find_git_root(cwd_path) or cwd_path.resolve() +def _project_root(cwd_path: Path, directory: Optional[Path] = None) -> Path: + """Containment root for a project context file found in *directory* (default: the cwd): the git root, else + the cwd; a root at or above ``$HOME`` narrows to *directory* (``subdirectory_hints._containment_root``).""" + from agent.subdirectory_hints import _containment_root # late import: that module imports this one + return _containment_root(_find_git_root(cwd_path) or cwd_path.resolve(), (directory or cwd_path).resolve()) def _hermes_md_candidates(cwd_path: Path) -> list[tuple[str, Path, str]]: @@ -1607,7 +1609,7 @@ def _hermes_md_candidates(cwd_path: Path) -> list[tuple[str, Path, str]]: if path is None: return [] label = str(path.relative_to(cwd_path)) if path.is_relative_to(cwd_path) else path.name - return [(label, path, _read_context_file(path, _project_root(cwd_path)))] + return [(label, path, _read_context_file(path, _project_root(cwd_path, path.parent)))] def _agents_md_directory_chain(cwd_path: Path) -> list[Path]: @@ -1624,9 +1626,9 @@ def _agents_md_candidates(cwd_path: Path) -> list[tuple[str, Path, str]]: """AGENTS.md chain from git root down to cwd; per directory the first NON-EMPTY of ``AGENTS.override.md`` / ``AGENTS.md`` / ``agents.md`` wins (empty or unreadable files are listed but fall through).""" cwd_resolved = cwd_path.resolve() - root = _project_root(cwd_resolved) found: list[tuple[str, Path, str]] = [] for directory in _agents_md_directory_chain(cwd_resolved): + root = _project_root(cwd_resolved, directory) for name in ("AGENTS.override.md", "AGENTS.md", "agents.md"): candidate = directory / name if not _exists_or_denied(candidate): diff --git a/agent/subdirectory_hints.py b/agent/subdirectory_hints.py index eb194068ef..38f6d39fbe 100644 --- a/agent/subdirectory_hints.py +++ b/agent/subdirectory_hints.py @@ -37,6 +37,18 @@ def _digest(content: str) -> str: return hashlib.sha256(content.encode("utf-8")).hexdigest() +def _containment_root(anchor: Path, directory: Path) -> Path: + """Directory a context/hint file found in *directory* must resolve inside: *anchor* (the project's git + root or the session's working dir), unless *anchor* is ``$HOME`` or above. A dotfiles repo at ``$HOME``, + or a session rooted at ``$HOME`` or ``/``, contains every file below it, including a download the agent + unpacked, so such a file must stay inside its own *directory*.""" + try: + wide = Path.home().resolve().is_relative_to(anchor) + except (OSError, RuntimeError): # no resolvable home: fail closed + wide = True + return directory if wide else anchor + + def _resolved_hint_target(hint_path: Path, working_dir: Path) -> Optional[Path]: """Resolved hint-file target, or None when the file must not be loaded. @@ -300,7 +312,7 @@ class SubdirectoryHintTracker: continue except OSError: continue - if (target := _resolved_hint_target(hint_path, self.working_dir)) is None: + if (target := _resolved_hint_target(hint_path, _containment_root(self.working_dir, directory))) is None: continue try: content = (_read_text_with_timeout(target) or "").strip() diff --git a/tests/agent/test_prompt_builder.py b/tests/agent/test_prompt_builder.py index 0d0669d2a1..71cf61163b 100644 --- a/tests/agent/test_prompt_builder.py +++ b/tests/agent/test_prompt_builder.py @@ -532,6 +532,36 @@ class TestBuildContextFilesPrompt: link.write_text("REGULAR-MARKER") assert "REGULAR-MARKER" in build_context_files_prompt(cwd=str(project), skip_soul=True) + @pytest.mark.parametrize("loader", ["startup", "subdirectory_hint"]) + def test_home_or_above_is_never_the_containment_root(self, tmp_path, monkeypatch, loader): + """A dotfiles repo at $HOME (startup context) or a session rooted at $HOME (subdirectory hints) would + contain every file below it: a download the agent unpacked must not link a context file to a home file.""" + home = tmp_path / "home" + (home / ".git").mkdir(parents=True) + (home / "notes.md").write_text("HOME-MARKER") + (home / "AGENTS.md").write_text("OWN-HOME-AGENTS") + unpacked = home / "Downloads" / "unpacked" + (unpacked / "docs").mkdir(parents=True) + (unpacked / "docs" / "rules.md").write_text("INSIDE-MARKER") + monkeypatch.setenv("HOME", str(home)) + monkeypatch.setenv("USERPROFILE", str(home)) + + def load() -> str: + if loader == "startup": + return build_context_files_prompt(cwd=str(unpacked), skip_soul=True) + from agent.subdirectory_hints import SubdirectoryHintTracker + return SubdirectoryHintTracker(working_dir=str(home)).check_tool_call( + "read_file", {"path": str(unpacked / "x.py")}) or "" + + link = unpacked / "AGENTS.md" + link.symlink_to(home / "notes.md") + assert "HOME-MARKER" not in load() + link.unlink() + link.symlink_to(unpacked / "docs" / "rules.md") + assert "INSIDE-MARKER" in load() + if loader == "startup": # the user's own AGENTS.md at the dotfiles root still loads + assert "OWN-HOME-AGENTS" in load() + diff --git a/website/docs/user-guide/features/context-files.md b/website/docs/user-guide/features/context-files.md index 4d151c2522..72b457abc8 100644 --- a/website/docs/user-guide/features/context-files.md +++ b/website/docs/user-guide/features/context-files.md @@ -126,7 +126,7 @@ This means your existing Cursor conventions automatically apply when using Herme Context files are loaded by `build_context_files_prompt()` in `agent/prompt_builder.py`: 1. **Scan working directory** — checks for `.hermes.md` → `AGENTS.md` → `CLAUDE.md` → `.cursorrules` (first match wins) -2. **Content is read** — each file is read as UTF-8 text. A file (or symlink) whose resolved target lies outside the project (the git root, else the working directory) or is on the file read deny-list is skipped +2. **Content is read** — each file is read as UTF-8 text. A file (or symlink) whose resolved target lies outside the project (the git root, else the working directory) or is on the file read deny-list is skipped. When that root is your home directory or above (a dotfiles repo at `$HOME`, or a session started in `$HOME`), the target must instead stay inside the file's own directory. Subdirectory context files follow the same rule, with the session's working directory as the root 3. **Security scan** — content is checked for prompt injection patterns 4. **Truncation** — files exceeding the character cap are head/tail truncated (70% head, 20% tail, with a marker in the middle). The cap is an explicit `context_file_max_chars` from config.yaml when set; otherwise it scales dynamically with the model's context window (floor 20,000 chars, ceiling 500,000) 5. **Assembly** — all sections are combined under a `# Project Context` header diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/context-files.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/context-files.md index 5d83f76df3..9b920548b6 100644 --- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/context-files.md +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/context-files.md @@ -107,7 +107,7 @@ Hermes 兼容 Cursor IDE 的 `.cursorrules` 文件和 `.cursor/rules/*.mdc` 规 上下文文件由 `agent/prompt_builder.py` 中的 `build_context_files_prompt()` 加载: 1. **扫描工作目录** — 依次检查 `.hermes.md` → `AGENTS.md` → `CLAUDE.md` → `.cursorrules`(先匹配先生效) -2. **读取内容** — 以 UTF-8 文本读取每个文件。解析后的目标(含符号链接)位于项目之外(git 根目录,否则为工作目录)或在文件读取拒绝列表中的文件会被跳过 +2. **读取内容** — 以 UTF-8 文本读取每个文件。解析后的目标(含符号链接)位于项目之外(git 根目录,否则为工作目录)或在文件读取拒绝列表中的文件会被跳过。当该根目录是你的主目录或其上级目录时(例如 `$HOME` 下的 dotfiles 仓库,或在 `$HOME` 中启动的会话),目标必须改为位于该文件自身所在的目录内。子目录上下文文件遵循同样的规则,以会话的工作目录作为根目录 3. **安全扫描** — 检查内容是否存在 prompt 注入模式 4. **截断** — 超过 20,000 个字符的文件进行首尾截断(70% 头部,20% 尾部,中间插入标记) 5. **组装** — 所有部分合并在 `# Project Context` 标题下