Project-Level .agent/ Isolation, Dual-Protocol Hooks & Read-Only DB/Redis Plugins
The first two posts focused on user-level ergonomics on your own machine without touching any application repository. The moment you bring agy into a shared multi-developer codebase, a completely different class of problems shows up:
- Multi-tool coexistence leads to cross-contamination: Inside the same repository, some teammates use Cursor, some use Codex, some use Claude Code, and I use AGY. If I take a shortcut and let
.agent/call scripts inside.codex/or.claude/, AGY breaks the day a teammate refactors their directory layout—and I have no business modifying directories other people maintain. - Written rules alone do not hold:
AGENTS.mdcan state plainly, “Never rungo testorpnpm devon the host; execute inside local K3s Pods” and “No Docker outside docs.” Once the context window grows long, the model still casually runsgo test ./...or wraps commands inbash -corpython -cto slip past naive checks. - Local DB access needs convenience without risking data loss or secret leaks: Letting an agent query PostgreSQL and Redis in local K3s saves massive debugging time. Hardcoding connection strings with passwords into CLI arguments or config files, however, means you cannot commit the config to Git—and still risks leaking passwords straight into
ps auxandstderrlogs.
Drawing from a real Go + Vue + K3s microservice repository (with the repository name and environment variable prefix sanitized to app-cloud and APP_*), this post breaks down three concrete defenses: directory isolation, escape-proof dual-protocol Hooks, and a local read-only DB/Redis MCP plugin.

1. Multi-Tool Coexistence: Drawing a Hard Line Between .agent/ and Shared scripts/
When multiple AI tool directories live side by side at the repository root, only one boundary holds up over time: each tool owns its private adapter directory, while every deterministic engineering script lives under the repo-root scripts/ directory.
1 | app-cloud/ |
1. Pin Isolation Boundaries in Context with trigger: always_on
.agent/rules/agy-workspace.md skips the fluff and pins five hard boundaries:
1 | --- |
2. Run Serial Lint Immediately After Edits (auto-lint-after-edit.md)
Another high-leverage rule is .agent/rules/auto-lint-after-edit.md (also trigger: always_on). Previously, the fastest way an agent could peg CPU and memory on a devbox was spawning parallel golangci-lint processes—or running frontend linters with --fix and reformatting unrelated files. Hardcoding serial flags and banning --fix directly in the rule eliminates both:
- Go backend:
python3 scripts/dev-runtime.py exec api-service-dev env GOMAXPROCS=1 GOFLAGS=-p=1 golangci-lint run --concurrency=1 <affected-package-paths> - Frontend (Vue / TS / CSS):
python3 scripts/dev-runtime.py exec web-dev sh -ec 'npx oxlint <files...> && npx eslint <files...> && npx stylelint <style-or-vue-files...>'(--fixexplicitly prohibited)
2. Escape-Proof Static Analysis Hooks: Move Beyond if "docker" in cmd
Rule files are soft guardrails. Hard red lines belong in deterministic PreToolUse and PostToolUse Hooks.
Most first-draft Hooks start with if "docker" in command: deny. Within two days, that fails from both sides:
- False positives on routine work:
git commit -m "fix docker docs",rg "docker" README.md, or writing documentation inside a heredoc gets blocked immediately. - Trivial bypasses:
env -S "docker ps",timeout 5 docker build .,sh -c "go test ./...",$(go build), andpython3 -c 'import subprocess; subprocess.run(["docker", "ps"])'all walk right past it.
In both my user-level Hook (~/.gemini/config/hooks/deny-docker-agy.py) and project-level Hook (scripts/hook-command-policy.py), I replaced regex matching with a pure static analyzer that never executes untrusted input:
flowchart TD
CMD["Raw CommandLine string"] --> HD["strip_heredocs()<br/>Track multi-line quotes & strip heredoc bodies<br/>Still inspect unquoted bodies for command substitution"]
HD --> SUB["substitutions()<br/>Recursively extract $(...) & backtick commands<br/>Respect single-quote semantics"]
SUB --> LEX["shlex lexical split<br/>Segment on ; & | ( ) { } and newlines"]
LEX --> WRAP{"Wrapper or interpreter?"}
WRAP -- "env -S / sudo / timeout / xargs / busybox" --> REC1["Strip flags & recursively inspect inner segment"]
WRAP -- "sh/bash -c / eval / find -exec / kubectl exec --" --> REC2["Recursively inspect inner command string"]
WRAP -- "python -c or stdin" --> AST["ast.parse static extraction<br/>Resolve literal subprocess.* / os.system args"]
WRAP -- "Target command" --> RULE{"Matches deny policy?"}
AST --> RULE
RULE -- "Yes" --> DENY["Return decision: deny + explicit reason"]
RULE -- "No" --> ALLOW["Return decision: allow"]
1. Two Hardened Details in the User-Level Docker Firewall (deny-docker-agy.py)
This 359-line script blocks all non-docs Docker/Compose invocations globally while keeping a narrow allowlist for the docs-dev documentation container. Its two most reusable mechanisms are static Python AST inspection and quote-aware multi-line heredoc stripping:
1 | def python_commands(source): |
Even if someone writes:
1 | python3 -c 'cmd = ["doc" + "ker", "ps"]; import subprocess; subprocess.run(cmd)' |
Without executing a single line of Python, literal() resolves the variable assignment and string concatenation statically and feeds segment(["docker", "ps"]) straight into the deny rule. Meanwhile, mentioning docker inside cat <<'EOF' > doc.md is cleanly stripped by strip_heredocs() with zero false positives.
2. One Project Script, Dual-Protocol Support (--protocol codex | agy)
Teammates running Codex and my own AGY sessions expect different PreToolUse / PostToolUse JSON schemas and exit-code contracts, even though the underlying policy logic is 100% identical. Instead of duplicating scripts and watching them drift apart, scripts/hook-*.py accepts a --protocol flag.
Core protocol differences side by side:
| Dimension | Codex / Claude Style | Antigravity (--protocol agy) |
|---|---|---|
| Event name field | hook_event_name |
hookEventName |
| Tool name & args | tool_name / tool_input.command |
toolCall.name / toolCall.args.CommandLine |
PreToolUse allow |
Exit code 0 |
stdout {"decision": "allow"} + exit code 0 |
PreToolUse deny |
Error message on stderr + exit code 2 |
stdout {"decision": "deny", "reason": "..."} + exit code 0 |
PostToolUse success |
Optional {"systemMessage": "..."} |
stdout {} |
.agent/hooks.json wires directly into the repo-root scripts by passing --protocol agy:
1 | { |
Note the -B flag (disabling __pycache__ generation) and the relative path ../scripts/.... Pay attention to the working-directory base when AGY executes .agent/hooks.json, and pass -B so Python never drops untracked .pyc files inside scripts/.
The dual-protocol entry point in scripts/hook-command-policy.py stays under 30 lines:
1 | def extract_command(payload, protocol): |
3. Incremental PostToolUse Docs Sidebar Sync via Path Fingerprints (hook-docs-sidebar.py)
Our docs site uses VitePress. Adding, deleting, or renaming any docs/**/*.md file requires regenerating the sidebar, whereas editing the body of an existing Markdown file never changes the sidebar. Triggering the containerized gen-sidebar.ts generator on every single doc edit would make writing documentation unbearably sluggish.
scripts/hook-docs-sidebar.py cuts the overhead to near zero with four layers of filtering:
- Fast tool pre-filter: Under AGY,
edit_filemodifies content rather than filenames and immediately returns{};write_fileonly proceeds for.mdpaths;run_commandskips simple read-only commands (rg,cat,ls,git status/diff/log, etc.), while conservatively falling through to a filesystem check whenever a command contains; | & > < $orrg --pre. - Worktree boundary validation: Calls
git worktree list --porcelain -zto verifycwdbelongs to the repository or a registered worktree before running any sync. - SHA-256 fingerprint over sorted relative paths: Hashes only the sorted list of
.mdrelative paths underdocs/(without reading a single byte of file content) and compares it againsttmp/app-docs-sidebar/state.json. Renaming a file changes the hash even when the file count stays constant; editing body text leaves the hash identical and exits in milliseconds. - Exclusive file lock + no state advancement on failure: Serializes concurrent writes with
fcntl.flock, re-hashes after generation to catch mid-sync edits, and leaves the previous fingerprint untouched on failure so the next operation retries automatically.
Core implementation:
1 | def fingerprint(root): |
3. Project-Level Read-Only DB & Redis MCP Plugin: Zero Credential Exposure End to End
The last recurring friction point is letting an agent inspect PostgreSQL and Redis inside local K3s.
Hardcoding database connection strings in the global mcp_config.json trips three landmines immediately:
- Ports and passwords go stale the moment you switch projects or check out a new branch;
- Plaintext passwords sitting in
mcp_config.jsonor CLI arguments are trivially visible inps aux; - Some upstream MCP servers print the connection string straight to
stderron startup, dumping plaintext passwords into logs.
To solve all three, I built a project-level AGY plugin under .agent/plugins/local-k3s-mcp/ around three invariants: pinned versions, read-only with row limits, and zero credential exposure (never in Git, never in OS argv, never on stderr):
flowchart LR
MC["mcp_config.json<br/>Resolve $PLUGIN_ROOT"] --> L["launcher.py db|redis"]
L --> V["Verify pinned local versions<br/>dbhub@1.2.1 / redis-mcp@1.0.0"]
L --> C["Dynamically load<br/>NIC LAN IP + workloads.json<br/>+ tmp/k8s-local/secrets.json"]
C -- "db" --> PG["env APP_DB_DSN<br/>dbhub.toml: readonly=true, max_rows=100"]
C -- "redis" --> RD["env APP_REDIS_URL<br/>mcp-redis.mjs sets argv in-process & deletes env"]
PG --> SIL["dup2(/dev/null, fd=2)<br/>Launch via os.execvpe"]
RD --> SIL
1. Plugin Manifest & Path Fallback (plugin.json + mcp_config.json)
plugin.json stays minimal:
1 | { |
mcp_config.json uses a short POSIX shell three-tier fallback around $PLUGIN_ROOT, ensuring launcher.py resolves whether launched from the repository root or the plugin directory:
1 | { |
2. PostgreSQL: Lock Down Read-Only & Max Rows in TOML (dbhub.toml)
@bytebase/dbhub lets you declare data sources and tool permissions in a TOML file and interpolate ${APP_DB_DSN} directly from the environment, keeping the DSN off the command line:
1 | [[sources]] |
Even if the agent forgets LIMIT, the query returns at most 100 rows instead of flooding the context window with hundreds of thousands of records—and any accidental DELETE or UPDATE is rejected server-side.
3. Redis: An 11-Line ESM Wrapper to Close the ps aux Leak (mcp-redis.mjs)
@gongrzhe/server-redis-mcp has an annoying constraint: it only accepts the Redis URL through CLI argument argv[2]. Running node index.js redis://:secret@... exposes the password to any local process via ps aux.
An 11-line Node ESM wrapper (.agent/plugins/local-k3s-mcp/mcp-redis.mjs) closes that hole cleanly: pass the URL through an environment variable, overwrite process.argv inside Node memory, immediately delete process.env.APP_REDIS_URL, and dynamically import the real entry point:
1 | // Upstream Redis MCP only accepts the URL via argv; |
Mutating Node’s process.argv never rewrites /proc/<pid>/cmdline, and the environment variable is wiped from memory before upstream code even loads—leaving zero credentials visible from outside the process.
4. Unified Launcher: launcher.py (Pinned Versions + Dynamic Assembly + fd 2 Silencing)
Finally, .agent/plugins/local-k3s-mcp/launcher.py ties everything together:
- Refuses on-the-fly
npxdownloads and enforces exact version pins in~/.gemini/mcp-servers/app/node_modules/<pkg>/package.json; - Dynamically reads the physical NIC LAN IP (many local K3s ports bind to the LAN interface rather than
127.0.0.1),hostPortvalues fromdeploy/k8s/local/workloads.json, and secrets from gitignoredtmp/k8s-local/secrets.json; - URL-encodes usernames and passwords with
urllib.parse.quote(..., safe="")so special characters never corrupt the DSN; - Exposes a
--checkdry-run mode to verify readiness without printing any secrets; - Redirects
stderrto/dev/nullviaos.dup2(sink.fileno(), 2)right beforeos.execvpe, sealing the last channel through which an upstream server could log a connection string.
1 | #!/usr/bin/env python3 |
Full Project-Level Defense-in-Depth Checklist
Here is the complete inventory of components introduced in this post:
| File | Scope | Problem Solved |
|---|---|---|
~/.gemini/config/hooks/deny-docker-agy.py |
User-level | Static lexing + heredoc + Python AST blocking for non-docs Docker, keeping a minimal docs-dev allowlist |
.agent/rules/agy-workspace.md |
Project-level | Multi-tool directory isolation, skill routing priority, and fixed literal command prefixes for sandbox reuse |
.agent/rules/auto-lint-after-edit.md |
Project-level | Immediate serial post-edit linting inside K3s Pods (preventing CPU spikes and frontend --fix churn) |
.agent/hooks.json + scripts/hook-command-policy.py |
Dual-protocol shared | Single static analyzer supporting `–protocol codex |
scripts/hook-docs-sidebar.py |
Dual-protocol shared | SHA-256 docs/**/*.md path-set fingerprinting + flock for incremental sidebar sync with zero overhead on body edits |
.agent/plugins/local-k3s-mcp/* |
Project plugin | Pinned versions + physical LAN IP + TOML read-only 100-row cap + in-process Node secret erasure + fd 2 silencing |








