diff --git a/.codex/hooks/pre-tool-use.sh b/.codex/hooks/pre-tool-use.sh index ce8d772..63f5e7c 100644 --- a/.codex/hooks/pre-tool-use.sh +++ b/.codex/hooks/pre-tool-use.sh @@ -37,10 +37,10 @@ if [ -f "$PLAN_FILE" ]; then if [ -n "$PWF_PYTHON" ] && [ -f "$PWF_PYTHON" ] && [ -f "${HOOK_DIR}/context_frame.py" ]; then if [ -n "$PLAN_DIR" ]; then ATTEST_FILE="${PLAN_DIR}/.attestation"; else ATTEST_FILE=".plan-attestation"; fi if [ -n "$PLAN_DIR" ]; then MODE_FILE="${PLAN_DIR}/.mode"; else MODE_FILE=".mode"; fi - PWF_MODE=$("$PWF_PYTHON" -c 'import sys; from pathlib import Path; sys.path.insert(0, sys.argv[1]); import context_frame as c; raw=c.read_optional_regular_bytes(Path(sys.argv[2]), max_source_bytes=256); tokens=[] if raw is None else raw.decode("ascii", errors="strict").split(); allowed={"autonomous", "gate", "inject-smart"}; print("unsafe" if any(t not in allowed for t in tokens) else ("gated" if "gate" in tokens else ("autonomous" if "autonomous" in tokens else "legacy")))' "$HOOK_DIR" "$MODE_FILE" 2>/dev/null) || PWF_MODE="unsafe" + PWF_MODE=$("$PWF_PYTHON" -I -c 'import sys; from pathlib import Path; sys.path.insert(0, sys.argv[1]); import context_frame as c; raw=c.read_optional_regular_bytes(Path(sys.argv[2]), max_source_bytes=256); tokens=[] if raw is None else raw.decode("ascii", errors="strict").split(); allowed={"autonomous", "gate", "inject-smart"}; print("unsafe" if any(t not in allowed for t in tokens) else ("gated" if "gate" in tokens else ("autonomous" if "autonomous" in tokens else "legacy")))' "$HOOK_DIR" "$MODE_FILE" 2>/dev/null) || PWF_MODE="unsafe" case "$PWF_MODE" in autonomous|gated) echo '{"decision": "allow"}'; exit 0 ;; - legacy) "$PWF_PYTHON" "${HOOK_DIR}/context_frame.py" plan "$PLAN_FILE" --head 30 --attestation "$ATTEST_FILE" --mode "$MODE_FILE" >&2 ;; + legacy) "$PWF_PYTHON" -I "${HOOK_DIR}/context_frame.py" plan "$PLAN_FILE" --head 30 --attestation "$ATTEST_FILE" --mode "$MODE_FILE" >&2 ;; *) : ;; esac fi diff --git a/.codex/hooks/session-start.sh b/.codex/hooks/session-start.sh index 70680ce..5efa9c2 100644 --- a/.codex/hooks/session-start.sh +++ b/.codex/hooks/session-start.sh @@ -12,7 +12,7 @@ SKILL_DIR="$CODEX_ROOT/skills/planning-with-files" PYTHON_BIN="${PYTHON_BIN:-$(command -v python3 || command -v python)}" if [ -n "$PYTHON_BIN" ] && [ -f "$SKILL_DIR/scripts/session-catchup.py" ]; then - "$PYTHON_BIN" "$SKILL_DIR/scripts/session-catchup.py" --no-history "$(pwd)" + "$PYTHON_BIN" -I "$SKILL_DIR/scripts/session-catchup.py" --no-history "$(pwd)" fi sh "$SCRIPT_DIR/user-prompt-submit.sh" diff --git a/.codex/hooks/user-prompt-submit.sh b/.codex/hooks/user-prompt-submit.sh index 2bad255..0bdd15c 100644 --- a/.codex/hooks/user-prompt-submit.sh +++ b/.codex/hooks/user-prompt-submit.sh @@ -23,7 +23,7 @@ validate_python_candidate() { case "$_tp_lower" in */microsoft/windowsapps/*) return 1 ;; esac - "$_tp_candidate" -c 'import sys' >/dev/null 2>&1 || return 1 + "$_tp_candidate" -I -c 'import sys' >/dev/null 2>&1 || return 1 printf '%s\n' "$_tp_candidate" } @@ -61,7 +61,7 @@ if [ -n "${PWF_PLAN_ROOT:-}" ]; then esac PIN_PYTHON="$(trusted_python explicit 2>/dev/null)" || PIN_PYTHON="" [ -n "$PIN_PYTHON" ] || { echo "[planning-with-files] PWF_PLAN_ROOT could not be validated; nothing injected."; exit 0; } - PIN_REAL=$("$PIN_PYTHON" -c 'import sys; from pathlib import Path; sys.path.insert(0, sys.argv[1]); import codex_hook_adapter as a; root=a.effective_plan_root(Path.cwd()); print(root or "")' "$HOOK_DIR" 2>/dev/null) || PIN_REAL="" + PIN_REAL=$("$PIN_PYTHON" -I -c 'import sys; from pathlib import Path; sys.path.insert(0, sys.argv[1]); import codex_hook_adapter as a; root=a.effective_plan_root(Path.cwd()); print(root or "")' "$HOOK_DIR" 2>/dev/null) || PIN_REAL="" [ -n "$PIN_REAL" ] || { echo "[planning-with-files] PWF_PLAN_ROOT must stay within the current workspace; nothing injected."; exit 0; } if [ -n "$PIN_REAL" ] && [ -d "$PIN_REAL" ]; then PWF_PLAN_ROOT="$PIN_REAL" @@ -145,7 +145,7 @@ else if [ -z "$PWF_PYTHON" ]; then PWF_SESSION_ADMISSION="refused" else - PWF_SESSION_ADMISSION=$("$PWF_PYTHON" -c 'import sys; from pathlib import Path; sys.path.insert(0, sys.argv[1]); import codex_hook_adapter as a; root=a.effective_plan_root(Path.cwd()); + PWF_SESSION_ADMISSION=$("$PWF_PYTHON" -I -c 'import sys; from pathlib import Path; sys.path.insert(0, sys.argv[1]); import codex_hook_adapter as a; root=a.effective_plan_root(Path.cwd()); if root is None: print("refused") else: try: (root / ".planning" / "sessions").lstat(); armed=True @@ -253,13 +253,13 @@ if [ -f "$PLAN_FILE" ]; then if [ -z "$PWF_PYTHON" ] || [ ! -f "${HOOK_DIR}/context_frame.py" ]; then exit 0; fi if [ -n "$PLAN_DIR" ]; then ATTEST_FILE="${PLAN_DIR}/.attestation"; else ATTEST_FILE="${PLAN_PREFIX}.plan-attestation"; fi if [ -n "$PLAN_DIR" ]; then MODE_FILE="${PLAN_DIR}/.mode"; else MODE_FILE="${PLAN_PREFIX}.mode"; fi - PLAN_CONTEXT=$("$PWF_PYTHON" "${HOOK_DIR}/context_frame.py" plan "$PLAN_FILE" --head 50 --attestation "$ATTEST_FILE" --mode "$MODE_FILE" 2>&1) + PLAN_CONTEXT=$("$PWF_PYTHON" -I "${HOOK_DIR}/context_frame.py" plan "$PLAN_FILE" --head 50 --attestation "$ATTEST_FILE" --mode "$MODE_FILE" 2>&1) if [ $? -ne 0 ]; then printf '%s\n' "$PLAN_CONTEXT"; exit 0; fi echo "[planning-with-files] ACTIVE PLAN — current state:" printf '%s\n' "$PLAN_CONTEXT" echo "" if [ -f "$PROGRESS_FILE" ]; then - PROGRESS_CONTEXT=$("$PWF_PYTHON" "${HOOK_DIR}/context_frame.py" progress "$PROGRESS_FILE" --tail 20 2>&1) + PROGRESS_CONTEXT=$("$PWF_PYTHON" -I "${HOOK_DIR}/context_frame.py" progress "$PROGRESS_FILE" --tail 20 2>&1) [ $? -eq 0 ] && printf '%s\n' "$PROGRESS_CONTEXT" fi echo "" diff --git a/.gemini/hooks/before-model.sh b/.gemini/hooks/before-model.sh index 7e8d01c..8faaca9 100644 --- a/.gemini/hooks/before-model.sh +++ b/.gemini/hooks/before-model.sh @@ -18,7 +18,7 @@ CURRENT_PHASE=$(grep -m1 "^## Current Phase" "$PLAN_FILE" 2>/dev/null || grep -m if [ -n "$CURRENT_PHASE" ]; then PYTHON=$(command -v python3 || command -v python) - ESCAPED=$($PYTHON -c "import sys,json; print(json.dumps(sys.stdin.read(), ensure_ascii=False))" <<< "[planning-with-files] Current: $CURRENT_PHASE" 2>/dev/null || echo "\"\"") + ESCAPED=$($PYTHON -I -c "import sys,json; print(json.dumps(sys.stdin.read(), ensure_ascii=False))" <<< "[planning-with-files] Current: $CURRENT_PHASE" 2>/dev/null || echo "\"\"") printf '%s\n' "{\"additionalContext\":$ESCAPED}" else echo '{}' diff --git a/.gemini/hooks/before-tool.sh b/.gemini/hooks/before-tool.sh index 6dffe94..98b8cf5 100644 --- a/.gemini/hooks/before-tool.sh +++ b/.gemini/hooks/before-tool.sh @@ -21,7 +21,7 @@ fi PYTHON=$(command -v python3 || command -v python) if [ -n "$PYTHON" ]; then - ESCAPED=$($PYTHON -c "import sys,json; print(json.dumps(sys.stdin.read(), ensure_ascii=False))" <<< "$CONTEXT" 2>/dev/null) + ESCAPED=$($PYTHON -I -c "import sys,json; print(json.dumps(sys.stdin.read(), ensure_ascii=False))" <<< "$CONTEXT" 2>/dev/null) if [ -n "$ESCAPED" ] && [ "$ESCAPED" != "\"\"" ]; then printf '%s\n' "{\"systemMessage\":$ESCAPED}" exit 0 diff --git a/.gemini/hooks/session-end.sh b/.gemini/hooks/session-end.sh index ddae00e..42cd583 100644 --- a/.gemini/hooks/session-end.sh +++ b/.gemini/hooks/session-end.sh @@ -18,7 +18,7 @@ if [ -f "$SCRIPT_DIR/check-complete.sh" ]; then RESULT=$(sh "$SCRIPT_DIR/check-complete.sh" 2>/dev/null || true) if [ -n "$RESULT" ]; then PYTHON=$(command -v python3 || command -v python) - ESCAPED=$($PYTHON -c "import sys,json; print(json.dumps(sys.stdin.read(), ensure_ascii=False))" <<< "$RESULT" 2>/dev/null || echo "\"\"") + ESCAPED=$($PYTHON -I -c "import sys,json; print(json.dumps(sys.stdin.read(), ensure_ascii=False))" <<< "$RESULT" 2>/dev/null || echo "\"\"") printf '%s\n' "{\"systemMessage\":$ESCAPED}" exit 0 fi diff --git a/.gemini/hooks/session-start.sh b/.gemini/hooks/session-start.sh index 78e17dc..b198dba 100644 --- a/.gemini/hooks/session-start.sh +++ b/.gemini/hooks/session-start.sh @@ -19,11 +19,11 @@ fi PYTHON=$(command -v python3 || command -v python) CATCHUP="" if [ -n "$PYTHON" ] && [ -f "$SCRIPT_DIR/session-catchup.py" ]; then - CATCHUP=$($PYTHON "$SCRIPT_DIR/session-catchup.py" --no-history "$(pwd)" 2>/dev/null || true) + CATCHUP=$($PYTHON -I "$SCRIPT_DIR/session-catchup.py" --no-history "$(pwd)" 2>/dev/null || true) fi if [ -n "$CATCHUP" ]; then - ESCAPED=$($PYTHON -c "import sys,json; print(json.dumps(sys.stdin.read(), ensure_ascii=False))" <<< "$CATCHUP" 2>/dev/null || echo "\"[planning-with-files] Session recovery data available. Read task_plan.md, progress.md, and findings.md.\"") + ESCAPED=$($PYTHON -I -c "import sys,json; print(json.dumps(sys.stdin.read(), ensure_ascii=False))" <<< "$CATCHUP" 2>/dev/null || echo "\"[planning-with-files] Session recovery data available. Read task_plan.md, progress.md, and findings.md.\"") printf '%s\n' "{\"hookSpecificOutput\":{\"additionalContext\":$ESCAPED}}" else echo '{"hookSpecificOutput":{"additionalContext":"[planning-with-files] Active plan detected. Read task_plan.md, progress.md, and findings.md before proceeding."}}' diff --git a/.github/hooks/scripts/error-occurred.sh b/.github/hooks/scripts/error-occurred.sh index 7722b19..be1b3bb 100644 --- a/.github/hooks/scripts/error-occurred.sh +++ b/.github/hooks/scripts/error-occurred.sh @@ -21,7 +21,7 @@ for _p in /usr/bin/python3 /usr/local/bin/python3 /opt/homebrew/bin/python3; do [ -x "$_p" ] && { PYTHON="$_p"; break; } done [ -z "$PYTHON" ] && PYTHON=$(command -v python3 2>/dev/null || command -v python 2>/dev/null) -ERROR_MSG=$(printf '%s\n' "$INPUT" | $PYTHON -c " +ERROR_MSG=$(printf '%s\n' "$INPUT" | $PYTHON -I -c " import sys, json try: data = json.load(sys.stdin) @@ -33,7 +33,7 @@ except: if [ -n "$ERROR_MSG" ]; then CONTEXT="[planning-with-files] Error detected: ${ERROR_MSG}. Log this error in task_plan.md under Errors Encountered with the attempt number and resolution." - ESCAPED=$(printf '%s\n' "$CONTEXT" | $PYTHON -c "import sys,json; print(json.dumps(sys.stdin.read(), ensure_ascii=False))" 2>/dev/null || echo "\"\"") + ESCAPED=$(printf '%s\n' "$CONTEXT" | $PYTHON -I -c "import sys,json; print(json.dumps(sys.stdin.read(), ensure_ascii=False))" 2>/dev/null || echo "\"\"") printf '%s\n' "{\"hookSpecificOutput\":{\"hookEventName\":\"ErrorOccurred\",\"additionalContext\":$ESCAPED}}" else echo '{}' diff --git a/.github/hooks/scripts/pre-tool-use.sh b/.github/hooks/scripts/pre-tool-use.sh index 019cffc..a0d8180 100755 --- a/.github/hooks/scripts/pre-tool-use.sh +++ b/.github/hooks/scripts/pre-tool-use.sh @@ -31,7 +31,7 @@ for _p in /usr/bin/python3 /usr/local/bin/python3 /opt/homebrew/bin/python3; do [ -x "$_p" ] && { PYTHON="$_p"; break; } done [ -z "$PYTHON" ] && PYTHON=$(command -v python3 2>/dev/null || command -v python 2>/dev/null) -ESCAPED=$(echo "$CONTEXT" | $PYTHON -c "import sys,json; print(json.dumps(sys.stdin.read(), ensure_ascii=False))" 2>/dev/null || echo "\"\"") +ESCAPED=$(echo "$CONTEXT" | $PYTHON -I -c "import sys,json; print(json.dumps(sys.stdin.read(), ensure_ascii=False))" 2>/dev/null || echo "\"\"") printf '%s\n' "{\"hookSpecificOutput\":{\"hookEventName\":\"PreToolUse\",\"permissionDecision\":\"allow\",\"additionalContext\":$ESCAPED}}" exit 0 diff --git a/.github/hooks/scripts/session-start.sh b/.github/hooks/scripts/session-start.sh index 7637753..4ad17c6 100755 --- a/.github/hooks/scripts/session-start.sh +++ b/.github/hooks/scripts/session-start.sh @@ -21,7 +21,7 @@ if [ -f "$PLAN_FILE" ]; then # Plan exists: keep catchup zero-history, then read the plan header. CATCHUP="" if [ -n "$PYTHON" ] && [ -f "$SKILL_DIR/scripts/session-catchup.py" ]; then - CATCHUP=$($PYTHON "$SKILL_DIR/scripts/session-catchup.py" --no-history "$(pwd)" 2>/dev/null | head -100) + CATCHUP=$($PYTHON -I "$SKILL_DIR/scripts/session-catchup.py" --no-history "$(pwd)" 2>/dev/null | head -100) fi if [ -n "$CATCHUP" ]; then @@ -43,7 +43,7 @@ if [ -z "$CONTEXT" ]; then fi # Escape context for JSON -ESCAPED=$(echo "$CONTEXT" | $PYTHON -c "import sys,json; print(json.dumps(sys.stdin.read(), ensure_ascii=False))" 2>/dev/null || echo "\"\"") +ESCAPED=$(echo "$CONTEXT" | $PYTHON -I -c "import sys,json; print(json.dumps(sys.stdin.read(), ensure_ascii=False))" 2>/dev/null || echo "\"\"") printf '%s\n' "{\"hookSpecificOutput\":{\"hookEventName\":\"SessionStart\",\"additionalContext\":$ESCAPED}}" exit 0 diff --git a/tests/test_adapter_python_isolation.py b/tests/test_adapter_python_isolation.py new file mode 100644 index 0000000..c210aa0 --- /dev/null +++ b/tests/test_adapter_python_isolation.py @@ -0,0 +1,198 @@ +"""Regression coverage for shell-adapter Python import isolation.""" +from __future__ import annotations + +import json +import os +import shutil +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + + +REPO = Path(__file__).resolve().parent.parent +SH = shutil.which("sh") +CODEX_HOOKS = REPO / ".codex" / "hooks" +GEMINI_HOOKS = REPO / ".gemini" / "hooks" +COPILOT_HOOKS = REPO / ".github" / "hooks" / "scripts" + +PYTHON_SHELL_HOOKS = ( + GEMINI_HOOKS / "before-model.sh", + GEMINI_HOOKS / "before-tool.sh", + GEMINI_HOOKS / "session-start.sh", + GEMINI_HOOKS / "session-end.sh", + COPILOT_HOOKS / "session-start.sh", + COPILOT_HOOKS / "pre-tool-use.sh", + COPILOT_HOOKS / "error-occurred.sh", +) + +CODEX_PYTHON_SHELL_HOOKS = ( + CODEX_HOOKS / "pre-tool-use.sh", + CODEX_HOOKS / "session-start.sh", + CODEX_HOOKS / "user-prompt-submit.sh", +) + + +def shell_python_is_usable() -> bool: + if not SH: + return False + result = subprocess.run( + [ + str(SH), + "-c", + 'PY=$(command -v python3 || command -v python); [ -n "$PY" ] && "$PY" -I -c "import json"', + ], + capture_output=True, + text=True, + timeout=10, + ) + return result.returncode == 0 + + +@unittest.skipUnless(shell_python_is_usable(), "shell Python is not usable") +class AdapterPythonIsolationTests(unittest.TestCase): + def setUp(self) -> None: + self._tmp = tempfile.TemporaryDirectory() + self.cwd = Path(self._tmp.name) + (self.cwd / "task_plan.md").write_text( + "# Task Plan\n## Current Phase: hardening\n### Phase 1: Work\n" + "**Status:** in_progress\n", + encoding="utf-8", + ) + (self.cwd / "json.py").write_text( + "open('PLANTED_json', 'w').close()\nraise RuntimeError('shadow loaded')\n", + encoding="utf-8", + ) + + def tearDown(self) -> None: + self._tmp.cleanup() + + def run_hook(self, script: Path, input_data: str = "{}") -> dict: + result = subprocess.run( + [str(SH), str(script)], + cwd=str(self.cwd), + env=dict(os.environ), + input=input_data, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + timeout=60, + ) + self.assertEqual(0, result.returncode, result.stderr) + return json.loads(result.stdout.lstrip("\ufeff")) + + def test_gemini_json_encoding_ignores_project_json_module(self) -> None: + for name in ("before-model.sh", "before-tool.sh"): + with self.subTest(hook=name): + marker = self.cwd / "PLANTED_json" + marker.unlink(missing_ok=True) + payload = self.run_hook(GEMINI_HOOKS / name) + self.assertFalse(marker.exists(), f"{name} imported project json.py") + self.assertIn("hardening", json.dumps(payload)) + + def test_copilot_python_paths_ignore_project_json_module(self) -> None: + cases = ( + ("session-start.sh", "{}"), + ("pre-tool-use.sh", "{}"), + ("error-occurred.sh", '{"error":{"message":"fixture failure"}}'), + ) + for name, input_data in cases: + with self.subTest(hook=name): + marker = self.cwd / "PLANTED_json" + marker.unlink(missing_ok=True) + payload = self.run_hook(COPILOT_HOOKS / name, input_data) + self.assertFalse(marker.exists(), f"{name} imported project json.py") + self.assertIn("additionalContext", payload.get("hookSpecificOutput", {})) + + +@unittest.skipUnless(SH, "sh is not available") +class CodexPythonIsolationTests(unittest.TestCase): + def setUp(self) -> None: + self._tmp = tempfile.TemporaryDirectory() + self.cwd = Path(self._tmp.name) + (self.cwd / "task_plan.md").write_text( + "# Task Plan\n### Phase 1: Work\n**Status:** in_progress\n", + encoding="utf-8", + ) + (self.cwd / "progress.md").write_text("# Progress\n", encoding="utf-8") + (self.cwd / "hashlib.py").write_text( + "open('PLANTED_hashlib', 'w').close()\nraise RuntimeError('shadow loaded')\n", + encoding="utf-8", + ) + + def tearDown(self) -> None: + self._tmp.cleanup() + + def run_hook(self, name: str) -> subprocess.CompletedProcess[str]: + env = dict(os.environ) + env["PYTHON_BIN"] = sys.executable + env["PWF_PLAN_ROOT"] = str(self.cwd) + return subprocess.run( + [str(SH), str(CODEX_HOOKS / name)], + cwd=str(self.cwd), + env=env, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + timeout=60, + ) + + def test_codex_shell_python_ignores_project_hashlib_module(self) -> None: + cases = ( + ("user-prompt-submit.sh", "ACTIVE PLAN", "stdout"), + ("pre-tool-use.sh", "# Task Plan", "stderr"), + ("session-start.sh", "ACTIVE PLAN", "stdout"), + ) + for name, expected, stream in cases: + with self.subTest(hook=name): + marker = self.cwd / "PLANTED_hashlib" + marker.unlink(missing_ok=True) + result = self.run_hook(name) + self.assertEqual(0, result.returncode, result.stderr) + self.assertFalse(marker.exists(), f"{name} imported project hashlib.py") + self.assertIn(expected, getattr(result, stream)) + + +class AdapterPythonIsolationContractTests(unittest.TestCase): + def test_every_adapter_python_invocation_uses_isolated_mode(self) -> None: + for script in PYTHON_SHELL_HOOKS: + with self.subTest(hook=script.relative_to(REPO)): + text = script.read_text(encoding="utf-8") + invocations = [ + line + for line in text.splitlines() + if "$($PYTHON" in line or "| $PYTHON" in line + ] + self.assertTrue(invocations, f"no Python invocation found in {script}") + for line in invocations: + self.assertIn( + "$PYTHON -I", + line, + f"non-isolated Python invocation in {script.relative_to(REPO)}: {line}", + ) + + def test_every_codex_shell_python_invocation_uses_isolated_mode(self) -> None: + variables = ('"$PYTHON_BIN"', '"$PWF_PYTHON"', '"$PIN_PYTHON"', '"$_tp_candidate"') + for script in CODEX_PYTHON_SHELL_HOOKS: + with self.subTest(hook=script.relative_to(REPO)): + text = script.read_text(encoding="utf-8") + invocations = [ + line + for line in text.splitlines() + if any(variable in line for variable in variables) + and (" -c " in line or (".py\"" in line and " -f " not in line)) + ] + self.assertTrue(invocations, f"no Python invocation found in {script}") + for line in invocations: + self.assertIn( + " -I ", + line, + f"non-isolated Python invocation in {script.relative_to(REPO)}: {line}", + ) + + +if __name__ == "__main__": + unittest.main()