Skip to content

Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.

fix(learn): guard session-derived path checks against PermissionError in gemini/grok plugins (#2522)

Abhay Singh60bfe8be9356
diff --git a/headroom/learn/plugins/_paths.py b/headroom/learn/plugins/_paths.py
new file mode 100644
index 000000000..6ba4ca064
--- /dev/null
+++ b/headroom/learn/plugins/_paths.py
@@ -0,0 +1,22 @@
+"""Shared filesystem helpers for the ``learn`` session plugins."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+
+def path_exists(path: Path) -> bool:
+ """Like ``Path.exists()`` but treats an unreadable path as absent.
+
+ The ``learn`` plugins probe project paths reconstructed or recorded in
+ session files written on other machines / by other users. ``Path.exists()``
+ calls ``os.stat``, which raises ``PermissionError`` (not ``False``) when a
+ parent directory isn't stat-able — e.g. a decoded candidate that collides
+ with another user's home, or a recorded ``cwd`` behind a restricted mount.
+ Unhandled, that crashes the whole ``learn`` command (issue #2443). Treat any
+ ``OSError`` as "does not exist" so discovery skips the path instead.
+ """
+ try:
+ return path.exists()
+ except OSError:
+ return False
diff --git a/headroom/learn/plugins/claude.py b/headroom/learn/plugins/claude.py
index 48fb75b69..14b6c2061 100644
--- a/headroom/learn/plugins/claude.py
+++ b/headroom/learn/plugins/claude.py
@@ -20,6 +20,7 @@ from ..models import (
ToolCall,
)
from ..writer import ClaudeCodeWriter, ContextWriter
+from ._paths import path_exists as _path_exists
logger = logging.getLogger(__name__)
@@ -368,23 +369,6 @@ class ClaudeCodePlugin(LearnPlugin, ConversationScanner):
# =============================================================================
-def _path_exists(path: Path) -> bool:
- """Like ``Path.exists()`` but treats an unreadable path as absent.
-
- ``_decode_project_path`` probes speculative candidate paths (e.g.
- ``/home/marco/rocha`` when reconstructing ``/home/marco-rocha/...``). A
- candidate can collide with another user's directory whose parent isn't
- stat-able, and ``Path.exists()`` calls ``os.stat`` which then raises
- ``PermissionError`` instead of returning ``False`` — crashing the whole
- ``learn`` command (issue #2443). Match ``_greedy_path_decode``'s existing
- ``OSError`` handling and treat any such error as "does not exist".
- """
- try:
- return path.exists()
- except OSError:
- return False
-
-
def _decode_windows_path(drive: str, parts: list[str]) -> Path | None:
"""Reconstruct a Windows path from drive letter + dash-split tokens.
diff --git a/headroom/learn/plugins/gemini.py b/headroom/learn/plugins/gemini.py
index fd4722aa8..cf0ad28f1 100644
--- a/headroom/learn/plugins/gemini.py
+++ b/headroom/learn/plugins/gemini.py
@@ -19,6 +19,7 @@ from ..models import (
ToolCall,
)
from ..writer import ContextWriter, GeminiWriter
+from ._paths import path_exists
logger = logging.getLogger(__name__)
@@ -89,9 +90,9 @@ class GeminiPlugin(LearnPlugin, ConversationScanner):
project_path = self._detect_project_path(session_files[0])
gemini_md = None
- if project_path and project_path.exists():
+ if project_path and path_exists(project_path):
candidate = project_path / "GEMINI.md"
- if candidate.exists():
+ if path_exists(candidate):
gemini_md = candidate
projects.append(
@@ -356,10 +357,10 @@ class GeminiPlugin(LearnPlugin, ConversationScanner):
@staticmethod
def _project_path_from_entry(entry: dict) -> Path | None:
project_path = entry.get("projectPath", entry.get("project_path", ""))
- if project_path and Path(project_path).exists():
+ if project_path and path_exists(Path(project_path)):
return Path(project_path)
cwd = entry.get("cwd", entry.get("workingDirectory", ""))
- if cwd and Path(cwd).exists():
+ if cwd and path_exists(Path(cwd)):
return Path(cwd)
return None
diff --git a/headroom/learn/plugins/grok.py b/headroom/learn/plugins/grok.py
index 898466126..1011d34ba 100644
--- a/headroom/learn/plugins/grok.py
+++ b/headroom/learn/plugins/grok.py
@@ -14,6 +14,7 @@ from .._shared import classify_error, is_error_content, normalize_tool_name
from ..base import ConversationScanner, LearnPlugin
from ..models import ErrorCategory, ProjectInfo, SessionData, ToolCall
from ..writer import ContextWriter, GrokWriter
+from ._paths import path_exists
logger = logging.getLogger(__name__)
@@ -76,9 +77,9 @@ class GrokPlugin(LearnPlugin, ConversationScanner):
project_path=project_path,
data_path=workspace_dir,
context_file=grok_md
- if grok_md.exists()
+ if path_exists(grok_md)
else agents_md
- if agents_md.exists()
+ if path_exists(agents_md)
else None,
)
)
diff --git a/headroom/learn/plugins/opencode.py b/headroom/learn/plugins/opencode.py
index 593d16bc1..9bc53fb80 100644
--- a/headroom/learn/plugins/opencode.py
+++ b/headroom/learn/plugins/opencode.py
@@ -45,6 +45,7 @@ from ..models import (
ToolCall,
)
from ..writer import CodexWriter, ContextWriter
+from ._paths import path_exists
logger = logging.getLogger(__name__)
@@ -126,7 +127,7 @@ class OpenCodePlugin(LearnPlugin, ConversationScanner):
name=proj_name or worktree_path.name or proj_id,
project_path=worktree_path,
data_path=self._db_path.parent,
- context_file=agents_md if agents_md.exists() else None,
+ context_file=agents_md if path_exists(agents_md) else None,
)
)
finally:
diff --git a/tests/test_learn/test_plugin_permission_errors.py b/tests/test_learn/test_plugin_permission_errors.py
new file mode 100644
index 000000000..575cb07dd
--- /dev/null
+++ b/tests/test_learn/test_plugin_permission_errors.py
@@ -0,0 +1,123 @@
+"""learn plugins must not crash when a session-derived path can't be stat'd.
+
+Session files record project paths written on other machines / by other users.
+``Path.exists()`` calls ``os.stat``, which raises ``PermissionError`` (not
+``False``) when a parent directory isn't stat-able, and unhandled that aborts
+the whole ``learn`` command (issue #2443). The claude plugin already guards
+this; the gemini and grok plugins share the same shape and must too.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from headroom.learn.plugins._paths import path_exists
+
+
+class _BoomPath(type(Path())): # type: ignore[misc]
+ """A Path whose ``exists()`` raises PermissionError, like a restricted stat."""
+
+ def exists(self) -> bool: # noqa: D401
+ raise PermissionError(13, "Permission denied", str(self))
+
+
+def test_path_exists_swallows_permission_error() -> None:
+ assert path_exists(_BoomPath("/home/other/project")) is False
+
+
+def test_path_exists_true_for_real_path(tmp_path: Path) -> None:
+ assert path_exists(tmp_path) is True
+
+
+def test_gemini_detect_project_path_survives_permission_error(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from headroom.learn.plugins.gemini import GeminiPlugin
+
+ session = tmp_path / "session-1.json"
+ session.write_text(json.dumps({"projectPath": "/restricted/project"}), encoding="utf-8")
+
+ # os.stat on the recorded path raises PermissionError for a restricted parent.
+ def _boom(self: Path) -> bool:
+ raise PermissionError(13, "Permission denied", str(self))
+
+ monkeypatch.setattr(Path, "exists", _boom)
+
+ plugin = GeminiPlugin(gemini_dir=tmp_path)
+ # Must treat the unreadable path as absent, not raise.
+ assert plugin._detect_project_path(session) is None
+
+
+def test_grok_discover_projects_survives_permission_error(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from headroom.learn.plugins.grok import GrokPlugin
+
+ workspace = tmp_path / "sessions" / "%2Fhome%2Fu%2Fproj"
+ (workspace / "s1").mkdir(parents=True)
+ (workspace / "s1" / "updates.jsonl").write_text("{}\n", encoding="utf-8")
+
+ real_exists = Path.exists
+
+ def _boom_for_context_files(self: Path) -> bool:
+ # Only the GROK.md / AGENTS.md probes under the decoded project path blow
+ # up; the real session dirs still resolve so discovery reaches them.
+ if self.name in {"GROK.md", "AGENTS.md"}:
+ raise PermissionError(13, "Permission denied", str(self))
+ return real_exists(self)
+
+ monkeypatch.setattr(Path, "exists", _boom_for_context_files)
+
+ plugin = GrokPlugin(grok_dir=tmp_path)
+ projects = plugin.discover_projects()
+ # Discovery completes; the unreadable context file is simply treated as absent.
+ assert len(projects) == 1
+ assert projects[0].context_file is None
+
+
+def test_opencode_discover_projects_survives_permission_error(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ import sqlite3
+
+ from headroom.learn.plugins.opencode import OpenCodePlugin
+
+ db_path = tmp_path / "opencode.db"
+ conn = sqlite3.connect(db_path)
+ try:
+ conn.executescript(
+ """
+ CREATE TABLE project (id TEXT PRIMARY KEY, name TEXT, worktree TEXT);
+ CREATE TABLE session (id TEXT PRIMARY KEY, project_id TEXT, time_created INTEGER);
+ """
+ )
+ conn.execute(
+ "INSERT INTO project (id, name, worktree) VALUES (?, ?, ?)",
+ ("p1", "Proj", "/restricted/worktree"),
+ )
+ conn.execute(
+ "INSERT INTO session (id, project_id, time_created) VALUES (?, ?, ?)",
+ ("s1", "p1", 1_700_000_000_000),
+ )
+ conn.commit()
+ finally:
+ conn.close()
+
+ # The recorded worktree is behind a restricted parent: the AGENTS.md probe
+ # stats it. Only that probe blows up so the DB open still works.
+ real_exists = Path.exists
+
+ def _boom(self: Path) -> bool:
+ if self.name == "AGENTS.md":
+ raise PermissionError(13, "Permission denied", str(self))
+ return real_exists(self)
+
+ monkeypatch.setattr(Path, "exists", _boom)
+
+ plugin = OpenCodePlugin(db_path=db_path)
+ projects = plugin.discover_projects()
+ assert len(projects) == 1
+ assert projects[0].context_file is None