fix(python): mirror transactional Auggie hooks

This commit is contained in:
ZacharyZhang-NY committed 2026-07-20 09:57:11 -04:00
1 parent 30257b2c76
commit dccec10fea
11 files changed
+1452 -510

No files matched your search

+55 -191
View File
@@ -2,37 +2,27 @@
from __future__ import annotations
import os
import shutil
import subprocess # nosec B404
from typing import List
from ._file_io import (
read_json as _read_json,
regular_file_exists as _regular_file_exists,
remove_file as _remove_file,
require_runtime as _require_runtime,
write_json_atomic as _write_json_atomic,
write_text_atomic as _write_text_atomic,
)
from .augment_contract import (
AGENT_KEY,
AUDIT_SCRIPT,
AugmentDocument,
AugmentHooks,
JsonObject,
RuntimeContract,
build_handler,
build_wrapper,
elydora_dir,
read_hooks,
remove_managed_hooks,
resolve_config_path,
render_augment_document,
runtime_contracts,
wrapper_paths,
)
from .augment_installation import (
AugmentRuntimePaths,
commit_augment_installation,
commit_augment_uninstall,
preflight_augment_installation,
prepare_augment_installation,
prepare_augment_uninstall,
)
from .augment_io import augment_runtime_files_exist, read_augment_document
from .base import AgentPlugin, InstallConfig, PluginStatus
from .hook_template import generate_hook_script
_REGEX_VALIDATION_TIMEOUT_SECONDS = 10
@@ -105,196 +95,70 @@ def _validate_matchers(hooks: AugmentHooks) -> None:
_validate_matcher(node_path, label, matcher)
def _read_config() -> AugmentDocument:
config_path = resolve_config_path()
root = _read_json(config_path, "Auggie settings")
if root is None:
return AugmentDocument(False, config_path, {}, {})
return AugmentDocument(True, config_path, root, read_hooks(root))
def _same_agent_id(left: str, right: str) -> bool:
return os.path.normcase(left) == os.path.normcase(right)
def _runtime_files_exist(contracts: List[RuntimeContract]) -> bool:
root = elydora_dir()
try:
with os.scandir(root) as iterator:
entries = sorted(iterator, key=lambda entry: entry.name)
except FileNotFoundError:
return False
except OSError as error:
raise OSError(f"Read Elydora runtime directory at {root}: {error}") from error
for contract in contracts:
entry = next(
(
candidate
for candidate in entries
if _same_agent_id(candidate.name, contract.agent_id)
),
None,
)
if entry is None:
continue
try:
if not entry.is_dir(follow_symlinks=False):
continue
except OSError as error:
raise OSError(
f"Read Elydora runtime entry at {entry.path}: {error}"
) from error
runtime_config_path = os.path.join(entry.path, "config.json")
runtime_config = _read_json(runtime_config_path, "Elydora runtime config")
if runtime_config is None:
continue
agent_name = runtime_config.get("agent_name")
if not isinstance(agent_name, str):
raise ValueError(
f"Elydora runtime config at {runtime_config_path} field "
'"agent_name" must be a string'
)
if agent_name != AGENT_KEY:
continue
files = (
(contract.guard_path, "Elydora guard runtime"),
(contract.audit_path, "Elydora audit runtime"),
(contract.guard_wrapper_path, "Auggie guard wrapper"),
(contract.audit_wrapper_path, "Auggie audit wrapper"),
)
return all(_regular_file_exists(file_path, label) for file_path, label in files)
return False
def _installed_hooks(hooks: AugmentHooks, paths: AugmentRuntimePaths) -> AugmentHooks:
cleaned, _ = remove_managed_hooks(hooks)
return {
**cleaned,
"PreToolUse": [
*cleaned.get("PreToolUse", []),
{
"matcher": ".*",
"hooks": [build_handler(paths.guard_wrapper_path)],
},
],
"PostToolUse": [
*cleaned.get("PostToolUse", []),
{
"matcher": ".*",
"hooks": [build_handler(paths.audit_wrapper_path)],
},
],
}
class AugmentPlugin(AgentPlugin):
"""Install Elydora into Auggie's global user settings."""
manages_guard_runtime = True
def preflight_install(self, config: InstallConfig) -> None:
document = read_augment_document()
_validate_matchers(document.hooks)
preflight_augment_installation(config, document)
def install(self, config: InstallConfig) -> None:
agent_id = config.get("agent_id", "")
if not agent_id:
raise ValueError("agent_id is required")
source = _read_config()
_validate_matchers(source.hooks)
guard_path = config.get("guard_script_path", "")
_require_runtime(guard_path, "Elydora guard runtime")
agent_directory = os.path.join(elydora_dir(), agent_id)
audit_path = os.path.join(agent_directory, AUDIT_SCRIPT)
wrappers = wrapper_paths(agent_id)
cleaned, _ = remove_managed_hooks(source.hooks)
hooks = {
**cleaned,
"PreToolUse": [
*cleaned.get("PreToolUse", []),
{
"matcher": ".*",
"hooks": [build_handler(wrappers.guard_path)],
},
],
"PostToolUse": [
*cleaned.get("PostToolUse", []),
{
"matcher": ".*",
"hooks": [build_handler(wrappers.audit_path)],
},
],
}
runtime_config: JsonObject = {
"org_id": config.get("org_id", ""),
"agent_id": agent_id,
"kid": config.get("kid", ""),
"base_url": config.get("base_url", "https://api.elydora.com"),
"token": config.get("token", ""),
"agent_name": AGENT_KEY,
}
audit_script = generate_hook_script(
org_id=config.get("org_id", ""),
agent_id=agent_id,
kid=config.get("kid", ""),
base_url=config.get("base_url", "https://api.elydora.com"),
)
_write_json_atomic(
os.path.join(agent_directory, "config.json"),
runtime_config,
0o600,
"Elydora runtime config",
)
_write_text_atomic(
os.path.join(agent_directory, "private.key"),
config.get("private_key", ""),
0o600,
"Elydora private key",
)
_write_text_atomic(
audit_path,
audit_script,
0o700,
"Elydora audit runtime",
)
_write_text_atomic(
wrappers.guard_path,
build_wrapper(guard_path),
0o700,
"Auggie guard wrapper",
)
_write_text_atomic(
wrappers.audit_path,
build_wrapper(audit_path),
0o700,
"Auggie audit wrapper",
)
_write_json_atomic(
source.config_path,
{**source.root, "hooks": hooks},
0o600,
"Auggie settings",
document = read_augment_document()
_validate_matchers(document.hooks)
paths = preflight_augment_installation(config, document)
rendered = render_augment_document(
document, _installed_hooks(document.hooks, paths)
)
changes = prepare_augment_installation(config, paths, rendered)
commit_augment_installation(changes)
print("Auggie: user-level PreToolUse and PostToolUse hooks installed.")
def uninstall(self, agent_id: str = "") -> None:
source = _read_config()
if not source.exists:
document = read_augment_document()
if not document.exists:
return
hooks, changed = remove_managed_hooks(source.hooks, agent_id)
hooks, changed = remove_managed_hooks(document.hooks, agent_id)
if not changed:
return
root = dict(source.root)
if hooks:
root["hooks"] = hooks
else:
root.pop("hooks", None)
if root:
_write_json_atomic(
source.config_path,
root,
0o600,
"Auggie settings",
)
else:
_remove_file(source.config_path, "Auggie settings")
rendered = render_augment_document(document, hooks)
commit_augment_uninstall(prepare_augment_uninstall(rendered))
def status(self) -> PluginStatus:
source = _read_config()
contracts = runtime_contracts(source.hooks)
if not contracts:
return PluginStatus(
installed=False,
agent=AGENT_KEY,
details="Not installed",
)
installed = _runtime_files_exist(contracts)
document = read_augment_document()
contracts = runtime_contracts(document.hooks)
configured = bool(contracts)
installed = configured and augment_runtime_files_exist(contracts)
details = (
f"Config: {source.config_path}"
f"Config: {document.config_path}"
if installed
else (
f"Configured at {source.config_path}; "
"runtime scripts or wrappers missing"
)
else f"Configured at {document.config_path}; managed contract incomplete"
)
return PluginStatus(
installed=installed,
agent=AGENT_KEY,
details=details,
details=details if configured else "Not installed",
)
@@ -3,11 +3,14 @@
from __future__ import annotations
from dataclasses import dataclass
import json
import math
import os
import sys
from typing import Any, Dict, List, Optional, Set, Tuple
from ._strict_json import parse_json_object
AGENT_KEY = "augment"
GUARD_SCRIPT = "guard.py"
@@ -37,6 +40,14 @@ class AugmentDocument:
config_path: str
root: JsonObject
hooks: AugmentHooks
raw: Optional[str] = None
@dataclass(frozen=True)
class RenderedAugmentDocument:
document: AugmentDocument
changed: bool
next_source: Optional[str] = None
@dataclass(frozen=True)
@@ -66,8 +77,7 @@ def resolve_config_path() -> str:
return os.path.join(home_dir(), ".augment", "settings.json")
def wrapper_paths(agent_id: str) -> WrapperPaths:
agent_directory = os.path.join(elydora_dir(), agent_id)
def wrapper_paths(agent_directory: str) -> WrapperPaths:
return WrapperPaths(
guard_path=os.path.join(agent_directory, GUARD_WRAPPER),
audit_path=os.path.join(agent_directory, AUDIT_WRAPPER),
@@ -273,6 +283,34 @@ def read_hooks(root: JsonObject) -> AugmentHooks:
return hooks
def parse_augment_document(config_path: str, raw: str) -> AugmentDocument:
root = parse_json_object(raw, f"Auggie user settings at {config_path}")
return AugmentDocument(True, config_path, root, read_hooks(root), raw)
def create_augment_document(config_path: str) -> AugmentDocument:
return AugmentDocument(False, config_path, {}, {})
def render_augment_document(
document: AugmentDocument, hooks: AugmentHooks
) -> RenderedAugmentDocument:
if hooks == document.hooks:
return RenderedAugmentDocument(document, False)
if not document.exists and not hooks:
return RenderedAugmentDocument(document, False)
root = dict(document.root)
if hooks:
root["hooks"] = hooks
else:
root.pop("hooks", None)
if not root:
return RenderedAugmentDocument(document, True)
next_source = json.dumps(root, indent=2, ensure_ascii=False) + "\n"
parse_augment_document(document.config_path, next_source)
return RenderedAugmentDocument(document, next_source != document.raw, next_source)
def _remove_managed(
groups: List[JsonObject],
wrapper_name: str,
@@ -0,0 +1,203 @@
"""Transactional Auggie hook and runtime installation."""
from __future__ import annotations
from dataclasses import dataclass
import json
import os
from typing import List, Optional
from elydora._runtime_paths import resolve_agent_directory
from ._managed_files import MAX_CONFIG_BYTES, MAX_SECRET_BYTES, MAX_SOURCE_BYTES
from ._transaction import FileChange, file_change, write_changes
from .augment_contract import (
AGENT_KEY,
AUDIT_SCRIPT,
GUARD_SCRIPT,
AugmentDocument,
RenderedAugmentDocument,
build_wrapper,
elydora_dir,
wrapper_paths,
)
from .augment_io import (
rendered_change,
validate_api_origin,
validate_private_key,
validate_runtime_tree,
)
from .base import InstallConfig
from .guard_template import generate_guard_script
from .hook_template import generate_hook_script
@dataclass(frozen=True)
class AugmentRuntimePaths:
agent_id: str
agent_directory: str
guard_path: str
audit_path: str
guard_wrapper_path: str
audit_wrapper_path: str
def _same_path(left: str, right: str) -> bool:
return os.path.normcase(os.path.abspath(left)) == os.path.normcase(
os.path.abspath(right)
)
def _runtime_config(config: InstallConfig, agent_id: str) -> dict:
value = {
"org_id": config.get("org_id", ""),
"agent_id": agent_id,
"kid": config.get("kid", ""),
"base_url": config.get("base_url", "https://api.elydora.com"),
"agent_name": AGENT_KEY,
}
token = config.get("token")
if token:
value["token"] = token
return value
def _json_source(value: dict) -> str:
return json.dumps(value, indent=2) + "\n"
def _agent_paths(config: InstallConfig) -> AugmentRuntimePaths:
agent_id = config.get("agent_id", "")
if not agent_id:
raise ValueError("agent_id is required")
agent_directory = resolve_agent_directory(elydora_dir(), agent_id)
guard_path = os.path.join(agent_directory, GUARD_SCRIPT)
audit_path = os.path.join(agent_directory, AUDIT_SCRIPT)
if not _same_path(config.get("guard_script_path", ""), guard_path):
raise ValueError(
f"Elydora guard runtime must use the managed agent directory: {guard_path}"
)
wrappers = wrapper_paths(agent_directory)
return AugmentRuntimePaths(
agent_id,
agent_directory,
guard_path,
audit_path,
wrappers.guard_path,
wrappers.audit_path,
)
def _validate_install_config(config: InstallConfig) -> None:
for field in ("org_id", "agent_id", "kid", "private_key", "base_url"):
value = config.get(field)
if not isinstance(value, str) or not value:
raise ValueError(f"{field} is required")
if config.get("agent_name") != AGENT_KEY:
raise ValueError(
f"Augment Code CLI installation requires agent_name {AGENT_KEY}"
)
validate_private_key(config["private_key"])
validate_api_origin(config["base_url"])
if "token" in config:
token = config["token"]
if not isinstance(token, str) or not token:
raise ValueError("token must be a non-empty string when provided")
_agent_paths(config)
def preflight_augment_installation(
config: InstallConfig, document: AugmentDocument
) -> AugmentRuntimePaths:
if not document.config_path:
raise ValueError("Augment Code CLI installation requires a settings path")
_validate_install_config(config)
paths = _agent_paths(config)
validate_runtime_tree(paths.agent_directory, paths.agent_id)
return paths
def _runtime_change(
file_path: str,
label: str,
next_source: str,
mode: int,
maximum_bytes: int = MAX_SOURCE_BYTES,
) -> Optional[FileChange]:
return file_change(file_path, label, next_source, mode, maximum_bytes)
def _present(changes: List[Optional[FileChange]]) -> List[FileChange]:
return [change for change in changes if change is not None]
def prepare_augment_installation(
config: InstallConfig,
paths: AugmentRuntimePaths,
rendered: RenderedAugmentDocument,
) -> List[FileChange]:
if not rendered.changed and rendered.document.raw is None:
raise ValueError("Auggie hook installation did not produce a settings document")
validate_runtime_tree(paths.agent_directory, paths.agent_id)
guard_script = generate_guard_script(AGENT_KEY, paths.agent_id)
audit_script = generate_hook_script(
org_id=config.get("org_id", ""),
agent_id=paths.agent_id,
kid=config.get("kid", ""),
base_url=config.get("base_url", "https://api.elydora.com"),
native_payload=True,
agent_name=AGENT_KEY,
)
changes = _present(
[
_runtime_change(
paths.guard_path, "Elydora guard runtime", guard_script, 0o700
),
_runtime_change(
os.path.join(paths.agent_directory, "config.json"),
"Elydora runtime config",
_json_source(_runtime_config(config, paths.agent_id)),
0o600,
MAX_CONFIG_BYTES,
),
_runtime_change(
os.path.join(paths.agent_directory, "private.key"),
"Elydora private key",
config.get("private_key", ""),
0o600,
MAX_SECRET_BYTES,
),
_runtime_change(
paths.audit_path, "Elydora audit runtime", audit_script, 0o700
),
_runtime_change(
paths.guard_wrapper_path,
"Auggie guard wrapper",
build_wrapper(paths.guard_path),
0o700,
),
_runtime_change(
paths.audit_wrapper_path,
"Auggie audit wrapper",
build_wrapper(paths.audit_path),
0o700,
),
rendered_change(rendered),
]
)
validate_runtime_tree(paths.agent_directory, paths.agent_id)
return changes
def commit_augment_installation(changes: List[FileChange]) -> None:
write_changes(changes, "Install Augment Code CLI hooks")
def prepare_augment_uninstall(
rendered: RenderedAugmentDocument,
) -> List[FileChange]:
return _present([rendered_change(rendered)])
def commit_augment_uninstall(changes: List[FileChange]) -> None:
write_changes(changes, "Uninstall Augment Code CLI hooks")
+266
View File
@@ -0,0 +1,266 @@
"""Auggie settings discovery and managed runtime I/O."""
from __future__ import annotations
import base64
import os
from typing import Any, List, Optional
import urllib.parse
from ._managed_files import (
MAX_CONFIG_BYTES,
MAX_SECRET_BYTES,
physical_directory_exists,
physical_file_exists,
read_physical_file,
)
from ._strict_json import JsonObject, parse_json_object
from ._transaction import FileChange, source_change, write_changes
from .augment_contract import (
AGENT_KEY,
AUDIT_SCRIPT,
AUDIT_WRAPPER,
GUARD_SCRIPT,
GUARD_WRAPPER,
AugmentDocument,
RenderedAugmentDocument,
RuntimeContract,
build_wrapper,
create_augment_document,
elydora_dir,
parse_augment_document,
resolve_config_path,
)
def _same_path(left: str, right: str) -> bool:
return os.path.normcase(os.path.abspath(left)) == os.path.normcase(
os.path.abspath(right)
)
def _same_agent_id(left: str, right: str) -> bool:
return os.path.normcase(left) == os.path.normcase(right)
def read_augment_document() -> AugmentDocument:
config_path = resolve_config_path()
physical_directory_exists(
os.path.dirname(config_path), "Auggie configuration directory"
)
snapshot = read_physical_file(config_path, "Auggie user settings", MAX_CONFIG_BYTES)
if snapshot is None:
return create_augment_document(config_path)
return parse_augment_document(config_path, snapshot.contents)
def rendered_change(
rendered: RenderedAugmentDocument,
) -> Optional[FileChange]:
if not rendered.changed:
return None
return source_change(
rendered.document.config_path,
"Auggie user settings",
rendered.document.raw,
rendered.next_source,
0o600,
MAX_CONFIG_BYTES,
)
def write_augment_document(rendered: RenderedAugmentDocument) -> None:
change = rendered_change(rendered)
if change is not None:
write_changes([change], "Uninstall Augment Code CLI hooks")
def validate_api_origin(value: str, label: str = "base_url") -> None:
try:
parsed = urllib.parse.urlsplit(value)
hostname = parsed.hostname
parsed.port
except ValueError as error:
raise ValueError(f"{label} must be an absolute HTTP or HTTPS URL") from error
invalid_character = "\\" in value or any(
character.isspace() or ord(character) < 32 for character in value
)
if (
parsed.scheme not in ("http", "https")
or not parsed.netloc
or hostname is None
or invalid_character
):
raise ValueError(f"{label} must be an absolute HTTP or HTTPS URL")
if (
parsed.username is not None
or parsed.password is not None
or parsed.query
or parsed.fragment
):
raise ValueError(
f"{label} must exclude credentials, query parameters, and fragments"
)
def validate_private_key(value: str, label: str = "private_key") -> None:
try:
padded = value + "=" * ((4 - len(value) % 4) % 4)
seed = base64.b64decode(
padded.replace("-", "+").replace("_", "/"), validate=True
)
canonical = base64.urlsafe_b64encode(seed).rstrip(b"=").decode("ascii")
except (ValueError, UnicodeEncodeError) as error:
raise ValueError(
f"{label} must be a canonical 32-byte base64url value"
) from error
if len(seed) != 32 or canonical != value:
raise ValueError(f"{label} must be a canonical 32-byte base64url value")
def _require_non_empty_string(value: Any, field: str, config_path: str) -> str:
if not isinstance(value, str) or not value.strip():
raise ValueError(f"Elydora runtime config {field} is invalid: {config_path}")
return value
def _validate_runtime_config(
config: JsonObject, expected_agent_id: str, config_path: str
) -> None:
supported = {"org_id", "agent_id", "kid", "base_url", "token", "agent_name"}
extra = next((key for key in config if key not in supported), None)
if extra is not None:
raise ValueError(
f'Elydora runtime config has unsupported field "{extra}": {config_path}'
)
_require_non_empty_string(config.get("org_id"), "org_id", config_path)
_require_non_empty_string(config.get("kid"), "kid", config_path)
agent_id = _require_non_empty_string(
config.get("agent_id"), "agent_id", config_path
)
if (
not _same_agent_id(agent_id, expected_agent_id)
or config.get("agent_name") != AGENT_KEY
):
raise ValueError(
f"Elydora runtime identity does not match Auggie hooks: {config_path}"
)
if "token" in config:
_require_non_empty_string(config.get("token"), "token", config_path)
base_url = _require_non_empty_string(
config.get("base_url"), "base_url", config_path
)
validate_api_origin(base_url, "Elydora runtime config base_url")
def _read_runtime_config(file_path: str) -> Optional[JsonObject]:
snapshot = read_physical_file(file_path, "Elydora runtime config", MAX_CONFIG_BYTES)
if snapshot is None:
return None
return parse_json_object(
snapshot.contents, f"Elydora runtime config at {file_path}"
)
def validate_runtime_tree(agent_directory: str, agent_id: str) -> None:
root = elydora_dir()
if not physical_directory_exists(root, "Elydora runtime directory"):
return
if not physical_directory_exists(
agent_directory, "Elydora agent runtime directory"
):
return
config_path = os.path.join(agent_directory, "config.json")
config = _read_runtime_config(config_path)
artifacts = (
("private.key", "Elydora private key"),
(GUARD_SCRIPT, "Elydora guard runtime"),
(AUDIT_SCRIPT, "Elydora audit runtime"),
(GUARD_WRAPPER, "Auggie guard wrapper"),
(AUDIT_WRAPPER, "Auggie audit wrapper"),
("chain-state.json", "Elydora chain state"),
("status-cache.json", "Elydora status cache"),
("error.log", "Elydora error log"),
)
artifact_exists = any(
physical_file_exists(os.path.join(agent_directory, name), label)
for name, label in artifacts
)
if config is None:
if artifact_exists:
raise ValueError(
"Elydora runtime identity cannot be verified without config.json: "
f"{agent_directory}"
)
return
configured_id = config.get("agent_id")
if (
not isinstance(configured_id, str)
or not _same_agent_id(configured_id, agent_id)
or config.get("agent_name") != AGENT_KEY
):
raise ValueError(
"Elydora runtime config identity does not match Auggie agent "
f"{agent_id}: {config_path}"
)
def _runtime_contract_exists(contract: RuntimeContract) -> bool:
root = elydora_dir()
agent_directory = os.path.dirname(contract.guard_path)
if (
not _same_path(os.path.dirname(agent_directory), root)
or not _same_path(
contract.audit_path, os.path.join(agent_directory, AUDIT_SCRIPT)
)
or not _same_path(
contract.guard_wrapper_path,
os.path.join(agent_directory, GUARD_WRAPPER),
)
or not _same_path(
contract.audit_wrapper_path,
os.path.join(agent_directory, AUDIT_WRAPPER),
)
):
return False
if not physical_directory_exists(root, "Elydora runtime directory"):
return False
if not physical_directory_exists(
agent_directory, "Elydora agent runtime directory"
):
return False
config_path = os.path.join(agent_directory, "config.json")
key_path = os.path.join(agent_directory, "private.key")
config = _read_runtime_config(config_path)
key = read_physical_file(key_path, "Elydora private key", MAX_SECRET_BYTES)
guard = read_physical_file(contract.guard_path, "Elydora guard runtime")
audit = read_physical_file(contract.audit_path, "Elydora audit runtime")
guard_wrapper = read_physical_file(
contract.guard_wrapper_path, "Auggie guard wrapper"
)
audit_wrapper = read_physical_file(
contract.audit_wrapper_path, "Auggie audit wrapper"
)
if any(
item is None
for item in (config, key, guard, audit, guard_wrapper, audit_wrapper)
):
return False
assert config is not None
assert key is not None
assert guard is not None
assert audit is not None
assert guard_wrapper is not None
assert audit_wrapper is not None
_validate_runtime_config(config, contract.agent_id, config_path)
validate_private_key(key.contents, "Elydora private key")
return (
bool(guard.contents)
and bool(audit.contents)
and guard_wrapper.contents == build_wrapper(contract.guard_path)
and audit_wrapper.contents == build_wrapper(contract.audit_path)
)
def augment_runtime_files_exist(contracts: List[RuntimeContract]) -> bool:
return any(_runtime_contract_exists(contract) for contract in contracts)