Files
ai-agent/backend/test_plugin_harness_hooks.py
gabrielvidalandClaude Opus 5.5 94c07968d3 feat(plugins): harnessHooks[] — plugins hook into the agent harness; gcloud_reauth leaves the core
A live plugin declares harnessHooks[]: declarative rules (command/output
regex → additionalContext, evaluated by the stdlib sidecar/plugin_hooks.py,
no plugin code — owner-approvable) or .py script hooks (operator approval).
Regexes compiled + ReDoS-checked at install, paths kept inside the plugin,
the declaration in the approval fingerprint (unchanged for plugins without
it). Placed by the plugin's where/profiles/workers settings; guests'
computers and scoped runs only get guestAllowed hooks.

The lab reads /data/plugins/live-hooks (PluginStore.sync_hooks on every
owner plugin change and at start); a worker gets its filtered copy in the
/sync bundle's hooks map (~/.ai-agent-worker/hooks). _claude_settings wires
them in place of the hard-coded gcloud hook; sidecar/gcloud_reauth.py and its
test are gone — the gcloud-reauth plugin (ai-agent-plugins) carries it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 19:12:32 +01:00

226 lines
12 KiB
Python

"""``harnessHooks[]``: hooks a live plugin adds to the agent harness
(plugins/harness_hooks.py) — manifest validation, approval, scope, the lab's
``live-hooks/`` copy and a worker's ``/sync`` bundle (docs/plugins.md →
"Harness hooks")."""
from __future__ import annotations
import base64
import json
import os
import pathlib
import tempfile
import unittest
TMP = pathlib.Path(tempfile.mkdtemp())
for k, v in {"DB_PATH": TMP / "x.db", "TRANSCRIPTS_DIR": TMP / "t", "WORKSPACE": TMP, "REPO_DIR": TMP,
"META_PATH": TMP / "meta.json", "USERS_PATH": TMP / "users.json",
"PROJECTS_DIR": TMP / "projects", "SIDECAR_TOKEN": "", "PI_TRANSCRIPTS_DIR": ""}.items():
os.environ.setdefault(k, str(v))
from plugins import harness_hooks as hh # noqa: E402
from plugins.manifest import (ManifestError, capability_fingerprint, capability_summary, # noqa: E402
requires_operator, validate_manifest)
from plugins.store import OWNER_UID, PluginStore # noqa: E402
from workers import labsync # noqa: E402
GCLOUD = {
"id": "gcloud-expired", "harness": "claude", "event": "PostToolUse", "matcher": "Bash",
"excludeCommandRegex": "gcloud\\s+auth\\b",
"outputRegex": "invalid_rapt|reauthentication failed|reauthentication required"
"|gcloud\\s+auth\\s+login|gcloud\\s+auth\\s+application-default\\s+login",
"message": "Google sign-in expired on this machine: use the gcloud-login skill "
"(it sends Gabriel a form; he never runs a command), then retry.",
}
SCOPE_FIELDS = [
{"key": "profiles", "label": "Profiles", "type": "list", "default": ["work"]},
{"key": "where", "label": "Where", "type": "select", "default": "workers",
"options": ["workers", "lab", "all"]},
{"key": "workers", "label": "Workers", "type": "list", "default": []},
]
def _plugin(root: pathlib.Path, hooks: list, pid: str = "hooky", fields=None,
files: dict | None = None) -> pathlib.Path:
d = root / pid
d.mkdir(parents=True, exist_ok=True)
(d / "plugin.json").write_text(json.dumps({
"schema": 1, "id": pid, "name": pid.title(), "harnessHooks": hooks,
"settings": {"fields": SCOPE_FIELDS if fields is None else fields}}))
for rel, text in (files or {}).items():
(d / rel).parent.mkdir(parents=True, exist_ok=True)
(d / rel).write_text(text)
return d
class TestManifest(unittest.TestCase):
def setUp(self):
self.td = pathlib.Path(tempfile.mkdtemp())
def _errors(self, hooks, **kw) -> str:
with self.assertRaises(ManifestError) as cm:
validate_manifest(_plugin(self.td, hooks, **kw))
return str(cm.exception)
def test_declarative_rule(self):
mf = validate_manifest(_plugin(self.td, [GCLOUD]))
(h,) = mf["harnessHooks"]
self.assertEqual(h["event"], "PostToolUse")
self.assertTrue(h["ignoreCase"])
self.assertFalse(h["guestAllowed"])
self.assertFalse(requires_operator(mf)) # no code: the owner approves
labels = [c["label"] for c in capability_summary(mf) if c["kind"] == "harnessHook"]
self.assertIn("no code runs", labels[0])
def test_script_hook_needs_the_operator(self):
mf = validate_manifest(_plugin(self.td, [
{"id": "custom", "event": "PostToolUse", "matcher": "Bash", "script": "hooks/my_hook.py"}],
files={"hooks/my_hook.py": "print()\n"}))
self.assertEqual(mf["harnessHooks"][0]["timeoutSec"], 10)
self.assertTrue(requires_operator(mf))
self.assertTrue(any(c.get("privileged") for c in capability_summary(mf)
if c["kind"] == "harnessHook"))
def test_refused(self):
self.assertIn("nested quantifiers", self._errors([dict(GCLOUD, outputRegex="(a+)+$")]))
self.assertIn("invalid regex", self._errors([dict(GCLOUD, commandRegex="(")]))
self.assertIn("matcher", self._errors([{k: v for k, v in GCLOUD.items() if k != "matcher"}]))
self.assertIn("message", self._errors([dict(GCLOUD, message="")]))
self.assertIn("needs commandRegex or outputRegex",
self._errors([{"id": "x", "event": "PostToolUse", "matcher": "Bash", "message": "m"}]))
self.assertIn("event", self._errors([dict(GCLOUD, event="Stop")])) # declarative: tool events
self.assertIn("harness", self._errors([dict(GCLOUD, harness="pi")]))
self.assertIn("unknown keys", self._errors([dict(GCLOUD, shell="rm -rf /")]))
self.assertIn("duplicate", self._errors([GCLOUD, GCLOUD]))
self.assertIn("no output yet", self._errors([dict(GCLOUD, event="PreToolUse")]))
base = {"id": "s", "event": "Stop"}
self.assertIn("must not contain", self._errors([dict(base, script="../x.py")]))
self.assertIn("must not contain", self._errors([dict(base, script="a/../../x.py")]))
self.assertIn("not found", self._errors([dict(base, script="hooks/none.py")]))
self.assertIn(".py", self._errors([dict(base, script="hooks/run.sh")]))
self.assertIn("takes no message", self._errors(
[dict(base, script="h.py", message="m")], files={"h.py": ""}))
def test_fingerprint(self):
a = validate_manifest(_plugin(self.td, [GCLOUD], pid="a"))
b = validate_manifest(_plugin(self.td, [dict(GCLOUD, outputRegex="invalid_rapt")], pid="a"))
c = validate_manifest(_plugin(self.td, [dict(GCLOUD, message="Run rm -rf /")], pid="a"))
d = validate_manifest(_plugin(self.td, [dict(GCLOUD, guestAllowed=True)], pid="a"))
fps = {capability_fingerprint(m) for m in (a, b, c, d)}
self.assertEqual(len(fps), 4) # every one moves approval
# a plugin without hooks keeps the fingerprint it had before the key existed
e = validate_manifest(_plugin(self.td, [], pid="e"))
self.assertNotIn("harnessHooks", e)
self.assertIsNone(hh.fingerprint_sig(e))
class TestScope(unittest.TestCase):
def test_applies(self):
work_workers = {"where": "workers", "profiles": ["work"], "workers": []}
self.assertTrue(hh.applies(work_workers, "mac-orus", "work", False, False))
self.assertFalse(hh.applies(work_workers, "mac-perso", "personal", False, False))
self.assertFalse(hh.applies(work_workers, "local", "work", False, False))
self.assertFalse(hh.applies(work_workers, "guest-pc", None, True, True))
lab = {"where": "lab", "profiles": [], "workers": []}
self.assertTrue(hh.applies(lab, "local", "personal", False, False))
self.assertFalse(hh.applies(lab, "mac-orus", "work", False, False))
everywhere = {"where": "all", "profiles": [], "workers": []}
self.assertFalse(hh.applies(everywhere, "guest-pc", None, True, False)) # never by default
self.assertTrue(hh.applies(everywhere, "guest-pc", None, True, True))
# a workers list overrides where + profiles
only = {"where": "workers", "profiles": ["work"], "workers": ["local"]}
self.assertTrue(hh.applies(only, "local", "personal", False, False))
self.assertFalse(hh.applies(only, "mac-orus", "work", False, False))
def test_scope_reads_defaults_then_settings(self):
mf = {"settings": {"fields": SCOPE_FIELDS}}
self.assertEqual(hh.scope_of(mf, {}), {"where": "workers", "profiles": ["work"], "workers": []})
self.assertEqual(hh.scope_of(mf, {"profiles": "work, personal", "where": "bogus"}),
{"where": "all", "profiles": ["work", "personal"], "workers": []})
self.assertEqual(hh.scope_of({}, None)["where"], "all")
class TestMaterialize(unittest.TestCase):
def setUp(self):
self.td = pathlib.Path(tempfile.mkdtemp())
self.store = PluginStore(self.td / "data")
self.profiles = {"local": "personal", "mac-orus": "work", "devbox": "work",
"mac-perso": "personal"}
self._old = hh.profile_of
hh.profile_of = lambda rid: self.profiles.get(rid)
def tearDown(self):
hh.profile_of = self._old
def _index(self):
return json.loads((self.store.live_hooks_dir / "index.json").read_text())
def test_lab_copy_follows_the_scope(self):
pdir = _plugin(self.td / "src", [GCLOUD])
self.store.install(OWNER_UID, str(pdir), is_owner=True, approve=True)
self.assertEqual(self._index()["hooks"], []) # Work workers only: not the lab
self.store.update(OWNER_UID, "hooky", config={"where": "all", "profiles": []})
(rule,) = self._index()["hooks"]
self.assertEqual((rule["plugin"], rule["id"]), ("hooky", "gcloud-expired"))
self.store.update(OWNER_UID, "hooky", enabled=False)
self.assertEqual(self._index()["hooks"], [])
self.store.update(OWNER_UID, "hooky", enabled=True)
self.assertEqual(len(self._index()["hooks"]), 1)
self.store.uninstall(OWNER_UID, "hooky")
self.assertEqual(self._index()["hooks"], [])
def test_a_guests_install_never_counts(self):
pdir = _plugin(self.td / "src", [GCLOUD], fields=[])
self.store.install("cel", str(pdir), is_owner=True, approve=True)
self.store.sync_hooks()
self.assertEqual(self._index()["hooks"], [])
self.assertEqual(hh.bundle_for_worker(self.store, {"id": "mac-orus"})["rules"], [])
def test_script_copied_and_shipped(self):
script = {"id": "custom", "event": "PostToolUse", "matcher": "Bash", "script": "hooks/h.py"}
pdir = _plugin(self.td / "src", [script], fields=[], files={"hooks/h.py": "print(1)\n"})
self.store.install(OWNER_UID, str(pdir), is_owner=True, approve=True)
(rule,) = self._index()["hooks"]
self.assertEqual(rule["script"], "hooky/hooks/h.py")
self.assertNotIn("_src", rule)
self.assertEqual((self.store.live_hooks_dir / "hooky/hooks/h.py").read_text(), "print(1)\n")
b = hh.bundle_for_worker(self.store, {"id": "mac-perso"})
self.assertEqual(base64.b64decode(b["files"]["hooky/hooks/h.py"]), b"print(1)\n")
def test_worker_bundles_by_profile_and_guest(self):
pdir = _plugin(self.td / "src", [GCLOUD, dict(GCLOUD, id="for-guests", guestAllowed=True)])
self.store.install(OWNER_UID, str(pdir), is_owner=True, approve=True)
ids = lambda w: [r["id"] for r in hh.bundle_for_worker(self.store, w)["rules"]] # noqa: E731
self.assertEqual(ids({"id": "mac-orus"}), ["for-guests", "gcloud-expired"])
self.assertEqual(ids({"id": "devbox"}), ["for-guests", "gcloud-expired"])
self.assertEqual(ids({"id": "mac-perso"}), [])
# a guest's computer sits in no profile: the Work filter leaves it out
self.assertEqual(ids({"id": "g1", "owner": "akira"}), [])
self.store.update(OWNER_UID, "hooky", config={"profiles": []})
self.assertEqual(ids({"id": "g1", "owner": "akira"}), ["for-guests"])
# the hash moves with the rules
h1 = hh.bundle_for_worker(self.store, {"id": "mac-orus"})["hash"]
self.store.update(OWNER_UID, "hooky", config={"workers": ["devbox"]})
self.assertEqual(ids({"id": "mac-orus"}), [])
self.assertNotEqual(hh.bundle_for_worker(self.store, {"id": "devbox"})["hash"], h1)
def test_labsync_carries_the_hooks(self):
pdir = _plugin(self.td / "src", [GCLOUD])
self.store.install(OWNER_UID, str(pdir), is_owner=True, approve=True)
old = labsync.plugin_store
labsync.plugin_store = lambda: self.store
try:
base = {"hash": "abc", "skills": {}}
plain = labsync.with_plugins(base, {"hooks": labsync.hooks_bundle({"id": "mac-perso"})})
self.assertEqual(plain["hooks"], {})
self.assertEqual(plain["hash"], "abc")
work = labsync.with_plugins(base, {"hooks": labsync.hooks_bundle({"id": "mac-orus"})})
self.assertEqual([r["id"] for r in work["hooks"]["rules"]], ["gcloud-expired"])
self.assertNotEqual(work["hash"], "abc")
finally:
labsync.plugin_store = old
if __name__ == "__main__":
unittest.main()