fix(python): mirror official Gemini hooks

This commit is contained in:
ZacharyZhang-NY committed 2026-07-20 08:19:11 -04:00
1 parent 2d8111d823
commit 2f223dca73
15 files changed
+2359 -204

No files matched your search

+279
View File
@@ -0,0 +1,279 @@
from __future__ import annotations
from dataclasses import dataclass
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
import ntpath
import os
from pathlib import Path
import subprocess # nosec B404
import sys
from threading import Thread
from typing import Any, Mapping
import pytest
from elydora.plugins._jsonc import parse_jsonc
from elydora.plugins.gemini import GeminiPlugin
from elydora.utils import base64url_encode
AGENT_ID = "agent-1"
MISSING = object()
VALID_PRIVATE_KEY = base64url_encode(bytes(range(32)))
@dataclass
class GeminiFixture:
root_dir: Path
home_dir: Path
project_dir: Path
config_path: Path
agent_dir: Path
guard_path: Path
hook_path: Path
runtime_config_path: Path
private_key_path: Path
plugin: GeminiPlugin
config: dict[str, str]
def install(self) -> None:
self.plugin.install(self.config)
def source(self) -> str:
with self.config_path.open("r", encoding="utf-8", newline="") as file:
return file.read()
def settings(self) -> dict[str, Any]:
value = parse_jsonc(
self.source(),
f"Gemini CLI test settings at {self.config_path}",
allow_trailing_commas=False,
)
assert isinstance(value, dict)
return value
class ElydoraApiHandler(BaseHTTPRequestHandler):
agent_status: Any = "active"
operation_status = 201
requests: list[dict[str, Any]] = []
@classmethod
def reset(cls, status: Any, operation_status: int) -> None:
cls.agent_status = status
cls.operation_status = operation_status
cls.requests = []
def _respond(self, status: int, value: object) -> None:
body = json.dumps(value).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_GET(self) -> None:
type(self).requests.append({
"method": "GET",
"path": self.path,
"authorization": self.headers.get("Authorization"),
})
self._respond(200, {"agent": {"status": type(self).agent_status}})
def do_POST(self) -> None:
length = int(self.headers.get("Content-Length", "0"))
raw = self.rfile.read(length)
type(self).requests.append({
"method": "POST",
"path": self.path,
"authorization": self.headers.get("Authorization"),
"raw": raw,
"json": json.loads(raw),
})
self._respond(
type(self).operation_status,
{"operation": {"accepted": True}},
)
def log_message(self, _format: str, *_args: object) -> None:
return
def start_api_server(
*, status: Any = "active", operation_status: int = 201
) -> ThreadingHTTPServer:
ElydoraApiHandler.reset(status, operation_status)
server = ThreadingHTTPServer(("127.0.0.1", 0), ElydoraApiHandler)
Thread(target=server.serve_forever, daemon=True).start()
return server
def server_base_url(server: ThreadingHTTPServer) -> str:
return f"http://127.0.0.1:{server.server_port}"
def write_text(path: Path, source: str, mode: int = 0o600) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(source, encoding="utf-8", newline="")
os.chmod(path, mode)
def write_json(path: Path, value: object, mode: int = 0o600) -> None:
source = value if isinstance(value, str) else json.dumps(value, indent=2) + "\n"
write_text(path, source, mode)
def _settings_root(
home_dir: Path, project_dir: Path, override: object
) -> Path:
if override is MISSING or override == "":
return home_dir
configured = str(home_dir) if override is None else str(override)
value = Path(configured)
return value if value.is_absolute() else project_dir / value
def prepare_fixture(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
*,
existing_settings: object = MISSING,
base_url: str = "http://127.0.0.1:9",
gemini_home_override: object = None,
) -> GeminiFixture:
home_dir = tmp_path / "home with spaces and 'quote $GEMINI_CWD %GEMINI_CWD%"
project_dir = tmp_path / "project with spaces"
project_dir.mkdir(parents=True)
monkeypatch.setenv("HOME", str(home_dir))
monkeypatch.setenv("USERPROFILE", str(home_dir))
monkeypatch.chdir(project_dir)
if gemini_home_override is MISSING:
monkeypatch.delenv("GEMINI_CLI_HOME", raising=False)
else:
configured = (
str(home_dir)
if gemini_home_override is None
else str(gemini_home_override)
)
monkeypatch.setenv("GEMINI_CLI_HOME", configured)
config_path = (
_settings_root(home_dir, project_dir, gemini_home_override)
/ ".gemini"
/ "settings.json"
)
agent_dir = home_dir / ".elydora" / AGENT_ID
guard_path = agent_dir / "guard.py"
hook_path = agent_dir / "hook.py"
runtime_config_path = agent_dir / "config.json"
private_key_path = agent_dir / "private.key"
if existing_settings is not MISSING:
write_json(config_path, existing_settings)
return GeminiFixture(
root_dir=tmp_path,
home_dir=home_dir,
project_dir=project_dir,
config_path=config_path,
agent_dir=agent_dir,
guard_path=guard_path,
hook_path=hook_path,
runtime_config_path=runtime_config_path,
private_key_path=private_key_path,
plugin=GeminiPlugin(),
config={
"org_id": "org-1",
"agent_id": AGENT_ID,
"agent_name": "gemini",
"private_key": VALID_PRIVATE_KEY,
"kid": "key-1",
"token": "token-1",
"base_url": base_url,
"guard_script_path": str(guard_path),
},
)
def managed_handler(
settings: Mapping[str, Any], event: str, name: str
) -> dict[str, Any]:
for group in settings["hooks"][event]:
if set(group) != {"hooks"}:
continue
for handler in group["hooks"]:
if (
set(handler) == {"type", "name", "command", "timeout"}
and handler.get("type") == "command"
and handler.get("name") == name
and handler.get("timeout") == 10_000
):
return handler
raise AssertionError(f"managed handler for {event!r} not found")
def assert_managed_handler(
handler: Mapping[str, Any], name: str
) -> None:
assert set(handler) == {"type", "name", "command", "timeout"}
assert handler["type"] == "command"
assert handler["name"] == name
assert handler["timeout"] == 10_000
assert isinstance(handler["command"], str)
def run_handler(
handler: Mapping[str, Any], payload: bytes, fixture: GeminiFixture
) -> subprocess.CompletedProcess[bytes]:
environment = {
**os.environ,
"HOME": str(fixture.home_dir),
"USERPROFILE": str(fixture.home_dir),
"GEMINI_CLI_HOME": str(fixture.home_dir),
}
if os.name == "nt":
powershell = ntpath.join(
os.environ.get("SystemRoot", r"C:\Windows"),
"System32",
"WindowsPowerShell",
"v1.0",
"powershell.exe",
)
source = (
f'{handler["command"]}; '
"if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }"
)
command = [
powershell,
"-NoLogo",
"-NoProfile",
"-NonInteractive",
"-Command",
source,
]
else:
command = ["/bin/bash", "-c", str(handler["command"])]
return subprocess.run( # nosec B603
command,
input=payload,
capture_output=True,
check=False,
cwd=fixture.project_dir,
env=environment,
)
def legacy_handler(script_path: Path) -> dict[str, str]:
command = (
f'"{sys.executable}" {script_path}'
if script_path.name == "guard.py"
else str(script_path)
)
return {"type": "command", "command": command}
def symlink_or_skip(
target: Path, link: Path, *, directory: bool = False
) -> None:
try:
link.symlink_to(target, target_is_directory=directory)
except OSError as error:
pytest.skip(f"Symbolic links unavailable: {error}")
-2
View File
@@ -17,7 +17,6 @@ from elydora.plugins._file_io import write_text_atomic
from elydora.plugins import (
copilot,
cursor,
gemini,
kiroide,
letta,
opencode,
@@ -375,7 +374,6 @@ def test_atomic_secret_write_preserves_existing_file_on_replace_failure(
[
(copilot, copilot.CopilotPlugin, "copilot"),
(cursor, cursor.CursorPlugin, "cursor"),
(gemini, gemini.GeminiPlugin, "gemini"),
(kiroide, kiroide.KiroIdePlugin, "kiroide"),
(letta, letta.LettaPlugin, "letta"),
(opencode, opencode.OpenCodePlugin, "opencode"),
+64
View File
@@ -0,0 +1,64 @@
from __future__ import annotations
import os
from pathlib import Path
import shutil
import subprocess # nosec B404
import pytest
from gemini_support import prepare_fixture
GEMINI_ENTRY = os.environ.get("ELYDORA_GEMINI_ENTRY")
@pytest.mark.skipif(
not GEMINI_ENTRY,
reason="set ELYDORA_GEMINI_ENTRY to the official Gemini CLI entry file",
)
def test_official_gemini_cli_accepts_installed_user_hooks(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
fixture = prepare_fixture(monkeypatch, tmp_path)
fixture.install()
node = shutil.which("node")
assert node is not None
environment = {
**os.environ,
"HOME": str(fixture.home_dir),
"USERPROFILE": str(fixture.home_dir),
"GEMINI_CLI_HOME": str(fixture.home_dir),
"GEMINI_API_KEY": "official-loader-test-key",
"GEMINI_TELEMETRY_ENABLED": "false",
"OTEL_SDK_DISABLED": "true",
}
version = subprocess.run( # nosec B603
[node, str(GEMINI_ENTRY), "--version"],
capture_output=True,
check=False,
cwd=fixture.project_dir,
env=environment,
text=True,
)
loaded = subprocess.run( # nosec B603
[node, str(GEMINI_ENTRY), "--skip-trust", "--list-extensions"],
capture_output=True,
check=False,
cwd=fixture.project_dir,
env=environment,
text=True,
)
assert version.returncode == 0, version.stderr
assert "0.51.0" in version.stdout
assert loaded.returncode == 0, loaded.stderr
output = (loaded.stdout + "\n" + loaded.stderr).lower()
for message in (
"invalid settings",
"settings validation",
"failed to parse",
"hook configuration error",
):
assert message not in output
+363
View File
@@ -0,0 +1,363 @@
from __future__ import annotations
import json
import os
from pathlib import Path
import subprocess # nosec B404
import sys
import pytest
from gemini_support import (
AGENT_ID,
MISSING,
VALID_PRIVATE_KEY,
assert_managed_handler,
legacy_handler,
managed_handler,
prepare_fixture,
write_json,
write_text,
)
from elydora.plugins.registry import SUPPORTED_AGENTS
GUARD_NAME = "elydora-guard"
AUDIT_NAME = "elydora-audit"
def assert_managed_pair(settings: dict, fixture: object) -> None:
guard = managed_handler(settings, "BeforeTool", GUARD_NAME)
audit = managed_handler(settings, "AfterTool", AUDIT_NAME)
assert_managed_handler(guard, GUARD_NAME)
assert_managed_handler(audit, AUDIT_NAME)
assert str(fixture.guard_path) not in ("", guard["command"])
assert str(fixture.hook_path) not in ("", audit["command"])
def test_gemini_is_registered_with_the_official_contract() -> None:
assert SUPPORTED_AGENTS["gemini"] == {
"name": "Gemini CLI",
"hook_event": "BeforeTool/AfterTool",
"config_path": "$GEMINI_CLI_HOME/.gemini/settings.json",
}
def test_install_preserves_jsonc_and_writes_one_exact_pair(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
capsys: pytest.CaptureFixture[str],
) -> None:
existing = "\r\n".join([
"{",
" // Keep this user preference.",
' "theme": "GitHub",',
' "hooks": {',
' "FutureEvent": [null],',
' "BeforeTool": [{ "matcher": "read_file", "hooks": '
'[{ "type": "command", "command": "user-hook" }] }]',
" }",
"}",
"",
])
fixture = prepare_fixture(
monkeypatch, tmp_path, existing_settings=existing
)
project_settings = fixture.project_dir / ".gemini" / "settings.json"
system_settings = tmp_path / "system-settings.json"
write_text(project_settings, '{ "owner": "project" }\n')
write_text(system_settings, '{ "owner": "system" }\n')
monkeypatch.setenv("GEMINI_CLI_SYSTEM_SETTINGS_PATH", str(system_settings))
fixture.install()
output = capsys.readouterr().out
assert "run /hooks list" in output
installed = fixture.settings()
assert "Keep this user preference" in fixture.source()
assert "\r\n" in fixture.source()
assert installed["theme"] == "GitHub"
assert installed["hooks"]["FutureEvent"] == [None]
assert installed["hooks"]["BeforeTool"][0]["hooks"][0]["command"] == "user-hook"
assert_managed_pair(installed, fixture)
first_source = fixture.source()
fixture.install()
assert fixture.source() == first_source
assert project_settings.read_text(encoding="utf-8") == '{ "owner": "project" }\n'
assert system_settings.read_text(encoding="utf-8") == '{ "owner": "system" }\n'
@pytest.mark.parametrize(
("override", "kind"),
[
(MISSING, "default"),
("", "empty"),
("relative gemini", "relative"),
("~", "literal_tilde"),
],
)
def test_gemini_home_matches_official_path_resolution(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
override: object,
kind: str,
) -> None:
fixture = prepare_fixture(
monkeypatch, tmp_path, gemini_home_override=override
)
fixture.install()
expected = {
"default": fixture.home_dir / ".gemini" / "settings.json",
"empty": fixture.home_dir / ".gemini" / "settings.json",
"relative": fixture.project_dir / "relative gemini" / ".gemini" / "settings.json",
"literal_tilde": fixture.project_dir / "~" / ".gemini" / "settings.json",
}[kind]
assert fixture.config_path == expected
assert expected.is_file()
INVALID_SETTINGS = [
("{ malformed", "parse Gemini CLI user settings"),
("[]", "must contain a JSON object"),
('{ "theme": true, }', "trailing commas are not allowed"),
('{ "hooks": {}, "hooks": {} }', 'duplicate field "hooks"'),
('{ "hooks": null }', 'field "hooks" must be an object'),
('{ "hooks": { "BeforeTool": null } }', "must be an array"),
('{ "hooks": { "BeforeTool": [null] } }', "group.*must be an object"),
(
'{ "hooks": { "BeforeTool": [{ "matcher": 1, "hooks": [] }] } }',
"matcher must be a string",
),
(
'{ "hooks": { "BeforeTool": [{ "sequential": 1, "hooks": [] }] } }',
"sequential must be a boolean",
),
('{ "hooks": { "BeforeTool": [{}] } }', "hooks array"),
('{ "hooks": { "BeforeTool": [{ "hooks": [null] }] } }', "handler"),
(
'{ "hooks": { "BeforeTool": [{ "hooks": [{ "type": "http" }] }] } }',
"unsupported type",
),
(
'{ "hooks": { "BeforeTool": [{ "hooks": [{ "type": "command", '
'"command": "" }] }] } }',
"non-empty command",
),
(
'{ "hooks": { "BeforeTool": [{ "hooks": [{ "type": "command", '
'"command": "x", "timeout": -1 }] }] } }',
"non-negative finite number",
),
(
'{ "hooks": { "BeforeTool": [{ "hooks": [{ "type": "command", '
'"command": "x", "env": { "A": 1 } }] }] } }',
"env must map names to strings",
),
('{ "hooksConfig": null }', "hooksConfig.*must be an object"),
('{ "hooksConfig": { "future": true } }', 'unsupported field "future"'),
('{ "hooksConfig": { "enabled": "yes" } }', "enabled.*must be a boolean"),
('{ "hooksConfig": { "disabled": [1] } }', "array of strings"),
('{ "hooksConfig": { "notifications": 1 } }', "notifications.*boolean"),
]
@pytest.mark.parametrize(("source", "pattern"), INVALID_SETTINGS)
def test_invalid_official_settings_fail_before_every_write(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
source: str,
pattern: str,
) -> None:
fixture = prepare_fixture(
monkeypatch, tmp_path, existing_settings=source
)
with pytest.raises(ValueError, match=pattern):
fixture.install()
assert fixture.source() == source
assert not fixture.agent_dir.exists()
@pytest.mark.parametrize(
("settings", "pattern"),
[
({"hooksConfig": {"enabled": False}}, "hooksConfig.enabled"),
({"hooksConfig": {"disabled": [GUARD_NAME]}}, GUARD_NAME),
({"hooksConfig": {"disabled": [AUDIT_NAME]}}, AUDIT_NAME),
],
)
def test_canonical_hook_controls_block_installation(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
settings: dict,
pattern: str,
) -> None:
fixture = prepare_fixture(
monkeypatch, tmp_path, existing_settings=settings
)
with pytest.raises(ValueError, match=pattern):
fixture.install()
assert not fixture.agent_dir.exists()
def test_disabled_legacy_command_blocks_installation(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
fixture = prepare_fixture(monkeypatch, tmp_path)
write_json(fixture.config_path, {
"hooksConfig": {
"disabled": [legacy_handler(fixture.guard_path)["command"]]
}
})
with pytest.raises(ValueError, match="hooksConfig.disabled"):
fixture.install()
assert not fixture.agent_dir.exists()
def test_exact_legacy_hooks_migrate_and_lookalikes_survive_uninstall(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
fixture = prepare_fixture(monkeypatch, tmp_path)
lookalike = legacy_handler(fixture.guard_path)
lookalike["command"] += " --inspect"
write_json(fixture.config_path, {
"hooks": {
"BeforeTool": [
{"hooks": [legacy_handler(fixture.guard_path)]},
{"hooks": [lookalike]},
],
"AfterTool": [{"hooks": [legacy_handler(fixture.hook_path)]}],
}
})
fixture.install()
settings = fixture.settings()
assert_managed_pair(settings, fixture)
assert any(
group["hooks"][0].get("command") == lookalike["command"]
for group in settings["hooks"]["BeforeTool"]
)
settings["hooks"]["BeforeTool"][-1]["hooks"].append({
"type": "command", "command": "user-command"
})
write_json(fixture.config_path, settings)
fixture.plugin.uninstall(AGENT_ID)
remaining = fixture.settings()["hooks"]
assert remaining["BeforeTool"] == [
{"hooks": [lookalike]},
{"hooks": [{"type": "command", "command": "user-command"}]},
]
assert "AfterTool" not in remaining
def test_uninstall_preserves_user_settings_and_removes_owned_file(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
user = prepare_fixture(
monkeypatch,
tmp_path / "user",
existing_settings={"theme": "GitHub", "hooks": {"Notification": []}},
)
user.install()
user.plugin.uninstall(AGENT_ID)
assert user.settings() == {
"theme": "GitHub", "hooks": {"Notification": []}
}
owned = prepare_fixture(monkeypatch, tmp_path / "owned")
owned.install()
owned.plugin.uninstall(AGENT_ID)
assert not owned.config_path.exists()
def test_status_requires_enabled_unique_pair_and_strict_runtime(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
fixture = prepare_fixture(monkeypatch, tmp_path)
fixture.install()
assert fixture.plugin.status()["installed"] is True
settings = fixture.settings()
settings["hooks"]["AfterTool"].append(settings["hooks"]["AfterTool"][-1])
write_json(fixture.config_path, settings)
assert fixture.plugin.status()["installed"] is False
fixture.install()
settings = fixture.settings()
settings["hooksConfig"] = {"disabled": [AUDIT_NAME]}
write_json(fixture.config_path, settings)
assert fixture.plugin.status()["installed"] is False
settings["hooksConfig"] = {"disabled": []}
write_json(fixture.config_path, settings)
write_text(fixture.private_key_path, "invalid")
with pytest.raises(ValueError, match="canonical 32-byte"):
fixture.plugin.status()
def test_cli_install_status_and_uninstall_end_to_end(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
fixture = prepare_fixture(monkeypatch, tmp_path)
key_path = tmp_path / "install-private.key"
token_path = tmp_path / "install-token.txt"
write_text(key_path, VALID_PRIVATE_KEY + "\n")
write_text(token_path, "token-1\n")
environment = {
**os.environ,
"HOME": str(fixture.home_dir),
"USERPROFILE": str(fixture.home_dir),
"GEMINI_CLI_HOME": str(fixture.home_dir),
}
root = Path(__file__).parents[1]
base = [sys.executable, "-m", "elydora.cli"]
install = subprocess.run( # nosec B603
[
*base, "install", "--agent", "gemini",
"--org_id", "org-1", "--agent_id", AGENT_ID,
"--private_key_file", str(key_path),
"--token_file", str(token_path),
"--kid", "key-1", "--base_url", "http://127.0.0.1:9",
],
capture_output=True,
check=False,
cwd=root,
env=environment,
text=True,
)
assert install.returncode == 0, install.stderr
assert "run /hooks list" in install.stdout
assert_managed_pair(fixture.settings(), fixture)
status = subprocess.run( # nosec B603
[*base, "status"],
capture_output=True,
check=False,
cwd=root,
env=environment,
text=True,
)
assert status.returncode == 0, status.stderr
assert "Gemini CLI" in status.stdout
assert "[installed]" in status.stdout
uninstall = subprocess.run( # nosec B603
[*base, "uninstall", "--agent", "gemini", "--agent_id", AGENT_ID],
capture_output=True,
check=False,
cwd=root,
env=environment,
text=True,
)
assert uninstall.returncode == 0, uninstall.stderr
assert not fixture.config_path.exists()
assert not fixture.agent_dir.exists()
+165
View File
@@ -0,0 +1,165 @@
from __future__ import annotations
import json
import os
from pathlib import Path
import pytest
from gemini_support import (
ElydoraApiHandler,
managed_handler,
prepare_fixture,
run_handler,
server_base_url,
start_api_server,
)
GUARD_NAME = "elydora-guard"
AUDIT_NAME = "elydora-audit"
def official_payload(event: str, **overrides: object) -> dict[str, object]:
value: dict[str, object] = {
"session_id": "session-1",
"transcript_path": "/tmp/session-1.jsonl",
"cwd": "/tmp/project",
"hook_event_name": event,
"timestamp": "2026-07-19T00:00:00.000Z",
"tool_name": "run_shell_command",
"tool_input": {"command": "pytest"},
}
if event == "AfterTool":
value["tool_response"] = {"output": "passed", "error": None}
value.update(overrides)
return value
def encoded(value: object) -> bytes:
return json.dumps(value, separators=(",", ":")).encode()
def test_guard_accepts_active_agents_with_valid_json_stdout(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
server = start_api_server()
try:
fixture = prepare_fixture(
monkeypatch, tmp_path, base_url=server_base_url(server)
)
fixture.install()
result = run_handler(
managed_handler(fixture.settings(), "BeforeTool", GUARD_NAME),
encoded(official_payload("BeforeTool")),
fixture,
)
finally:
server.shutdown()
server.server_close()
assert result.returncode == 0, result.stderr
assert json.loads(result.stdout) == {}
assert [request["method"] for request in ElydoraApiHandler.requests] == ["GET"]
@pytest.mark.parametrize("status", ["frozen", "revoked"])
def test_guard_propagates_official_exit_code_two(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
status: str,
) -> None:
server = start_api_server(status=status)
try:
fixture = prepare_fixture(
monkeypatch, tmp_path, base_url=server_base_url(server)
)
fixture.install()
result = run_handler(
managed_handler(fixture.settings(), "BeforeTool", GUARD_NAME),
encoded(official_payload("BeforeTool")),
fixture,
)
finally:
server.shutdown()
server.server_close()
assert result.returncode == 2
assert result.stdout == b""
assert status.encode() in result.stderr.lower()
def test_audit_preserves_complete_native_after_tool_payload(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
server = start_api_server()
try:
fixture = prepare_fixture(
monkeypatch, tmp_path, base_url=server_base_url(server)
)
fixture.install()
payload = official_payload(
"AfterTool",
mcp_context={"server_name": "filesystem", "tool_name": "write_file"},
original_request_name="write_file",
future_provider_field={"preserved": True},
)
result = run_handler(
managed_handler(fixture.settings(), "AfterTool", AUDIT_NAME),
encoded(payload),
fixture,
)
finally:
server.shutdown()
server.server_close()
assert result.returncode == 0, result.stderr
assert json.loads(result.stdout) == {}
operation = next(
request["json"]
for request in ElydoraApiHandler.requests
if request["method"] == "POST"
)
assert operation["payload"] == payload
assert operation["subject"] == {"session_id": "session-1"}
assert operation["action"] == {"tool": "run_shell_command"}
def test_runtime_failures_stay_observable_and_fail_open(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
fixture = prepare_fixture(monkeypatch, tmp_path)
fixture.install()
settings = fixture.settings()
guard = managed_handler(settings, "BeforeTool", GUARD_NAME)
audit = managed_handler(settings, "AfterTool", AUDIT_NAME)
invalid_guard = run_handler(guard, b"{ malformed", fixture)
audit_result = run_handler(
audit, encoded(official_payload("AfterTool")), fixture
)
assert invalid_guard.returncode == 0
assert json.loads(invalid_guard.stdout) == {}
assert b"invalid JSON" in invalid_guard.stderr
assert audit_result.returncode == 0
assert json.loads(audit_result.stdout) == {}
log = (fixture.agent_dir / "error.log").read_text(encoding="utf-8")
assert "[elydora-hook]" in log
assert "refused" in log.lower() or "urlerror" in log.lower()
@pytest.mark.skipif(os.name == "nt", reason="POSIX mode bits apply on POSIX")
def test_runtime_artifacts_use_private_modes(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
fixture = prepare_fixture(monkeypatch, tmp_path)
fixture.install()
for path, expected in (
(fixture.runtime_config_path, 0o600),
(fixture.private_key_path, 0o600),
(fixture.guard_path, 0o700),
(fixture.hook_path, 0o700),
(fixture.config_path, 0o600),
):
assert path.stat().st_mode & 0o777 == expected
@@ -0,0 +1,254 @@
from __future__ import annotations
import os
from pathlib import Path
import shutil
import subprocess # nosec B404
import sys
import pytest
from gemini_support import (
AGENT_ID,
VALID_PRIVATE_KEY,
prepare_fixture,
symlink_or_skip,
write_json,
write_text,
)
from elydora.plugins import _transaction, gemini_installation
from elydora.plugins.gemini_config import render_gemini_document
from elydora.plugins.gemini_contract import (
AUDIT_HOOK_NAME,
GUARD_HOOK_NAME,
build_gemini_group,
)
from elydora.plugins.gemini_io import read_gemini_document
RUNTIME_NAMES = ("guard.py", "config.json", "private.key", "hook.py")
def prepare_installation(fixture: object) -> list[_transaction.FileChange]:
document = read_gemini_document()
paths = gemini_installation.preflight_gemini_installation(
fixture.config, document
)
rendered = render_gemini_document(
document,
None,
{
"BeforeTool": build_gemini_group(
paths.guard_path, GUARD_HOOK_NAME
),
"AfterTool": build_gemini_group(
paths.audit_path, AUDIT_HOOK_NAME
),
},
)
return gemini_installation.prepare_gemini_installation(
fixture.config, paths, rendered
)
def assert_no_transaction_files(root: Path) -> None:
assert not list(root.rglob("*.tmp"))
assert not list(root.rglob("*.rollback"))
def test_transaction_rolls_back_all_five_files(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
original = '{"theme":"GitHub"}\n'
fixture = prepare_fixture(
monkeypatch, tmp_path, existing_settings=original
)
real_replace = _transaction.os.replace
failed = False
def fail_settings_once(source: str, destination: str) -> None:
nonlocal failed
if os.path.abspath(destination) == str(fixture.config_path) and not failed:
failed = True
raise OSError("injected Gemini settings failure")
real_replace(source, destination)
monkeypatch.setattr(_transaction.os, "replace", fail_settings_once)
with pytest.raises(OSError, match="injected Gemini settings failure"):
fixture.install()
assert fixture.source() == original
for name in RUNTIME_NAMES:
assert not (fixture.agent_dir / name).exists()
assert_no_transaction_files(fixture.home_dir)
def test_concurrent_settings_change_is_detected_before_runtime_commit(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
fixture = prepare_fixture(
monkeypatch, tmp_path, existing_settings={"theme": "GitHub"}
)
changes = prepare_installation(fixture)
concurrent = '{"theme":"Atom One","hooks":{"Notification":[]}}\n'
write_text(fixture.config_path, concurrent)
with pytest.raises(OSError, match="changed during installation"):
gemini_installation.commit_gemini_installation(changes)
assert fixture.source() == concurrent
for name in RUNTIME_NAMES:
assert not (fixture.agent_dir / name).exists()
assert_no_transaction_files(fixture.home_dir)
@pytest.mark.parametrize(
"runtime_name",
[
"private.key",
"guard.py",
"hook.py",
"chain-state.json",
"status-cache.json",
"error.log",
],
)
def test_orphan_runtime_artifacts_fail_before_settings_writes(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
runtime_name: str,
) -> None:
fixture = prepare_fixture(monkeypatch, tmp_path)
artifact = fixture.agent_dir / runtime_name
write_text(artifact, "orphan\n")
with pytest.raises(ValueError, match="identity cannot be verified"):
fixture.install()
assert artifact.read_text(encoding="utf-8") == "orphan\n"
assert not fixture.config_path.exists()
def test_mismatched_runtime_identity_fails_before_writes(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
fixture = prepare_fixture(monkeypatch, tmp_path)
write_json(fixture.runtime_config_path, {
"agent_id": "another-agent", "agent_name": "gemini"
})
original = fixture.runtime_config_path.read_text(encoding="utf-8")
with pytest.raises(ValueError, match="identity does not match"):
fixture.install()
assert fixture.runtime_config_path.read_text(encoding="utf-8") == original
assert not fixture.config_path.exists()
@pytest.mark.parametrize("kind", ["configuration", "settings", "runtime"])
def test_linked_configuration_and_runtime_paths_are_rejected(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
kind: str,
) -> None:
fixture = prepare_fixture(monkeypatch, tmp_path)
target = tmp_path / f"{kind}-target"
if kind == "settings":
write_text(target, "{}\n")
fixture.config_path.parent.mkdir(parents=True)
symlink_or_skip(target, fixture.config_path)
else:
target.mkdir()
link = (
fixture.config_path.parent
if kind == "configuration"
else fixture.agent_dir.parent
)
if kind == "runtime" and link.exists():
shutil.rmtree(link)
link.parent.mkdir(parents=True, exist_ok=True)
symlink_or_skip(target, link, directory=True)
with pytest.raises(OSError, match="physical (file|directory)"):
fixture.install()
@pytest.mark.parametrize(
("field", "value", "pattern"),
[
("agent_name", "codex", "requires agent_name gemini"),
("agent_id", "../escape", "Invalid agent ID"),
("private_key", "invalid", "canonical 32-byte"),
("token", "", "non-empty string"),
("base_url", "https://api.elydora.com?q=1", "query parameters"),
("guard_script_path", "outside", "managed agent directory"),
],
)
def test_install_validates_runtime_inputs_before_writes(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
field: str,
value: str,
pattern: str,
) -> None:
fixture = prepare_fixture(monkeypatch, tmp_path)
fixture.config[field] = value
with pytest.raises(ValueError, match=pattern):
fixture.install()
assert not fixture.config_path.exists()
assert not fixture.agent_dir.exists()
def test_status_surfaces_malformed_runtime_metadata(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
fixture = prepare_fixture(monkeypatch, tmp_path)
fixture.install()
write_text(fixture.runtime_config_path, "{ malformed")
with pytest.raises(ValueError, match="parse Elydora runtime config"):
fixture.plugin.status()
def test_installation_leaves_no_transaction_artifacts(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
fixture = prepare_fixture(monkeypatch, tmp_path)
fixture.install()
assert_no_transaction_files(fixture.home_dir)
def test_cli_preflight_preserves_malformed_settings(tmp_path: Path) -> None:
home_dir = tmp_path / "cli-home"
settings_path = home_dir / ".gemini" / "settings.json"
key_path = tmp_path / "private.key"
write_text(settings_path, "{ malformed")
write_text(key_path, VALID_PRIVATE_KEY)
environment = {
**os.environ,
"HOME": str(home_dir),
"USERPROFILE": str(home_dir),
"GEMINI_CLI_HOME": str(home_dir),
}
result = subprocess.run( # nosec B603
[
sys.executable, "-m", "elydora.cli", "install",
"--agent", "gemini", "--org_id", "org-1",
"--agent_id", AGENT_ID, "--private_key_file", str(key_path),
"--kid", "key-1", "--base_url", "https://api.elydora.com",
],
capture_output=True,
check=False,
cwd=Path(__file__).parents[1],
env=environment,
text=True,
)
assert result.returncode == 1
assert "parse Gemini CLI user settings" in result.stderr
assert settings_path.read_text(encoding="utf-8") == "{ malformed"
assert not (home_dir / ".elydora").exists()
@@ -1,22 +1,15 @@
from __future__ import annotations
from collections.abc import Callable
import pytest
from elydora.plugins.gemini import _is_elydora_hook as is_gemini_hook
from elydora.plugins.letta import _is_elydora_hook as is_letta_hook
HookDetector = Callable[[dict, str], bool]
@pytest.mark.parametrize("detector", [is_gemini_hook, is_letta_hook])
def test_hook_detection_handles_only_string_commands(detector: HookDetector) -> None:
assert detector({"command": 42}, "") is False
assert detector({"hooks": [{"command": None}]}, "") is False
assert detector({"hooks": [{"command": "run .elydora/agent-1/hook.py"}]}, "") is True
assert detector(
def test_hook_detection_handles_only_string_commands() -> None:
assert is_letta_hook({"command": 42}, "") is False
assert is_letta_hook({"hooks": [{"command": None}]}, "") is False
assert is_letta_hook(
{"hooks": [{"command": "run .elydora/agent-1/hook.py"}]}, ""
) is True
assert is_letta_hook(
{"hooks": [{"command": "run .elydora/agent-1/hook.py"}]},
"agent-2",
) is False