前两篇改的都是自己电脑上的用户级体验,不侵入业务仓库。可一旦把 agy 带进真实的多人业务仓库,问题马上变成另一类:
多工具共存容易互相污染 :同一个仓库里,有的同事用 Cursor,有的用 Codex,有的用 Claude Code,我自己用 AGY。如果图省事让 .agent/ 去引用 .codex/ 或 .claude/ 的脚本,哪天同事改了一把目录结构,AGY 这边就莫名其妙挂了;反之我也不该动别人维护的目录。
光写文档约束,Agent 还是会顺手破戒 :AGENTS.md 里明明白白写着“禁止在宿主机跑 go test / pnpm dev,统一进本机 K3s Pod”“非文档用途禁止跑 Docker”,但上下文一长,模型照样顺手敲出 go test ./... 或套一层 bash -c、python -c 绕过去。
查本地库既想要方便,又怕 Agent 删库或把密码打进日志 :联调问题时让 Agent 直接查一下本机 K3s 里的 PostgreSQL 和 Redis 极其省时间,但直接把带密码的连接串塞进命令参数或配置里,不仅不能提交 Git,连 ps aux 和 stderr 都可能把密码吐出来。
这篇结合我在一个 Go + Vue + K3s 微服务仓库里的实际落地配置(仓库名、环境变量前缀均已脱敏为 app-cloud / APP_*),把目录隔离、防逃逸双协议 Hooks、本地只读 DB/Redis 插件 三块逐一拆开。
一、多工具共存:把 .agent/ 与公共 scripts/ 划清界线 仓库根目录同时挂着多个 AI 工具目录时,最稳的分层只有一条原则:**工具私有配置各管各的,真正干活的工程脚本全部下沉到仓库根目录 scripts/**。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 app-cloud/ ├── AGENTS.md # 仓库通用说明 ├── scripts/ # 所有工具共用的确定性工程脚本 │ ├── dev-runtime.py # 统一进本机 K3s Pod 执行编译/lint/测试 │ ├── k8s-local-host.py # 解析本机物理网卡 LAN IP │ ├── hook-command-policy.py # 双协议(--protocol codex|agy)禁宿主机编译 │ └── hook-docs-sidebar.py # 双协议按路径指纹增量同步文档侧边栏 ├── .agent/ # AGY 专属,完全不依赖 .codex / .claude │ ├── hooks.json # 挂载根目录 scripts/hook-*.py --protocol agy │ ├── rules/ │ │ ├── agy-workspace.md # trigger: always_on,隔离边界与技能路由 │ │ └── auto-lint-after-edit.md # trigger: always_on,改完代码串行 lint 门禁 │ ├── skills/ # 项目专属技能(proj-review / proj-jira 等) │ └── plugins/ │ └── local-k3s-mcp/ # 项目级只读 PG / Redis MCP 插件 ├── .codex/ # 同事维护,AGY 禁止读取与修改 ├── .claude/ # 同事维护,AGY 禁止读取与修改 └── .cursor/ # 同事维护,AGY 禁止读取与修改
1. 用 trigger: always_on 把隔离规则钉死在上下文里 .agent/rules/agy-workspace.md 不写废话,只列六条硬边界:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 --- trigger: always_on description: 项目下 Antigravity (AGY) 专属隔离边界与本地运行约束 --- # AGY 项目隔离与运行规则 1. **完全不依赖 Codex / Claude** : - AGY 专属规则、技能、Hook 与插件统一维护在 `.agent/`,公共工程脚本统一调用 `scripts/`。 - 禁止读取、依赖或引用 `.codex/`、`.claude/` 中的任何脚本、Hook、技能或产物。 - 不擅自修改同事维护的 `.codex/`、`.claude/`、`.cursor/`。 2. **本机运行环境(K3s 优先,文档 Docker 例外)** : - 业务编译、lint、测试均通过 `python3 scripts/dev-runtime.py exec <service > ...` 在 K3s Pod 内执行;非文档用途禁止使用 Docker/Compose。 3. **技能路由优先于全局通用技能** : - 代码审查优先用项目技能 `proj-review`(高于全局 `code-review`)。 - 业务提交与 MR 优先用项目技能 `proj-jira`(高于全局 `git-commit`),遵守提交格式规范。 4. **项目级 MCP(`local-k3s-mcp`)使用边界** : - `local-k3s-mcp_ db` 已强制只读且限 100 行;` local-k3s-mcp_redis` 默认仅执行只读查询(`get`、`list`)。 5. **沙箱命令形态** : - 保持固定字面前缀(如 `python3 scripts/dev-runtime.py exec ...`),避免不必要的 `$()`、变量展开或包装器,方便沙箱授权前缀复用、减少重复确认。
2. 改完代码立刻串行跑 Lint(auto-lint-after-edit.md) 另一条很实用的是 .agent/rules/auto-lint-after-edit.md(同样 trigger: always_on)。之前最容易把开发机 CPU/内存打满的场景,就是 Agent 并行起好几个 golangci-lint 或者在前端加上 --fix 把无关文件全格式化一遍。直接写死串行参数:
Go 后端 :python3 scripts/dev-runtime.py exec api-service-dev env GOMAXPROCS=1 GOFLAGS=-p=1 golangci-lint run --concurrency=1 <受影响包路径>
前端(Vue / TS / CSS) :python3 scripts/dev-runtime.py exec web-dev sh -ec 'npx oxlint <文件...> && npx eslint <文件...> && npx stylelint <样式或vue文件...>'(明确禁止 --fix)
二、防逃逸静态分析 Hooks:别只靠正则 if "docker" in cmd 规则文件只是“软约束”,真正不能破的红线必须交给 PreToolUse / PostToolUse Hook 做确定性拦截。
很多人的第一版 Hook 都喜欢写 if "docker" in command: deny。用不了两天就会发现两头不讨好:
误杀一堆正常操作 :git commit -m "fix docker docs"、rg "docker" README.md、或者 heredoc 里写篇文档直接被拦;
防不住花式绕过 :env -S "docker ps"、timeout 5 docker build .、sh -c "go test ./..."、$(go build)、甚至 python3 -c 'import subprocess; subprocess.run(["docker", "ps"])' 全能轻松穿过去。
我在用户级(~/.gemini/config/hooks/deny-docker-agy.py)和项目级(scripts/hook-command-policy.py)都换成了纯静态分析器(绝不执行任何输入) ,完整解析链路如下:
flowchart TD
CMD["CommandLine 原始字符串"] --> HD["strip_heredocs()<br/>追踪跨行引号剥离 heredoc 正文<br/>未加引号的正文仍检查命令替换"]
HD --> SUB["substitutions()<br/>递归提取 $(...) 与反引号内部命令<br/>尊重单引号语义"]
SUB --> LEX["shlex 词法切分<br/>按 ; & | ( ) { } 换行分段"]
LEX --> WRAP{"遇到包装器 / 解释器?"}
WRAP -- "env -S / sudo / timeout / xargs / busybox" --> REC1["剥离选项后递归检查内部段"]
WRAP -- "sh/bash -c / eval / find -exec / kubectl exec --" --> REC2["递归 inspect 内部命令串"]
WRAP -- "python -c 或 stdin" --> AST["ast.parse 静态提取<br/>subprocess.* / os.system 字面量参数"]
WRAP -- "目标命令" --> RULE{"命中禁用策略?"}
AST --> RULE
RULE -- "是" --> DENY["返回 decision: deny + 明确原因"]
RULE -- "否" --> ALLOW["返回 decision: allow"]
1. 用户级 Docker 防火墙里的两个硬核细节(deny-docker-agy.py) 这个脚本 359 行,职责是“全局禁止非文档用途的 Docker/Compose,仅放行固定的 docs-dev 文档容器白名单操作”。其中最值得复用的是 Python AST 静态穿透 和 跨行引号感知的 heredoc 扫描 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 def python_commands (source ): """Recognize common literal subprocess/os calls without running Python code.""" try : tree = ast.parse(source) except SyntaxError: return values = {} def literal (node ): if isinstance (node, ast.Name): return values[node.id ] if isinstance (node, (ast.List , ast.Tuple )): return [literal(item) for item in node.elts] if isinstance (node, ast.BinOp) and isinstance (node.op, ast.Add): return literal(node.left) + literal(node.right) return ast.literal_eval(node) for node in ast.walk(tree): try : if isinstance (node, ast.Assign): for target in node.targets: if isinstance (target, ast.Name): values[target.id ] = literal(node.value) if not isinstance (node, ast.Call): continue name = node.func.attr if isinstance (node.func, ast.Attribute) else "" if name not in {"run" , "Popen" , "call" , "check_call" , "check_output" , "system" , "popen" , "execv" , "execvp" }: continue argument = node.args[0 ] if node.args else next ( keyword.value for keyword in node.keywords if keyword.arg in {"args" , "command" , "cmd" } ) command = literal(argument) except (ValueError, TypeError, KeyError, StopIteration): continue if isinstance (command, str ): inspect(command) elif isinstance (command, list ) and all (isinstance (value, str ) for value in command): segment(command)
哪怕有人写成:
1 python3 -c 'cmd = ["doc" + "ker", "ps"]; import subprocess; subprocess.run(cmd)'
不需要跑一行 Python 代码,literal() 就能把变量赋值和字符串加法静态求值出来,交给 segment(["docker", "ps"]) 精准拦下;同时普通 cat <<'EOF' > doc.md 里提到 docker 又会被 strip_heredocs() 干净剥离,完全不误杀。
2. 项目级一套脚本双协议复用(--protocol codex | agy) 仓库里同事用 Codex、我用 AGY,两边的 PreToolUse / PostToolUse 协议字段和退出码契约长得不一样,但底层拦截逻辑 100% 相同。没必要复制两份脚本互相漂移,直接在 scripts/hook-*.py 里加一个 --protocol 开关。
两个协议的核心差异对照:
维度
Codex / Claude 风格
Antigravity (--protocol agy)
事件名字段
hook_event_name
hookEventName
工具名与参数
tool_name / tool_input.command
toolCall.name / toolCall.args.CommandLine
PreToolUse 放行
退出码 0
stdout 输出 {"decision": "allow"} 且退出码 0
PreToolUse 拦截
报错打到 stderr 且退出码 2
stdout 输出 {"decision": "deny", "reason": "..."} 且退出码 0
PostToolUse 正常返回
可带 {"systemMessage": "..."}
stdout 输出 {}
在 .agent/hooks.json 里挂载仓库根目录脚本,只需传 --protocol agy:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 { "no-host-compile" : { "PreToolUse" : [ { "matcher" : "run_command" , "hooks" : [ { "type" : "command" , "command" : "python3 -B ../scripts/hook-command-policy.py --protocol agy" , "timeout" : 10 } ] } ] } , "update-docs-sidebar" : { "PostToolUse" : [ { "matcher" : "write_file|edit_file|run_command" , "hooks" : [ { "type" : "command" , "command" : "python3 -B ../scripts/hook-docs-sidebar.py --protocol agy" , "timeout" : 60 } ] } ] } }
注意命令行里的 -B 参数(禁止生成 __pycache__),以及相对路径 ../scripts/...——AGY 执行 .agent/hooks.json 时工作目录解析要注意路径基准,加 -B 能防止在仓库 scripts/ 里产生未追踪的 .pyc 垃圾文件。
scripts/hook-command-policy.py 适配双协议的入口极其干净(不到 30 行):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 def extract_command (payload, protocol ): if not isinstance (payload, dict ): raise ValueError("Hook 输入必须是 JSON 对象。" ) if protocol == "agy" : args = payload.get("toolCall" , {}).get("args" , {}) command = args.get("CommandLine" ) if isinstance (args, dict ) else None else : tool_input = payload.get("tool_input" ) command = tool_input.get("command" ) if isinstance (tool_input, dict ) else None if not isinstance (command, str ): raise ValueError("无法解析命令 Hook 输入,拒绝放行。" ) return command def run_protocol (protocol ): try : payload = json.load(sys.stdin) command = extract_command(payload, protocol) inspect(command) if protocol == "agy" : print (json.dumps({"decision" : "allow" }, ensure_ascii=False )) return 0 except (ValueError, TypeError, AttributeError) as exc: if protocol == "agy" : print (json.dumps({"decision" : "deny" , "reason" : str (exc)}, ensure_ascii=False )) return 0 print (str (exc), file=sys.stderr) return 2
文档站点用 VitePress,新增、删除或重命名 docs/**/*.md 后必须重跑侧边栏生成器,但仅仅修改某篇 Markdown 的正文内容时根本不需要重新生成 ——如果每次编辑文档都跑一次容器里的 gen-sidebar.ts,写篇文章会被卡得怀疑人生。
scripts/hook-docs-sidebar.py 用四层过滤把这个开销压到几乎无感:
工具快筛 :AGY 下 edit_file 只改正文不改文件名,直接返回 {};write_file 只放行 .md 路径;run_command 跳过简单只读命令(rg、cat、ls、git status/diff/log 等,但对带 ; | & > < $ 或 rg --pre 的命令一律保守放行去查文件系统)。
Worktree 安全边界校验 :通过 git worktree list --porcelain -z 确认 cwd 确实属于当前仓库或已注册 worktree,防止越界同步。
相对路径集合 SHA-256 指纹 :只把 docs/ 下排序后的 .md 相对路径列表算 SHA-256(不读任何正文内容!),和 tmp/app-docs-sidebar/state.json 比对。改名即使文件总数不变,哈希也会变;改正文哈希完全不变,直接秒退。
排他文件锁 + 失败不推进状态 :fcntl.flock 串行化并发写入,生成完还会再算一次指纹防止同步期间文档又变了;如果同步失败,保留旧指纹,下次操作自动重试。
关键片段:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 def fingerprint (root ): """只比较排序后的相对文件路径,同数量改名也能识别。""" entries = [] for directory, dirs, files in os.walk(root / "docs" , followlinks=False ): base = Path(directory) dirs[:] = sorted ( d for d in dirs if not d.startswith(("." , "_" )) and d != "node_modules" and not (base / d).is_symlink() ) for name in files: if name.endswith(".md" ): entries.append(str ((base / name).relative_to(root))) return hashlib.sha256(json.dumps(sorted (entries), ensure_ascii=False ).encode()).hexdigest() def synchronize (root, runner_root=None ): runner_root = root if runner_root is None else runner_root cache = root / Path("tmp/app-docs-sidebar" ) cache.mkdir(parents=True , exist_ok=True ) state_path = cache / "state.json" with (cache / "sync.lock" ).open ("a" ) as lock: before = fingerprint(root) try : state = json.loads(state_path.read_text()) except (FileNotFoundError, ValueError): state = None expected = {"paths" : before} if (root / OUTPUT).is_file() and state == expected: return False result = subprocess.run(["bash" , str (runner_root / "scripts/docs-sync.sh" )], cwd=root, capture_output=True , text=True , timeout=40 ) if result.returncode: raise RuntimeError(f"文档生成命令退出码 {result.returncode} " ) if fingerprint(root) != before: raise RuntimeError("同步期间文档发生变化,需要重新同步" ) pending = state_path.with_suffix(".tmp" ) pending.write_text(json.dumps(expected) + "\n" ) pending.replace(state_path) return True
三、项目级只读 DB & Redis MCP 插件:凭据全链路零暴露 最后一个高频痛点是让 Agent 查本机 K3s 里的 PostgreSQL 和 Redis。
如果图省事在全局 mcp_config.json 里写死数据库连接串,马上踩三个雷:
换个项目或拉新分支端口/密码就对不上;
密码明文躺进 mcp_config.json 或 CLI 参数里,随时被 ps aux 扫走;
上游部分 MCP 服务启动时会顺手把连接串打到 stderr,日志里全是明文密码。
我的做法是在仓库内建一个项目级 AGY 插件 .agent/plugins/local-k3s-mcp/,所有设计围绕“版本锁死、只读限行、凭据三不露(不入 Git、不进 OS 参数、不漏 stderr) ”展开:
flowchart LR
MC["mcp_config.json<br/>解析 $PLUGIN_ROOT"] --> L["launcher.py db|redis"]
L --> V["校验本地锁定版本<br/>dbhub@1.2.1 / redis-mcp@1.0.0"]
L --> C["动态读取<br/>物理网卡 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 进程内写 argv 并 delete env"]
PG --> SIL["dup2(/dev/null, fd=2)<br/>os.execvpe 启动"]
RD --> SIL
1. 插件清单与路径兜底(plugin.json + mcp_config.json) plugin.json 极简:
1 2 3 4 { "name" : "local-k3s-mcp" , "author" : "Local Developer" }
mcp_config.json 用一小段 POSIX shell 对 $PLUGIN_ROOT 做三级回退,无论从仓库根还是插件目录触发都能找到 launcher.py:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 { "mcpServers" : { "db" : { "command" : "sh" , "args" : [ "-c" , "if [ -n \"${PLUGIN_ROOT:-}\" ] && [ -f \"$PLUGIN_ROOT/launcher.py\" ]; then exec python3 -B \"$PLUGIN_ROOT/launcher.py\" db; elif [ -f \"./launcher.py\" ]; then exec python3 -B ./launcher.py db; else exec python3 -B .agent/plugins/local-k3s-mcp/launcher.py db; fi" ] } , "redis" : { "command" : "sh" , "args" : [ "-c" , "if [ -n \"${PLUGIN_ROOT:-}\" ] && [ -f \"$PLUGIN_ROOT/launcher.py\" ]; then exec python3 -B \"$PLUGIN_ROOT/launcher.py\" redis; elif [ -f \"./launcher.py\" ]; then exec python3 -B ./launcher.py redis; else exec python3 -B .agent/plugins/local-k3s-mcp/launcher.py redis; fi" ] } } }
2. PostgreSQL:TOML 锁死只读与最大行数(dbhub.toml) @bytebase/dbhub 支持用 TOML 文件声明数据源和工具权限,并且可以直接引用环境变量 ${APP_DB_DSN},避免把 DSN 暴露在命令行参数里:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 [[sources]] id = "default" dsn = "${APP_DB_DSN}" connection_timeout = 10 query_timeout = 10 [[tools]] name = "execute_sql" source = "default" readonly = true max_rows = 100 [[tools]] name = "search_objects" source = "default"
这样就算 Agent 忘了写 LIMIT,最多也就吐 100 行,不会把几十万行表数据灌进上下文;就算它脑抽想 DELETE / UPDATE,服务端直接拒掉。
3. Redis:11 行 ESM 包装器堵死 ps aux 泄密(mcp-redis.mjs) @gongrzhe/server-redis-mcp 有个很讨厌的设计:它只接受通过命令行参数 argv[2] 传 Redis URL。如果直接 node index.js redis://:secret@...,本机任何进程一敲 ps aux 密码就一览无余。
用 11 行 Node ESM 包装器 .agent/plugins/local-k3s-mcp/mcp-redis.mjs 就能完美绕开:启动时通过环境变量传入,进 Node 进程后在内存里覆盖 process.argv,紧接着立刻 delete process.env.APP_REDIS_URL,再动态 import 真正的入口模块:
1 2 3 4 5 6 7 8 9 10 11 12 import { pathToFileURL } from 'node:url' const entry = process.env .APP_REDIS_ENTRY const url = process.env .APP_REDIS_URL if (!entry || !url) { throw new Error ('请通过 .agent/plugins/local-k3s-mcp/launcher.py redis 启动' ) } process.argv = [process.execPath , entry, url] delete process.env .APP_REDIS_URL await import (pathToFileURL (entry).href )
修改 Node 里的 process.argv **不会改写操作系统 /proc/<pid>/cmdline**,同时环境变量在真正业务逻辑跑起来前就已经从内存删掉,外部根本看不到密码。
4. 统一启动器:launcher.py(锁版本 + 动态组装 + fd 2 静音) 最后看 .agent/plugins/local-k3s-mcp/launcher.py:
拒绝 npx 随跑随下,强校验 ~/.gemini/mcp-servers/app/node_modules/<pkg>/package.json 版本号必须精确匹配;
动态读取物理网卡真实 LAN IP(很多本地 K3s 端口绑定在物理网卡而不是 127.0.0.1)、deploy/k8s/local/workloads.json 里的 hostPort 以及已加入 .gitignore 的 tmp/k8s-local/secrets.json;
对用户名和密码做 urllib.parse.quote(..., safe=""),防止特殊字符把 URL 搞炸;
提供 --check 自检模式,随时验证配置是否就绪而不打印任何凭据;
真正 os.execvpe 前,用 os.dup2(sink.fileno(), 2) 把 stderr 重定向到 /dev/null,彻底堵死上游服务把连接串打进错误日志的最后一条通道。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 """启动本机 K3s 的只读 PostgreSQL / Redis MCP 服务:凭据不入 Git、不进进程参数、不漏 stderr。""" import argparse, importlib.util, json, os, shutil, sysfrom pathlib import Pathfrom urllib.parse import quotePLUGIN_DIR = Path(__file__).resolve().parent ROOT = PLUGIN_DIR.parents[2 ] PACKAGES = { "db" : ("@bytebase/dbhub" , "1.2.1" , "dist/index.js" ), "redis" : ("@gongrzhe/server-redis-mcp" , "1.0.0" , "build/index.js" ), } def load_lan_address (): spec = importlib.util.spec_from_file_location("k8s_local_host" , ROOT / "scripts/k8s-local-host.py" ) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module.lan_address()[1 ] def load_host_port (service_name, default_port ): workloads = json.loads((ROOT / "deploy/k8s/local/workloads.json" ).read_text(encoding="utf-8" )) bindings = workloads.get("host_bindings" , {}).get(service_name, []) return bindings[0 ]["hostPort" ] if bindings and isinstance (bindings[0 ].get("hostPort" ), int ) else default_port def load_secrets (): secrets_path = ROOT / "tmp/k8s-local/secrets.json" if not secrets_path.is_file(): raise ValueError("缺少本机 K3s 私有凭据 tmp/k8s-local/secrets.json" ) return json.loads(secrets_path.read_text(encoding="utf-8" )) def launch_config (name ): install_dir = Path(os.environ.get("AGY_MCP_APP_DIR" ) or Path.home() / ".gemini/mcp-servers/app" ).expanduser() package, version, entry = PACKAGES[name] package_root = install_dir / "node_modules" / package pkg_json = package_root / "package.json" if not pkg_json.is_file() or json.loads(pkg_json.read_text(encoding="utf-8" )).get("version" ) != version: raise ValueError(f"请先在 {install_dir} 安装固定版本 {package} @{version} " ) node = shutil.which("node" ) if not node: raise ValueError("Node.js 不可用" ) address, secrets = load_lan_address(), load_secrets() env = os.environ.copy() if name == "db" : port = load_host_port("postgres" , 5432 ) user = quote(str (secrets["POSTGRES_USER" ]), safe="" ) password = quote(str (secrets["POSTGRES_PASSWORD" ]), safe="" ) database = quote(str (secrets["POSTGRES_DB" ]), safe="" ) env["APP_DB_DSN" ] = f"postgres://{user} :{password} @{address} :{port} /{database} ?sslmode=disable" command = [node, str (package_root / entry), "--transport" , "stdio" , "--config" , str (PLUGIN_DIR / "dbhub.toml" )] else : port = load_host_port("redis" , 6379 ) password = quote(str (secrets["REDIS_PASSWORD" ]), safe="" ) env["APP_REDIS_URL" ] = f"redis://:{password} @{address} :{port} " env["APP_REDIS_ENTRY" ] = str (package_root / entry) command = [node, str (PLUGIN_DIR / "mcp-redis.mjs" )] return command, env def main (): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("server" , choices=sorted (PACKAGES)) parser.add_argument("--check" , action="store_true" ) args = parser.parse_args() try : command, env = launch_config(args.server) if args.check: print (f"{args.server} : K3s MCP 启动配置就绪(凭据已脱敏,未泄露至参数)" ) return 0 with open (os.devnull, "w" , encoding="utf-8" ) as sink: os.dup2(sink.fileno(), 2 ) os.execvpe(command[0 ], command, env) except (OSError, ValueError, KeyError) as error: print (f"{args.server} : 启动配置失败({error} )" , file=sys.stderr) return 1 if __name__ == "__main__" : raise SystemExit(main())
整套项目级防线清单 把这一篇落地的组件按职责收个尾:
文件
作用域
解决的问题
~/.gemini/config/hooks/deny-docker-agy.py
用户级
词法 + heredoc + Python AST 静态拦截非文档 Docker,保留 docs-dev 最小白名单
.agent/rules/agy-workspace.md
项目级
多工具目录隔离、技能路由优先级、固定字面前缀便于沙箱复用
.agent/rules/auto-lint-after-edit.md
项目级
改完代码立刻在 K3s Pod 串行跑 lint(禁用并发打爆与前端 --fix)
.agent/hooks.json + scripts/hook-command-policy.py
双协议复用
同一套静态解析器兼容 `–protocol codex
scripts/hook-docs-sidebar.py
双协议复用
按 docs/**/*.md 路径集合 SHA-256 指纹 + flock 增量同步侧边栏,改正文零开销
.agent/plugins/local-k3s-mcp/*
项目级插件
锁版本 + 物理 LAN IP + TOML 只读限 100 行 + Node 进程内擦除密码 + fd 2 静音
系列导航