fix(python): mirror Factory Droid 0.175 hooks

This commit is contained in:
ZacharyZhang-NY committed 2026-07-20 14:11:58 -04:00
1 parent 47ef2cc691
commit c59fcafebb
12 files changed
+2301 -763

No files matched your search

+253
View File
@@ -0,0 +1,253 @@
from __future__ import annotations
import base64
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
import os
from pathlib import Path
import subprocess # nosec B404
import threading
from typing import Any, Dict, Iterable, Optional
import pytest
from elydora.plugins import _jsonc, droid, droid_policy
from elydora.plugins.base import InstallConfig
AGENT_ID = "agent-1"
VALID_PRIVATE_KEY = base64.urlsafe_b64encode(bytes([13]) * 32).rstrip(b"=").decode()
JsonObject = Dict[str, Any]
class DroidFixture:
def __init__(
self,
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
*,
root_config: Any = None,
legacy_config: Any = None,
settings: Any = None,
local_settings: Any = None,
project_settings: Any = None,
project_local_settings: Any = None,
base_url: str = "http://127.0.0.1:9",
agent_id: str = AGENT_ID,
) -> None:
self.root_dir = tmp_path
self.home_dir = tmp_path / "home with spaces and 'quote %DROID%"
self.workspace_dir = tmp_path / "workspace with spaces"
self.factory_dir = self.home_dir / ".factory"
self.root_path = self.factory_dir / "hooks.json"
self.legacy_path = self.factory_dir / "hooks" / "hooks.json"
self.settings_path = self.factory_dir / "settings.json"
self.local_settings_path = self.factory_dir / "settings.local.json"
self.project_factory_dir = self.workspace_dir / ".factory"
self.project_settings_path = self.project_factory_dir / "settings.json"
self.project_local_settings_path = (
self.project_factory_dir / "settings.local.json"
)
self.system_settings_path = (
tmp_path / "managed factory" / "settings.json"
)
self.agent_id = agent_id
self.agent_dir = self.home_dir / ".elydora" / agent_id
self.guard_path = self.agent_dir / "guard.py"
self.audit_path = self.agent_dir / "hook.py"
self.runtime_config = self.agent_dir / "config.json"
self.private_key_path = self.agent_dir / "private.key"
self.workspace_dir.mkdir(parents=True)
(self.workspace_dir / ".git").mkdir()
self._write(self.root_path, root_config)
self._write(self.legacy_path, legacy_config)
self._write(self.settings_path, settings)
self._write(self.local_settings_path, local_settings)
self._write(self.project_settings_path, project_settings)
self._write(self.project_local_settings_path, project_local_settings)
monkeypatch.setenv("HOME", str(self.home_dir))
monkeypatch.setenv("USERPROFILE", str(self.home_dir))
monkeypatch.chdir(self.workspace_dir)
monkeypatch.setattr(
droid_policy,
"_managed_settings_path",
lambda: str(self.system_settings_path),
)
self.config: InstallConfig = {
"agent_id": agent_id,
"agent_name": "droid",
"org_id": "org-1",
"private_key": VALID_PRIVATE_KEY,
"kid": "kid-1",
"token": "token-1",
"base_url": base_url,
"guard_script_path": str(self.guard_path),
}
self.plugin = droid.DroidPlugin()
@staticmethod
def _write(path: Path, value: Any) -> None:
if value is None:
return
path.parent.mkdir(parents=True, exist_ok=True)
raw = value if isinstance(value, str) else json.dumps(value, indent=2) + "\n"
with open(path, "w", encoding="utf-8", newline="") as file:
file.write(raw)
def install(self, **overrides: str) -> None:
config = InstallConfig(**self.config)
config.update(overrides)
self.plugin.install(config)
def write_system_settings(self, value: Any) -> None:
self._write(self.system_settings_path, value)
def load_jsonc(path: Path) -> JsonObject:
value = _jsonc.parse_jsonc(path.read_text(encoding="utf-8"), str(path))
assert isinstance(value, dict)
return value
def write_json(path: Path, value: Any) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
source = value if isinstance(value, str) else json.dumps(value, indent=2) + "\n"
with open(path, "w", encoding="utf-8", newline="") as file:
file.write(source)
def read_raw(path: Path) -> str:
with open(path, "r", encoding="utf-8", newline="") as file:
return file.read()
def managed_group(
hooks: JsonObject,
event: str,
script_name: str,
) -> Optional[JsonObject]:
for group in hooks.get(event, []):
if any(
script_name in handler.get("command", "")
for handler in group.get("hooks", [])
):
return group
return None
def managed_handler(
hooks: JsonObject,
event: str,
script_name: str,
) -> Optional[JsonObject]:
group = managed_group(hooks, event, script_name)
if group is None:
return None
return next(
handler
for handler in group["hooks"]
if script_name in handler.get("command", "")
)
def assert_native_group(group: Optional[JsonObject]) -> None:
assert group is not None
assert sorted(group) == ["hooks", "matcher"]
assert group["matcher"] == "*"
assert len(group["hooks"]) == 1
handler = group["hooks"][0]
assert sorted(handler) == ["command", "timeout", "type"]
assert handler["type"] == "command"
assert handler["timeout"] == 10
def run_hook(
command: str,
payload: str,
) -> subprocess.CompletedProcess[str]:
argv = (
[
"powershell.exe",
"-NoLogo",
"-NoProfile",
"-NonInteractive",
"-Command",
command,
]
if os.name == "nt"
else ["/bin/sh", "-c", command]
)
return subprocess.run( # nosec B603
argv,
input=payload,
text=True,
capture_output=True,
check=False,
timeout=10,
)
def assert_no_transaction_files(root: Path) -> None:
leaked = [
path
for path in root.rglob("*")
if path.suffix in {".tmp", ".rollback"}
]
assert leaked == []
def snapshot(paths: Iterable[Path]) -> Dict[Path, str]:
return {
path: read_raw(path)
for path in paths
}
def assert_snapshot(expected: Dict[Path, str]) -> None:
for path, source in expected.items():
assert read_raw(path) == source
class _ApiHandler(BaseHTTPRequestHandler):
def _respond(self, status: int, payload: str) -> None:
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(payload.encode("utf-8"))
def do_GET(self) -> None:
self.server.requests.append(("GET", self.path, b"")) # type: ignore[attr-defined]
self._respond(200, '{"agent":{"status":"active"}}')
def do_POST(self) -> None:
length = int(self.headers.get("Content-Length", "0"))
body = self.rfile.read(length)
self.server.requests.append( # type: ignore[attr-defined]
("POST", self.path, body)
)
self._respond(201, '{"operation":{"accepted":true}}')
def log_message(self, _format: str, *args: object) -> None:
del args
class ApiServer:
def __init__(self) -> None:
self.server = ThreadingHTTPServer(("127.0.0.1", 0), _ApiHandler)
self.server.requests = [] # type: ignore[attr-defined]
self.thread = threading.Thread(
target=self.server.serve_forever,
daemon=True,
)
self.thread.start()
host, port = self.server.server_address
self.base_url = f"http://{host}:{port}"
@property
def requests(self) -> list[tuple[str, str, bytes]]:
return self.server.requests # type: ignore[attr-defined,no-any-return]
def close(self) -> None:
self.server.shutdown()
self.thread.join(timeout=5)
self.server.server_close()
+376 -335
View File
@@ -1,109 +1,37 @@
from __future__ import annotations
import base64
import json
import os
from pathlib import Path
import subprocess # nosec B404
from typing import Any, Dict, Optional
import sys
import time
from typing import Any
import pytest
from elydora import cli
from elydora.plugins import _jsonc, droid, droid_io
from elydora.plugins.base import InstallConfig
from elydora.plugins import droid
from elydora.plugins.registry import SUPPORTED_AGENTS
AGENT_ID = "agent-1"
JsonObject = Dict[str, Any]
from droid_support import (
AGENT_ID,
VALID_PRIVATE_KEY,
ApiServer,
DroidFixture,
assert_native_group,
assert_no_transaction_files,
load_jsonc,
managed_group,
managed_handler,
read_raw,
run_hook,
snapshot,
write_json,
)
class DroidFixture:
def __init__(
self,
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
*,
hooks: Any = None,
legacy_hooks: Any = None,
settings: Any = None,
create_guard: bool = True,
) -> None:
self.home_dir = tmp_path / "home with spaces and 'quote"
self.workspace_dir = self.home_dir / "workspace"
self.factory_dir = self.home_dir / ".factory"
self.config_path = self.factory_dir / "hooks.json"
self.legacy_path = self.factory_dir / "hooks" / "hooks.json"
self.settings_path = self.factory_dir / "settings.json"
self.agent_dir = self.home_dir / ".elydora" / AGENT_ID
self.guard_path = self.agent_dir / "guard.py"
self.audit_path = self.agent_dir / "hook.py"
self.runtime_config = self.agent_dir / "config.json"
self.private_key_path = self.agent_dir / "private.key"
self.workspace_dir.mkdir(parents=True)
self.agent_dir.mkdir(parents=True)
if create_guard:
self.guard_path.write_text(
"import sys\nsys.stdin.read()\n"
"sys.stderr.write('Agent is frozen by Elydora.\\n')\n"
"raise SystemExit(2)\n",
encoding="utf-8",
)
self._write(self.config_path, hooks)
self._write(self.legacy_path, legacy_hooks)
self._write(self.settings_path, settings)
monkeypatch.setenv("HOME", str(self.home_dir))
monkeypatch.setenv("USERPROFILE", str(self.home_dir))
private_key = base64.urlsafe_b64encode(bytes([1]) * 32).rstrip(b"=").decode()
self.config: InstallConfig = {
"agent_id": AGENT_ID,
"agent_name": "droid",
"org_id": "org-1",
"private_key": private_key,
"kid": "kid-1",
"base_url": "https://api.elydora.test",
"guard_script_path": str(self.guard_path),
}
self.plugin = droid.DroidPlugin()
@staticmethod
def _write(path: Path, value: Any) -> None:
if value is None:
return
path.parent.mkdir(parents=True, exist_ok=True)
raw = value if isinstance(value, str) else json.dumps(value, indent=2) + "\n"
with open(path, "w", encoding="utf-8", newline="") as file:
file.write(raw)
def install(self) -> None:
self.plugin.install(self.config)
def _load(path: Path) -> JsonObject:
value = _jsonc.parse_jsonc(path.read_text(encoding="utf-8"), str(path))
assert isinstance(value, dict)
return value
def _managed_handler(groups: Any, script_path: Path) -> Optional[JsonObject]:
for group in groups or []:
for handler in group["hooks"]:
if str(script_path) in handler.get("command", ""):
return handler
return None
def _run_command(command: str, payload: str) -> subprocess.CompletedProcess[str]:
return subprocess.run( # nosec B602
command,
shell=True,
input=payload,
text=True,
capture_output=True,
check=False,
timeout=10,
)
def _current_hooks(path: Path) -> dict[str, Any]:
return load_jsonc(path)["hooks"]
def test_droid_is_registered_in_the_sdk_and_cli() -> None:
@@ -115,213 +43,379 @@ def test_droid_is_registered_in_the_sdk_and_cli() -> None:
assert cli.PLUGIN_MAP["droid"] is droid.DroidPlugin
def test_install_preserves_jsonc_and_uses_per_event_precedence(
def test_install_writes_current_container_and_complete_runtime(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
capsys: pytest.CaptureFixture[str],
) -> None:
hooks = """{
// root hook source
"PreToolUse": [
// keep root group comment
{ "matcher": "Read", "hooks": [{ "type": "command", "command": "root-user" }] }
],
"Notification": []
fixture = DroidFixture(monkeypatch, tmp_path)
fixture.install()
output = capsys.readouterr().out
source = fixture.root_path.read_text(encoding="utf-8")
assert source.startswith("// Managed by Elydora\n")
hooks = _current_hooks(fixture.root_path)
assert_native_group(managed_group(hooks, "PreToolUse", "guard.py"))
assert_native_group(managed_group(hooks, "PostToolUse", "hook.py"))
guard = managed_handler(hooks, "PreToolUse", "guard.py")
assert guard is not None
if os.name == "nt":
assert guard["command"].startswith("& '")
assert guard["command"].endswith("; exit $LASTEXITCODE")
runtime = json.loads(fixture.runtime_config.read_text(encoding="utf-8"))
assert runtime == {
"org_id": "org-1",
"agent_id": AGENT_ID,
"kid": "kid-1",
"base_url": "http://127.0.0.1:9",
"agent_name": "droid",
"token": "token-1",
}
assert fixture.private_key_path.read_text(encoding="utf-8") == VALID_PRIVATE_KEY
assert "AGENT_NAME = 'droid'" in fixture.guard_path.read_text(encoding="utf-8")
assert "NATIVE_PAYLOAD = True" in fixture.audit_path.read_text(encoding="utf-8")
assert "run /hooks" in output
paths = (
fixture.root_path,
fixture.guard_path,
fixture.audit_path,
fixture.runtime_config,
fixture.private_key_path,
)
before = snapshot(paths)
fixture.install()
assert snapshot(paths) == before
assert_no_transaction_files(tmp_path)
@pytest.mark.skipif(os.name != "nt", reason="Windows migration contract")
def test_install_migrates_legacy_windows_commands(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
fixture = DroidFixture(monkeypatch, tmp_path, root_config={"hooks": {}})
def group(script: Path) -> dict[str, Any]:
return {
"matcher": "*",
"hooks": [{
"type": "command",
"command": f'"{sys.executable}" "{script}"',
"timeout": 10,
}],
}
write_json(fixture.root_path, {
"hooks": {
"PreToolUse": [group(fixture.guard_path)],
"PostToolUse": [group(fixture.audit_path)],
},
})
fixture.install()
hooks = _current_hooks(fixture.root_path)
assert len(hooks["PreToolUse"]) == 1
assert len(hooks["PostToolUse"]) == 1
assert hooks["PreToolUse"][0]["hooks"][0]["command"].startswith("& '")
def test_root_hook_file_has_whole_source_precedence(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
root = """{
// active root source
"hooks": {
"PreToolUse": [
{ "matcher": "Read", "hooks": [{ "type": "command", "command": "root-user" }] }
]
}
}
"""
settings = """{
// general setting
// inactive settings source
"theme": "dark",
"hooks": {
// settings fallback event
"PostToolUse": [
// keep settings group comment
{ "matcher": "Edit", "hooks": [{ "type": "command", "command": "settings-user" }] }
],
"showHookOutput": true,
},
]
}
}
"""
fixture = DroidFixture(monkeypatch, tmp_path, hooks=hooks, settings=settings)
fixture = DroidFixture(
monkeypatch,
tmp_path,
root_config=root,
settings=settings,
)
fixture.install()
fixture.install()
output = capsys.readouterr().out
root_raw = fixture.config_path.read_text(encoding="utf-8")
settings_raw = fixture.settings_path.read_text(encoding="utf-8")
root = _load(fixture.config_path)
user_settings = _load(fixture.settings_path)
assert "root hook source" in root_raw
assert "keep root group comment" in root_raw
assert "general setting" in settings_raw
assert "settings fallback event" in settings_raw
assert "keep settings group comment" in settings_raw
assert len(root["PreToolUse"]) == 2
assert root["PreToolUse"][0]["hooks"][0]["command"] == "root-user"
assert "PostToolUse" not in root
assert user_settings["theme"] == "dark"
assert len(user_settings["hooks"]["PostToolUse"]) == 2
assert "PreToolUse" not in user_settings["hooks"]
for groups, path in (
(root["PreToolUse"], fixture.guard_path),
(user_settings["hooks"]["PostToolUse"], fixture.audit_path),
):
handler = _managed_handler(groups, path)
assert handler is not None
assert sorted(handler) == ["command", "timeout", "type"]
assert handler["type"] == "command"
assert handler["timeout"] == 10
assert "run /hooks" in output
assert not (fixture.workspace_dir / ".factory" / "hooks.json").exists()
root_source = fixture.root_path.read_text(encoding="utf-8")
hooks = _current_hooks(fixture.root_path)
assert "active root source" in root_source
assert hooks["PreToolUse"][0]["hooks"][0]["command"] == "root-user"
assert_native_group(managed_group(hooks, "PreToolUse", "guard.py"))
assert_native_group(managed_group(hooks, "PostToolUse", "hook.py"))
assert fixture.settings_path.read_text(encoding="utf-8") == settings
def test_install_keeps_active_legacy_source(
def test_settings_and_local_settings_follow_source_precedence(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
settings = '{\r\n\t"theme": "dark",\r\n\t"hooks": {}\r\n}\r\n'
fixture = DroidFixture(monkeypatch, tmp_path / "base", settings=settings)
fixture.install()
assert not fixture.root_path.exists()
source = read_raw(fixture.settings_path)
hooks = load_jsonc(fixture.settings_path)["hooks"]
assert '\r\n\t\t"PreToolUse"' in source
assert_native_group(managed_group(hooks, "PreToolUse", "guard.py"))
assert_native_group(managed_group(hooks, "PostToolUse", "hook.py"))
local_fixture = DroidFixture(
monkeypatch,
tmp_path / "local",
settings={"hooks": {"Notification": []}},
local_settings={"hooks": {"SessionStart": []}},
)
base_before = local_fixture.settings_path.read_text(encoding="utf-8")
local_fixture.install()
assert local_fixture.settings_path.read_text(encoding="utf-8") == base_before
local_hooks = load_jsonc(local_fixture.local_settings_path)["hooks"]
assert_native_group(managed_group(local_hooks, "PreToolUse", "guard.py"))
assert_native_group(managed_group(local_hooks, "PostToolUse", "hook.py"))
def test_legacy_hook_file_stays_active_until_factory_migrates_it(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
fixture = DroidFixture(
monkeypatch,
tmp_path,
legacy_hooks={"PreToolUse": []},
legacy_config={
"PreToolUse": [{
"matcher": "Read",
"hooks": [{"type": "command", "command": "legacy-user"}],
}],
},
settings={"hooks": {"PostToolUse": []}},
)
settings_before = fixture.settings_path.read_text(encoding="utf-8")
fixture.install()
assert not fixture.config_path.exists()
assert _managed_handler(_load(fixture.legacy_path)["PreToolUse"], fixture.guard_path)
assert _managed_handler(
_load(fixture.settings_path)["hooks"]["PostToolUse"],
fixture.audit_path,
)
assert not fixture.root_path.exists()
legacy = load_jsonc(fixture.legacy_path)
assert_native_group(managed_group(legacy, "PreToolUse", "guard.py"))
assert_native_group(managed_group(legacy, "PostToolUse", "hook.py"))
assert fixture.settings_path.read_text(encoding="utf-8") == settings_before
def test_install_reuses_settings_container_and_formatting(
def test_guard_blocks_and_audit_preserves_native_payload(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
source = '{\r\n\t"owner": "user",\r\n\t"hooks": {}\r\n}\r\n'
fixture = DroidFixture(monkeypatch, tmp_path, settings=source)
fixture.install()
assert not fixture.config_path.exists()
with open(fixture.settings_path, "r", encoding="utf-8", newline="") as file:
raw = file.read()
settings = _load(fixture.settings_path)
assert "\r\n\t\t\"PreToolUse\"" in raw
assert "\r\n\t\t\"PostToolUse\"" in raw
assert settings["owner"] == "user"
api = ApiServer()
try:
fixture = DroidFixture(
monkeypatch,
tmp_path,
base_url=api.base_url,
)
fixture.install()
hooks = _current_hooks(fixture.root_path)
guard = managed_handler(hooks, "PreToolUse", "guard.py")
audit = managed_handler(hooks, "PostToolUse", "hook.py")
assert guard is not None and audit is not None
write_json(fixture.agent_dir / "status-cache.json", {
"status": "frozen",
"cached_at": time.time(),
})
pre_payload = {
"session_id": "session-1",
"transcript_path": str(fixture.home_dir / "transcript.jsonl"),
"cwd": str(fixture.workspace_dir),
"permission_mode": "auto-high",
"hook_event_name": "PreToolUse",
"tool_name": "Execute",
"tool_input": {"command": "echo test"},
}
guard_result = run_hook(guard["command"], json.dumps(pre_payload))
assert guard_result.returncode == 2
assert 'Agent "droid" is frozen' in guard_result.stderr
post_payload = {
**pre_payload,
"hook_event_name": "PostToolUse",
"tool_response": {"output": "test", "success": True},
}
audit_result = run_hook(audit["command"], json.dumps(post_payload))
assert audit_result.returncode == 0, audit_result.stderr
request = next(item for item in api.requests if item[0] == "POST")
operation = json.loads(request[2])
assert operation["payload"] == post_payload
assert operation["subject"] == {"session_id": "session-1"}
assert operation["action"] == {"tool": "Execute"}
finally:
api.close()
def test_commands_block_and_forward_official_input_byte_for_byte(
def test_status_requires_exact_hooks_and_runtime_sources(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
fixture = DroidFixture(monkeypatch, tmp_path)
fixture.install()
capture_path = tmp_path / "captured-event.json"
fixture.audit_path.write_text(
"import pathlib, sys\n"
f"pathlib.Path({str(capture_path)!r}).write_bytes(sys.stdin.buffer.read())\n",
encoding="utf-8",
)
root = _load(fixture.config_path)
guard = _managed_handler(root["PreToolUse"], fixture.guard_path)
audit = _managed_handler(root["PostToolUse"], fixture.audit_path)
assert guard is not None and audit is not None
pre_payload = json.dumps({
"session_id": "session-1",
"transcript_path": str(tmp_path / "transcript.jsonl"),
"cwd": str(fixture.workspace_dir),
"permission_mode": "auto-high",
"hook_event_name": "PreToolUse",
"tool_name": "Execute",
"tool_input": {"command": "echo test"},
})
guard_result = _run_command(guard["command"], pre_payload)
assert guard_result.returncode == 2
assert "Agent is frozen by Elydora" in guard_result.stderr
post_payload = json.dumps({
**json.loads(pre_payload),
"hook_event_name": "PostToolUse",
"tool_response": {"output": "test", "success": True},
})
audit_result = _run_command(audit["command"], post_payload)
assert audit_result.returncode == 0, audit_result.stderr
assert capture_path.read_text(encoding="utf-8") == post_payload
def test_status_requires_enabled_pair_and_runtime_files(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
fixture = DroidFixture(
monkeypatch,
tmp_path,
hooks={"PreToolUse": []},
settings={"hooks": {"PostToolUse": []}},
)
fixture.install()
assert fixture.plugin.status()["installed"] is True
fixture.audit_path.unlink()
assert fixture.plugin.status()["installed"] is False
root = _load(fixture.config_path)
root["hooksDisabled"] = True
fixture.config_path.write_text(json.dumps(root), encoding="utf-8")
assert fixture.plugin.status() == {
"installed": True,
"agent": "droid",
"details": f"Config: {fixture.root_path}",
}
fixture.audit_path.write_text("tampered\n", encoding="utf-8")
status = fixture.plugin.status()
assert status["installed"] is False
assert "disabled" in status["details"].lower()
assert "incomplete" in status["details"]
def test_uninstall_preserves_user_sources_and_exact_ownership(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
hooks = '{\n // keep root comment\n "PreToolUse": []\n}\n'
settings = (
'{\n "theme": "dark",\n "hooks": {\n'
' // keep settings comment\n "PostToolUse": []\n }\n}\n'
)
fixture = DroidFixture(monkeypatch, tmp_path, hooks=hooks, settings=settings)
fixture.install()
fixture.plugin.uninstall("agent-10")
assert _managed_handler(_load(fixture.config_path)["PreToolUse"], fixture.guard_path)
uninstall_id = "AGENT-1" if os.name == "nt" else AGENT_ID
fixture.plugin.uninstall(uninstall_id)
root_raw = fixture.config_path.read_text(encoding="utf-8")
settings_raw = fixture.settings_path.read_text(encoding="utf-8")
assert "keep root comment" in root_raw
assert "keep settings comment" in settings_raw
assert _load(fixture.config_path)["PreToolUse"] == []
current_settings = _load(fixture.settings_path)
assert current_settings["hooks"]["PostToolUse"] == []
assert current_settings["theme"] == "dark"
def test_uninstall_deletes_only_an_owned_empty_hook_file(
@pytest.mark.parametrize(
("mutation", "pattern"),
[
("config", "parse Elydora runtime config"),
("key", "canonical 32-byte"),
],
)
def test_status_surfaces_malformed_runtime_identity(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
mutation: str,
pattern: str,
) -> None:
fixture = DroidFixture(monkeypatch, tmp_path)
fixture.install()
assert fixture.config_path.read_text(encoding="utf-8").startswith(
"// Managed by Elydora"
target = fixture.runtime_config if mutation == "config" else fixture.private_key_path
target.write_text("{ malformed" if mutation == "config" else "invalid", encoding="utf-8")
with pytest.raises(ValueError, match=pattern):
fixture.plugin.status()
@pytest.mark.parametrize(
("root_config", "legacy_config", "settings", "local_settings", "pattern"),
[
("{ malformed", None, None, None, "parse Factory Droid hooks"),
([], None, None, None, "JSON object"),
('{"hooks":{"PreToolUse":[],"PreToolUse":[]}}', None, None, None, "duplicate"),
({"hooks": {"PreToolUse": None}}, None, None, None, "must be an array"),
({"hooks": {"PreToolUse": [None]}}, None, None, None, "must be an object"),
(
{"hooks": {"PreToolUse": [{"matcher": "[", "hooks": []}]}},
None,
None,
None,
"regular expression",
),
(
{"hooks": {"PreToolUse": [{"hooks": [{
"type": "command",
"command": "",
}]}]}},
None,
None,
None,
"non-empty",
),
(
{"hooks": {"PreToolUse": [{"hooks": [{
"type": "command",
"command": "user",
"timeout": 0,
}]}]}},
None,
None,
None,
"positive",
),
(None, "{ malformed", None, None, "legacy hooks"),
(None, None, {"hooks": None}, None, "JSON object"),
(None, None, None, {"hooksDisabled": "yes"}, "boolean"),
],
)
def test_install_preserves_malformed_sources_before_writes(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
root_config: Any,
legacy_config: Any,
settings: Any,
local_settings: Any,
pattern: str,
) -> None:
fixture = DroidFixture(
monkeypatch,
tmp_path,
root_config=root_config,
legacy_config=legacy_config,
settings=settings,
local_settings=local_settings,
)
fixture.plugin.uninstall(AGENT_ID)
assert not fixture.config_path.exists()
originals = {
path: path.read_text(encoding="utf-8")
for path in (
fixture.root_path,
fixture.legacy_path,
fixture.settings_path,
fixture.local_settings_path,
)
if path.exists()
}
with pytest.raises((ValueError, OSError), match=pattern):
fixture.install()
for path, source in originals.items():
assert path.read_text(encoding="utf-8") == source
assert not fixture.runtime_config.exists()
assert not fixture.root_path.exists() or fixture.root_path in originals
def test_uninstall_preserves_mixed_groups_and_lookalikes(
def test_unknown_events_and_extension_fields_remain_valid(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
fixture = DroidFixture(monkeypatch, tmp_path)
fixture.install()
root = _load(fixture.config_path)
group = next(
item for item in root["PreToolUse"]
if _managed_handler([item], fixture.guard_path)
fixture = DroidFixture(
monkeypatch,
tmp_path,
root_config={
"hooks": {
"FutureFactoryEvent": [{
"matcher": ".*",
"commandRegex": "^factory",
"owner": "user",
"hooks": [{
"type": "command",
"command": "user-command",
"timeout": 1,
"future": True,
}],
}],
},
},
)
fixture.install()
current = load_jsonc(fixture.root_path)
assert current["hooks"]["FutureFactoryEvent"][0]["owner"] == "user"
def test_uninstall_preserves_users_and_exact_ownership(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
fixture = DroidFixture(
monkeypatch,
tmp_path,
root_config={"hooks": {"Notification": []}},
)
fixture.install()
root = load_jsonc(fixture.root_path)
group = managed_group(root["hooks"], "PreToolUse", "guard.py")
assert group is not None
command = group["hooks"][0]["command"]
group["hooks"].append({"type": "command", "command": "user-command"})
group["owner"] = "user"
root["PreToolUse"].extend([
root["hooks"]["PreToolUse"].extend([
{
"matcher": "*",
"hooks": [{
@@ -339,108 +433,55 @@ def test_uninstall_preserves_mixed_groups_and_lookalikes(
}],
},
])
fixture.config_path.write_text(json.dumps(root, indent=2) + "\n", encoding="utf-8")
fixture.plugin.uninstall(AGENT_ID)
remaining = _load(fixture.config_path)
write_json(fixture.root_path, root)
fixture.plugin.uninstall("AGENT-1" if os.name == "nt" else AGENT_ID)
remaining = load_jsonc(fixture.root_path)
raw = json.dumps(remaining)
assert "user-command" in raw
assert "guard.py.backup" in raw
assert "agent-10" in raw
assert remaining["PostToolUse"] == []
assert "PostToolUse" not in remaining["hooks"]
@pytest.mark.parametrize(
("hooks", "legacy", "settings", "pattern"),
[
("{ malformed", None, None, "parse Factory Droid hooks"),
("[]", None, None, "JSON object"),
('{ "PreToolUse": [], "PreToolUse": [] }', None, None, "duplicate"),
({"PreToolUse": None}, None, None, "must be an array"),
({"PreToolUse": [None]}, None, None, "must be an object"),
({"PreToolUse": [{"matcher": "[", "hooks": []}]}, None, None, "regular expression"),
({"PreToolUse": [{"hooks": [{"type": "command", "command": 1}]}]}, None, None, "string"),
(None, "{ malformed", None, "legacy hooks"),
({"PreToolUse": []}, None, "{ malformed", "settings"),
(None, None, {"hooks": None}, "must contain a JSON object"),
],
)
def test_install_preserves_every_malformed_source_before_writes(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
hooks: Any,
legacy: Any,
settings: Any,
pattern: str,
) -> None:
fixture = DroidFixture(
monkeypatch,
tmp_path,
hooks=hooks,
legacy_hooks=legacy,
settings=settings,
)
targets = [
(fixture.config_path, hooks),
(fixture.legacy_path, legacy),
(fixture.settings_path, settings),
]
originals = {
path: path.read_text(encoding="utf-8") for path, value in targets if value is not None
}
with pytest.raises((ValueError, RuntimeError), match=pattern):
fixture.install()
for path, raw in originals.items():
assert path.read_text(encoding="utf-8") == raw
assert not fixture.audit_path.exists()
assert not fixture.runtime_config.exists()
assert not fixture.private_key_path.exists()
def test_install_rejects_missing_guard_before_creating_files(
def test_uninstall_removes_owned_empty_file_and_keeps_absence(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
fixture = DroidFixture(monkeypatch, tmp_path, create_guard=False)
with pytest.raises(FileNotFoundError, match="guard runtime is missing"):
fixture.install()
assert not fixture.config_path.exists()
assert not fixture.audit_path.exists()
assert not fixture.runtime_config.exists()
fixture = DroidFixture(monkeypatch, tmp_path / "installed")
fixture.install()
fixture.plugin.uninstall(AGENT_ID)
assert not fixture.root_path.exists()
empty = DroidFixture(monkeypatch, tmp_path / "empty")
empty.plugin.uninstall(AGENT_ID)
assert not empty.root_path.exists()
def test_transaction_rolls_back_all_files_and_cleans_staging(
@pytest.mark.parametrize("kind", ["factory", "hook", "runtime"])
def test_install_rejects_linked_paths_before_writes(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
kind: str,
) -> None:
fixture = DroidFixture(
monkeypatch,
tmp_path,
hooks={"PreToolUse": []},
settings={"hooks": {"PostToolUse": []}},
)
original_root = fixture.config_path.read_text(encoding="utf-8")
original_settings = fixture.settings_path.read_text(encoding="utf-8")
real_replace = os.replace
failed = False
def fail_settings_commit(source: Any, destination: Any) -> None:
nonlocal failed
if not failed and Path(destination) == fixture.settings_path:
failed = True
raise OSError("simulated settings commit failure")
real_replace(source, destination)
monkeypatch.setattr(droid_io.os, "replace", fail_settings_commit)
with pytest.raises(OSError, match="Write Factory Droid installation"):
fixture = DroidFixture(monkeypatch, tmp_path)
target = tmp_path / f"{kind}-target"
target.mkdir()
try:
if kind == "factory":
fixture.home_dir.mkdir(parents=True)
fixture.factory_dir.symlink_to(target, target_is_directory=True)
elif kind == "hook":
fixture.factory_dir.mkdir(parents=True)
target_file = target / "hooks.json"
write_json(target_file, {"hooks": {}})
fixture.root_path.symlink_to(target_file)
else:
fixture.home_dir.mkdir(parents=True)
(fixture.home_dir / ".elydora").symlink_to(
target,
target_is_directory=True,
)
except OSError as error:
pytest.skip(f"Symbolic links unavailable: {error}")
with pytest.raises(OSError, match="physical (directory|file)"):
fixture.install()
assert failed is True
assert fixture.config_path.read_text(encoding="utf-8") == original_root
assert fixture.settings_path.read_text(encoding="utf-8") == original_settings
assert not fixture.audit_path.exists()
assert not fixture.runtime_config.exists()
assert not fixture.private_key_path.exists()
staging = [
path for path in fixture.home_dir.rglob("*")
if path.suffix in {".tmp", ".rollback"}
]
assert staging == []
+137
View File
@@ -0,0 +1,137 @@
from __future__ import annotations
from pathlib import Path
import pytest
from droid_support import DroidFixture, write_json
def test_user_settings_disable_before_runtime_creation(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
fixture = DroidFixture(
monkeypatch,
tmp_path,
settings={"hooksDisabled": True},
)
with pytest.raises(ValueError, match="hooksDisabled"):
fixture.install()
assert not fixture.runtime_config.exists()
assert not fixture.root_path.exists()
def test_user_local_settings_override_base_settings(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
fixture = DroidFixture(
monkeypatch,
tmp_path,
settings={"hooksDisabled": True},
local_settings={"hooksDisabled": False},
)
fixture.install()
assert fixture.runtime_config.exists()
def test_legacy_direct_flags_remain_safety_compatible(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
fixture = DroidFixture(
monkeypatch,
tmp_path,
legacy_config={"hooksDisabled": True, "PreToolUse": []},
settings={"hooksDisabled": False},
)
with pytest.raises(ValueError, match="legacy hooks"):
fixture.install()
assert not fixture.runtime_config.exists()
def test_project_policy_has_extension_only_precedence(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
blocked = DroidFixture(
monkeypatch,
tmp_path / "blocked",
settings={"hooksDisabled": False},
project_settings={"hooksDisabled": True},
)
with pytest.raises(ValueError, match="project settings"):
blocked.install()
assert not blocked.runtime_config.exists()
allowed = DroidFixture(
monkeypatch,
tmp_path / "allowed",
settings={"hooksDisabled": True},
project_settings={"hooksDisabled": False},
)
allowed.install()
assert allowed.runtime_config.exists()
def test_project_local_settings_override_matching_base(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
fixture = DroidFixture(
monkeypatch,
tmp_path,
project_settings={"hooksDisabled": False},
project_local_settings={"hooksDisabled": True},
)
with pytest.raises(ValueError, match="project local settings"):
fixture.install()
def test_project_value_precedes_deeper_folder_value(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
fixture = DroidFixture(
monkeypatch,
tmp_path,
project_settings={"hooksDisabled": False},
)
child = fixture.workspace_dir / "packages" / "console"
child.mkdir(parents=True)
write_json(
child / ".factory" / "settings.json",
{"hooksDisabled": True},
)
monkeypatch.chdir(child)
fixture.install()
assert fixture.runtime_config.exists()
def test_system_managed_policy_blocks_user_hooks(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
fixture = DroidFixture(monkeypatch, tmp_path)
fixture.write_system_settings({"allowManagedHooksOnly": True})
with pytest.raises(ValueError, match="allowManagedHooksOnly"):
fixture.install()
assert not fixture.runtime_config.exists()
def test_malformed_read_only_project_policy_is_preserved(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
fixture = DroidFixture(
monkeypatch,
tmp_path,
project_settings="{ malformed",
)
before = fixture.project_settings_path.read_text(encoding="utf-8")
with pytest.raises(ValueError, match="project settings"):
fixture.install()
assert fixture.project_settings_path.read_text(encoding="utf-8") == before
assert not fixture.runtime_config.exists()
assert not fixture.root_path.exists()
+264
View File
@@ -0,0 +1,264 @@
from __future__ import annotations
import os
from pathlib import Path
import subprocess # nosec B404
import sys
from typing import Any, Dict
import pytest
from elydora.plugins import _transaction, droid
from elydora.plugins.droid_config import render_document, source_documents
from elydora.plugins.droid_installation import (
commit_droid_installation,
commit_droid_uninstall,
preflight_droid_installation,
prepare_droid_installation,
prepare_droid_uninstall,
)
from elydora.plugins.droid_io import read_sources
from droid_support import (
AGENT_ID,
VALID_PRIVATE_KEY,
DroidFixture,
assert_no_transaction_files,
assert_snapshot,
load_jsonc,
snapshot,
write_json,
)
def _prepare_installation(
fixture: DroidFixture,
**overrides: str,
):
config: Dict[str, Any] = dict(fixture.config)
config.update(overrides)
sources = read_sources()
paths = preflight_droid_installation(config, sources)
rendered = droid._render_installation( # noqa: SLF001
sources,
paths.guard_path,
paths.audit_path,
)
return prepare_droid_installation(config, sources, rendered)
def _managed_paths(fixture: DroidFixture) -> tuple[Path, ...]:
return (
fixture.guard_path,
fixture.runtime_config,
fixture.private_key_path,
fixture.audit_path,
fixture.root_path,
)
def test_install_rolls_back_runtime_after_late_hook_commit_failure(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
fixture = DroidFixture(monkeypatch, tmp_path)
prepared = _prepare_installation(fixture)
real_replace = _transaction.os.replace
failed = False
def fail_hook_commit(source: Any, destination: Any) -> None:
nonlocal failed
if not failed and Path(destination) == fixture.root_path:
failed = True
raise OSError("injected Droid hook commit failure")
real_replace(source, destination)
monkeypatch.setattr(_transaction.os, "replace", fail_hook_commit)
with pytest.raises(OSError, match="injected Droid hook commit failure"):
commit_droid_installation(prepared)
assert failed is True
for path in _managed_paths(fixture):
assert not path.exists()
assert_no_transaction_files(tmp_path)
def test_concurrent_active_hook_replacement_prevents_runtime_commit(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
fixture = DroidFixture(monkeypatch, tmp_path)
fixture.install()
before = snapshot(_managed_paths(fixture))
prepared = _prepare_installation(fixture, org_id="org-updated")
concurrent = '{"hooks":{"PreToolUse":[]},"owner":"concurrent"}\n'
fixture.root_path.write_text(concurrent, encoding="utf-8")
with pytest.raises(OSError, match="hooks changed during Install Factory Droid"):
commit_droid_installation(prepared)
for path, source in before.items():
if path != fixture.root_path:
assert path.read_text(encoding="utf-8") == source
assert fixture.root_path.read_text(encoding="utf-8") == concurrent
assert_no_transaction_files(tmp_path)
def test_concurrent_inactive_local_source_creation_is_detected(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
fixture = DroidFixture(monkeypatch, tmp_path)
fixture.install()
before = snapshot(_managed_paths(fixture))
prepared = _prepare_installation(fixture, org_id="org-updated")
concurrent = '{"hooksDisabled":true}\n'
fixture.local_settings_path.write_text(concurrent, encoding="utf-8")
with pytest.raises(OSError, match="local settings changed during Install"):
commit_droid_installation(prepared)
assert_snapshot(before)
assert fixture.local_settings_path.read_text(encoding="utf-8") == concurrent
assert_no_transaction_files(tmp_path)
def test_concurrent_project_policy_change_is_detected(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
fixture = DroidFixture(
monkeypatch,
tmp_path,
project_settings={"hooksDisabled": False},
)
fixture.install()
before = snapshot(_managed_paths(fixture))
prepared = _prepare_installation(fixture, org_id="org-updated")
concurrent = '{"hooksDisabled":true}\n'
fixture.project_settings_path.write_text(concurrent, encoding="utf-8")
with pytest.raises(OSError, match="project settings changed during Install"):
commit_droid_installation(prepared)
assert_snapshot(before)
assert fixture.project_settings_path.read_text(encoding="utf-8") == concurrent
assert_no_transaction_files(tmp_path)
def test_same_content_replacement_is_rejected_by_physical_identity(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
fixture = DroidFixture(monkeypatch, tmp_path)
fixture.install()
before = snapshot(_managed_paths(fixture))
sources = read_sources()
original = fixture.root_path.read_text(encoding="utf-8")
fixture.root_path.unlink()
fixture.root_path.write_text(original, encoding="utf-8")
config: Dict[str, Any] = dict(fixture.config)
config["org_id"] = "org-updated"
paths = preflight_droid_installation(config, sources)
rendered = droid._render_installation( # noqa: SLF001
sources,
paths.guard_path,
paths.audit_path,
)
prepared = prepare_droid_installation(config, sources, rendered)
with pytest.raises(OSError, match="hooks changed during Install"):
commit_droid_installation(prepared)
assert fixture.root_path.read_text(encoding="utf-8") == original
for path, source in before.items():
if path != fixture.root_path:
assert path.read_text(encoding="utf-8") == source
assert_no_transaction_files(tmp_path)
def test_orphaned_runtime_is_preserved_without_verifiable_identity(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
fixture = DroidFixture(monkeypatch, tmp_path)
fixture.agent_dir.mkdir(parents=True)
fixture.guard_path.write_text("orphaned guard\n", encoding="utf-8")
with pytest.raises(ValueError, match="identity cannot be verified"):
fixture.install()
assert fixture.guard_path.read_text(encoding="utf-8") == "orphaned guard\n"
assert not fixture.root_path.exists()
def test_uninstall_rolls_back_all_hook_documents(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
fixture = DroidFixture(monkeypatch, tmp_path)
fixture.install()
installed = load_jsonc(fixture.root_path)
write_json(
fixture.settings_path,
{"hooks": installed["hooks"], "owner": "user"},
)
paths = (*_managed_paths(fixture), fixture.settings_path)
before = snapshot(paths)
sources = read_sources()
rendered = [
render_document(document, AGENT_ID, {})
for document in source_documents(sources)
]
prepared = prepare_droid_uninstall(rendered)
real_replace = _transaction.os.replace
failed = False
def fail_second_source(source: Any, destination: Any) -> None:
nonlocal failed
if not failed and Path(destination) == fixture.settings_path:
failed = True
raise OSError("injected Droid uninstall failure")
real_replace(source, destination)
monkeypatch.setattr(_transaction.os, "replace", fail_second_source)
with pytest.raises(OSError, match="injected Droid uninstall failure"):
commit_droid_uninstall(prepared)
assert failed is True
assert_snapshot(before)
assert_no_transaction_files(tmp_path)
def test_cli_preflight_blocks_disabled_hooks_before_runtime_creation(
tmp_path: Path,
) -> None:
home_dir = tmp_path / "cli-home"
settings_path = home_dir / ".factory" / "settings.json"
key_path = tmp_path / "private.key"
write_json(settings_path, {"hooksDisabled": True})
key_path.write_text(
VALID_PRIVATE_KEY,
encoding="utf-8",
)
environment = {
**os.environ,
"HOME": str(home_dir),
"USERPROFILE": str(home_dir),
}
result = subprocess.run( # nosec B603
[
sys.executable,
"-m",
"elydora.cli",
"install",
"--agent",
"droid",
"--org_id",
"org-1",
"--agent_id",
AGENT_ID,
"--private_key_file",
str(key_path),
"--kid",
"kid-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 "hooksDisabled" in result.stderr
assert not (home_dir / ".elydora").exists()