前兩篇改的都是自己電腦上的使用者層級體驗,完全不侵入業務儲存庫。但只要把 agy 帶進真實的多人協作業務儲存庫,問題馬上就變成另一回事:

  1. 多工具共存容易互相污染:同一個儲存庫裡,有的同事用 Cursor,有的用 Codex,有的用 Claude Code,我自己用 AGY。如果圖省事讓 .agent/ 去引用 .codex/ 或 .claude/ 的腳本,哪天同事調整了目錄結構,AGY 這邊就莫名其妙掛掉;反過來我也不應該去動別人維護的目錄。
  2. 光靠文件約束,Agent 還是會順手破戒:AGENTS.md 裡白紙黑字寫著「禁止在宿主機執行 go test / pnpm dev,一律進本機 K3s Pod」「非文件用途禁止執行 Docker」,但上下文一長,模型照樣順手敲出 go test ./...,甚至多套一層 bash -c、python -c 繞過去。
  3. 查本機資料庫既想要方便,又怕 Agent 誤刪資料或把密碼印進日誌:串接除錯時讓 Agent 直接查一下本機 K3s 裡的 PostgreSQL 和 Redis 非常省時間,但如果直接把帶密碼的連線字串塞進命令列參數或組態裡,不只無法提交進 Git,連 ps aux 和 stderr 都可能把密碼吐出來。

這篇結合我在一個 Go + Vue + K3s 微服務儲存庫裡的實際落地組態(儲存庫名稱與環境變數前綴皆已去識別化為 app-cloud / APP_*),把目錄隔離、防逃逸雙協定 Hooks、本機唯讀 DB/Redis 外掛這三個部分逐一拆解說明。

專案級 .agent/ 隔離、防逃逸 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)都改成了純靜態分析器(絕不執行任何輸入),完整的解析鏈路如下:

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

3. PostToolUse 依路徑指紋增量同步文件側邊欄(hook-docs-sidebar.py)

文件網站使用 VitePress,新增、刪除或重新命名 docs/**/*.md 後必須重跑側邊欄產生器,但單純修改某篇 Markdown 的內文時根本不需要重新產生——如果每次編輯文件都跑一次容器裡的 gen-sidebar.ts,寫一篇文章會被卡到懷疑人生。

scripts/hook-docs-sidebar.py 透過四層過濾把這項開銷壓到幾乎無感:

  1. 工具快篩:AGY 下 edit_file 只改內文不改檔名,直接回傳 {};write_file 只放行 .md 路徑;run_command 略過單純的唯讀指令(rg、cat、ls、git status/diff/log 等,但對帶有 ; | & > < $ 或 rg --pre 的指令一律保守放行去檢查檔案系統)。
  2. Worktree 安全邊界驗證:透過 git worktree list --porcelain -z 確認 cwd 確實屬於目前儲存庫或已註冊的 worktree,防止越界同步。
  3. 相對路徑集合 SHA-256 指紋:只把 docs/ 下排序後的 .md 相對路徑清單計算 SHA-256(完全不讀取任何內文!),再與 tmp/app-docs-sidebar/state.json 比對。重新命名就算檔案總數沒變,雜湊值也會改變;修改內文則雜湊值完全不變,直接快速結束。
  4. 排他檔案鎖+失敗不推進狀態:用 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:
# 5s 非阻塞輪詢取得排他鎖...
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 裡寫死資料庫連線字串,立刻會踩到三個雷:

  1. 換個專案或切新分支,埠號與密碼就對不上;
  2. 密碼明文躺在 mcp_config.json 或 CLI 參數裡,隨時會被 ps aux 掃出來;
  3. 上游部分 MCP 服務在啟動時會順手把連線字串印到 stderr,日誌裡滿滿都是明文密碼。

我的做法是在儲存庫裡建立一個專案級 AGY 外掛 .agent/plugins/local-k3s-mcp/,整體設計圍繞著「版本鎖死、唯讀限筆數、憑證三不露(不入 Git、不進 OS 參數、不漏 stderr)」展開:

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
// 上游 Redis MCP 僅支援透過 argv 傳入 URL;
// 在 Node 程序內注入後立即清除環境變數,避免憑證暴露在 OS 程序參數中。
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
#!/usr/bin/env python3
"""啟動本機 K3s 的唯讀 PostgreSQL / Redis MCP 服務:憑證不入 Git、不進程序參數、不漏 stderr。"""
import argparse, importlib.util, json, os, shutil, sys
from pathlib import Path
from urllib.parse import quote

PLUGIN_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
# 上游服務端可能在 stderr 印出連線字串,啟動前重新導向避免外洩憑證。
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 靜音

系列導覽