前三篇折腾完,本机已经攒了一整套顺手的工程化配置:agyr 启动器、目录级会话选择器、五色标题、MCP 懒加载代理、防逃逸 Hooks、全局 Skills 和 Chrome 标签组扩展。

东西越调越顺手,焦虑也跟着来了:万一硬盘挂了、或者明天换台 macOS / 新开发机,难道要对着笔记重新拼一遍?

我去 GitHub 翻了一圈现成的 Antigravity 备份工具(antigravity-storage-manager、antigravity-sync 等),发现它们大多只盯着 IDE 和聊天记录,覆盖不到 CLI 侧分散在 ~/.gemini/bin、~/.agents/skills、~/.agy-powerline、systemd 和 ~/.zshrc 里的自写脚本;而直接把整目录塞进 Git 或用 GNU Stow 软链,又会被 1.1 GB 的会话库、244 MB 的 node_modules 和程序随手写的缓存文件瞬间污染。

这篇记录我最终落地的零第三方依赖备份与新机初始化方案:一套 manifest.json + sync.py + init.sh,配合跨平台改造和 systemd --user 每日定时推送,做到「平时零感知自动备份,换机一条 ./init.sh 还原」。

AGY 环境白名单备份、跨平台适配与新机一键初始化


一、先拆清 1.4 GB 目录里哪些真该进 Git

动手写脚本前,先用 du -sh ~/.gemini/* 量了一遍本机真实体量,结果非常反直觉——1.4 GB 里真正独一无二、丢了最肉疼的自写代码和配置,加起来只有 1.1 MB:

分层 路径与实测体积 备份策略
核心配置与脚本(约 1.1 MB) ~/.gemini/bin/ (92K)
~/.gemini/config/ (544K,排除 node_modules)
~/.gemini/antigravity-cli/{settings.json,title.py}
~/.gemini/chrome-tab-group-ext/ (20K)
~/.gemini/memory/knowledge-graph.jsonl (108K)
~/.agents/skills/(排除云端 synced/)
~/.agy-powerline/{statusline.config.json,install.json,statusline.js}
~/.config/systemd/user/antigravity-cli-daemon.service
强白名单进私有 Git 仓库
可重建依赖(244 MB) ~/.gemini/mcp-servers/* **不备 node_modules**,只备 4 组 package.json + package-lock.json,新机 npm ci 十秒锁版本还原
敏感凭据(8 KB) ~/.gemini/secrets/jira.env 绝不入库,仓库只放 templates/jira.env.example
运行态大数据(1.1 GB) ~/.gemini/antigravity-cli/{conversations,brain,log,cache} 不进 Git;有归档需求另走 sqlite3.backup() 冷备

顺手踩出来的两个「最容易漏备的角落」:

  • ~/.agents/skills/:全局自定义技能(如 code-review、debug-root-cause、git-commit)藏在这里,不在 ~/.gemini/ 里;同目录下的 synced/ 是云端自动同步的,必须排除。
  • ~/.gemini/memory/knowledge-graph.jsonl:跨会话知识图谱记忆是纯文本 JSONL,放进私有 Git 顺带白嫖一份记忆变更历史。

二、先把 ~/.zshrc 里的 agyr 拆干净

千万别把整份 ~/.zshrc 直接拿去备份——里面混着 CUDA、代理、公司路径等大量单机配置。

我把第 1 篇写进 ~/.zshrc 的那 80 行 D-Bus/Keyring 补全和 agyr() 抽成一个独立文件 ~/.gemini/bin/agyr.zsh(并且顺手把 /home/user/.local/bin 改成 $HOME/.local/bin),~/.zshrc 末尾只留一个带起止标记的三行块:

1
2
3
# >>> ai-env agyr >>>
[[ -r "$HOME/.gemini/bin/agyr.zsh" ]] && source "$HOME/.gemini/bin/agyr.zsh"
# <<< ai-env agyr <<<

这样还原脚本在任意新机器上只要按标记块幂等追加或更新,**永远不会覆盖破坏新机原有的 .zshrc**。


三、白名单同步器:路径归一化、多机字段合并与防泄密门禁

我没引入 chezmoi(不想为了备份 AGY 专门装新工具再记一套 .tmpl 规则),直接用 Python 标准库写了 manifest.json + sync.py,预留 files/agy/、files/claude/、files/codex/ 顶层目录,方便以后把其他 AI 工具一并纳管。

完整数据流如下:

1. 为什么必须做 JSON 字段级合并(strip_keys)

如果只有一台开发机,整文件拷贝看不出问题;一旦同时在公司 Linux 和家里 macOS 上跑同步,有两个文件一定会来回打架:

  • settings.json 里的 trustedWorkspaces(两台机器的仓库路径完全不同);
  • config.json 里的 userSettings.cliRemoteControlHostname 和 remoteControlHostname(每台机器的远程控制实例名不同)。

在 manifest.json 里声明 strip_keys 就能干净解耦:

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
{
"version": 2,
"placeholder": "__HOME__",
"node_placeholder": "__NODE__",
"max_file_bytes": 2097152,
"items": [
{
"id": "gemini-config-json",
"type": "file",
"source": ".gemini/config/config.json",
"repo": "files/agy/gemini/config/config.json",
"templated": true,
"mode": "0600",
"strip_keys": [
"userSettings.cliRemoteControlHostname",
"userSettings.remoteControlHostname"
]
},
{
"id": "gemini-cli-settings",
"type": "file",
"source": ".gemini/antigravity-cli/settings.json",
"repo": "files/agy/gemini/antigravity-cli/settings.json",
"templated": true,
"mode": "0600",
"strip_keys": ["trustedWorkspaces"]
}
]
}

sync.py 导出时自动删掉这些键、同时把本机 shutil.which("node")(如 /usr/bin/node)替换成 __NODE__;还原时如果目标机已经存在该 JSON,就把目标机原有的单机字段合并回去,同时把 __NODE__ 展开成目标机真实的 Node 路径(比如 Apple Silicon macOS 的 /opt/homebrew/bin/node):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def restore_file(src: Path, dest: Path, *, templated: bool, replacements: list[tuple[str, str]],
strip_keys: list[str] | None = None, mode: int | None = None) -> None:
raw = src.read_bytes()
if templated and is_text_bytes(raw):
text = apply_replacements(raw.decode("utf-8"), replacements)
raw = text.encode("utf-8")

if strip_keys and dest.is_file() and is_text_bytes(raw):
incoming = json.loads(raw.decode("utf-8"))
existing = json.loads(dest.read_text(encoding="utf-8"))
if isinstance(incoming, dict) and isinstance(existing, dict):
for key_path in strip_keys:
found, val = get_nested(existing, key_path)
if found:
set_nested(incoming, key_path, val)
raw = (json.dumps(incoming, ensure_ascii=False, indent=2) + "\n").encode("utf-8")

write_file_atomic(dest, raw, mode=mode)

2. 提交前四重防泄密门禁(sync.py check)

私有仓库也不能裸奔。sync.py push 在 git commit 前强制跑四项检查,任意一条命中直接退出并弹桌面通知:

  • 禁止目录/文件名:拒绝任何 secrets/、node_modules/、.git/、*.env(仅放行 *.env.example)、*.key、*.pem、*.db;
  • 单文件上限 2 MB:防止哪天手滑把 SQLite 数据库或二进制放进白名单目录;
  • 敏感特征正则:扫描 ghp_/gho_、sk-、AKIA...、PRIVATE KEY、JIRA_PERSONAL_TOKEN=<非空值>;
  • 未归一化路径检查:确认 templated 条目里不残留原始本机 $HOME。

四、真正决定「换 macOS / Windows 能不能跑通」的 4 处跨平台改造

备份库建好之后,我把第 1、2 篇的脚本逐行对着 macOS 和 Windows 过了一遍,揪出了 4 处原版在非 Linux 环境下必挂的硬伤,顺手全部改掉:

原版写法 换系统后会出什么错 跨平台改造
title.sh(bash4 mapfile + jq + sha256sum) macOS 默认 bash 3.2 **没有 mapfile**,也没有 sha256sum(叫 shasum -a 256) 改写成 80 行零依赖 title.py,settings.json 切到 python3 ~/.gemini/antigravity-cli/title.py
ask-question-state.py 只调 xdotool / notify-send macOS 静默无通知,/tmp 写死 改用 tempfile.gettempdir(),增加 sys.platform == "darwin" 分支,用 osascript 查前台终端与弹系统通知
chrome-devtools-mcp-lazy.py 写死 /usr/bin/google-chrome 与 import fcntl macOS 路径是 /Applications/Google Chrome.app/...;原生 Windows Python 直接 ImportError: fcntl 按 sys.platform 自动探测 Chrome / Docker 路径;POSIX 用 fcntl、Windows 用 msvcrt;mcp_config.json 改用 python3 直接启动,甩掉 .sh 壳
chrome-tab-group-ext 不带 "key" Chrome 按本地绝对路径哈希算扩展 ID,换用户名或系统 ID 必变,换机还要手抄 在 manifest.json 写入固定 RSA 公钥 "key",永久锁死跨机一致的 Extension ID

1. 给 Chrome 未打包扩展锁死永久 ID

很多人不知道 Chrome 未打包扩展的 ID 是怎么算出来的:如果 manifest.json 里没有 "key",Chrome 就拿文件夹绝对路径算哈希;一旦写进 Base64 编码的 DER 格式 RSA 公钥 "key",Chrome 就只认公钥的 SHA-256 前 16 字节(映射到 a-p),任何操作系统、任何目录加载出来都是同一个 32 位 ID:

1
2
3
4
5
6
7
8
9
10
import base64, hashlib, subprocess

# 仅提取公钥写入 manifest.json,私钥不落盘直接丢弃
priv = subprocess.check_output(["openssl", "genrsa", "2048"], stderr=subprocess.DEVNULL)
pub_der = subprocess.check_output(["openssl", "rsa", "-pubout", "-outform", "DER"], input=priv, stderr=subprocess.DEVNULL)
b64_key = base64.b64encode(pub_der).decode("ascii")
digest = hashlib.sha256(pub_der).hexdigest()[:32]
ext_id = "".join(chr(ord("a") + int(c, 16)) for c in digest)
print("EXT_ID =", ext_id)
print("PUB_KEY =", b64_key)

把生成的 PUB_KEY 贴进 ~/.gemini/chrome-tab-group-ext/manifest.json 的 "key" 字段,再把 EXT_ID 写进同目录的 extension_id 并纳入备份仓库。以后换新机只要加载一次目录,再也不用去复制粘贴扩展 ID 了。

2. macOS 原生通知防注入写法(ask-question-state.py)

顺带提一个小细节:用 Python 调 osascript 发 macOS 通知时,千万别用 f-string 把标题/正文直接拼进 AppleScript 字符串里(项目名带引号会直接语法报错或命令注入),改成 on run argv 通过命令行参数传递最干净:

1
2
3
4
5
6
7
8
9
if sys.platform == "darwin":
osascript = shutil.which("osascript")
if osascript:
script = "on run argv\ndisplay notification (item 2 of argv) with title (item 1 of argv)\nend run"
subprocess.Popen(
[osascript, "-e", script, title, body],
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
start_new_session=True, close_fds=True,
)

五、新机一键初始化(init.sh)与每日定时自动推送

光有 sync.py restore 还不够——换台新机器时,我希望 git clone 完只要敲一条 ./init.sh 就把能自动化的全干完。

init.sh 支持 --target DIR 和 --skip-npm,专门用来在 /tmp 空目录里反复演练验证(没演练过的备份等于没备份):

1
2
3
4
5
6
# 模拟一台已有本机工作区和主机名的 macOS 机器还原
python3 sync.py restore --target /tmp/test-cross-machine --node-bin /opt/homebrew/bin/node

# 跑两遍 init.sh 确认幂等性(.zshrc 不会重复追加、权限 700/600/755 准确)
./init.sh --target /tmp/test-restore --skip-npm
./init.sh --target /tmp/test-restore --skip-npm

最后用 systemd --user 定时器解决「两周后就忘了手动推」的人性弱点:

1
2
3
4
5
6
7
8
9
10
11
# ~/.config/systemd/user/ai-env-backup.timer
[Unit]
Description=Daily backup of local AI/AGY environment

[Timer]
OnCalendar=*-*-* 20:30:00
RandomizedDelaySec=10m
Persistent=true

[Install]
WantedBy=timers.target

Persistent=true 保证哪怕 20:30 关着机,下次开机也会自动补跑;配套的 service 里调 python3 .../sync.py push --quiet,没变更时直接静默退出 0,有变更(比如记忆图谱或脚本更新)且通过安全扫描才自动提交并走 SSH 推送。

配完 systemd --user 定时任务后,一定要手动跑一次 systemctl --user start <service> 实测,不要只看 timer 列表就以为稳了——systemd 后台环境变量很干净,实测跑通一次才能确认 SSH 密钥、Git 作者信息和推送链路在后台真的没问题。


系列导航