- docs/consultant-review/: review brief, per-batch post dumps (01-10), audit-tracker.json + AUDIT-TRACKER.md generated by scripts/manage_review.py - scripts/manage_review.py: list/approve/approve-batch/generate over the tracker - docs/consultant-review-2026-10-27-posts-and-casestudies-plan.md: locked decision register + 4 work orders for the /posts/ archive rework and the case-studies portfolio treatment
4105 lines
225 KiB
Markdown
4105 lines
225 KiB
Markdown
# 博客文章顾问审阅资料包 — Batch-02
|
||
|
||
> **批次编号**:`Batch-02`
|
||
> **包含文章数**:10 篇
|
||
> **本批次总字符量**:160,519 字(严格限制 < 200,000 字)
|
||
> **模式**:BILINGUAL
|
||
> **生成时间**:2026-10-27 03:02:03
|
||
|
||
# 外部顾问审阅前置须知与工程背景规范
|
||
|
||
> **本文档目标**:本批次包含 `blog.hoelee.com` 的待审阅技术文章全文。请外部顾问在审阅正文与技术主张时,以此规范为最高评估准则。
|
||
|
||
## 1. 站点定位与双重业务目的
|
||
- **受众 A(技术招聘官 / 资深技术主管)**:寻找具备 Senior 全栈 + DevOps + AI 智能体闭环能力的架构工程师。文章定位为**“不可伪造的工程实操交付证据(Proof of Expertise)”**,要求代码真实、日志可查、有架构权衡与技术深度。
|
||
- **受众 B(中小企业主 SME / 商业客户)**:寻找能提供系统研发、私有化部署、24/7 AI 获客系统、高可用基础设施的技术顾问。文章需清晰阐述业务痛点、商业 ROI、上线效率与交付保障。
|
||
|
||
## 2. 核心人设铁律与工程硬约束(必须严格遵守)
|
||
1. **彻底杜绝业余爱好者/玩具口吻**:
|
||
- ❌ **绝对禁用词**:`homelab`, `home lab`, `家用`, `小主机`, `玩具`, `折腾`。
|
||
- ✅ **标准替代词**:`the infrastructure I manage`(我管理的私有基础设施)、`self-hosted production node`(自托管生产节点)、`on-premise host`(私有化服务器)。
|
||
2. **严禁捏造虚假指标与性能数字**:
|
||
- 所有 benchmark 数据必须有明确的测试基准与单设备限制。
|
||
- 严格区分“耗时减少比例”与“吞吐加速倍数”(例如耗时从 352s 降至 218s 是耗时减少 38.0%,吞吐提升 1.61×,严禁偷换概念混淆)。
|
||
- 时间戳精度与物理帧对齐:视频帧率上限(如 30 fps 单帧 33.3ms)不可妄称“微秒级精确”。
|
||
3. **去模板化叙事与真实物理锚点**:
|
||
- 拒绝千篇一律的 AI 模板味。文章采用三大叙事架构:① 故障排查谜案(Symptom → False Lead → Kernel Evidence → Fix);② 商业交付复盘(Client Bottleneck → Trade-offs → State Machine → ROI);③ 架构演进对比(V1 Naive → Concurrency Crash → V2 Redesign)。
|
||
- 每篇文章必须包含至少一个物理真实世界锚点(主机真实硬件规格、生产维护窗口、真实业务场景)。
|
||
4. **代码与配置展示规范**:
|
||
- 超过 20 行的配置或日志采用 HTML `<details><summary>` 原生折叠,`<summary>` 必须精准标注文档名与行数。
|
||
|
||
## 3. 顾问重点开刀维度
|
||
- [ ] **事实与数字可核性**:技术判断与性能数据是否自洽?有无过度夸大?
|
||
- [ ] **人设与语调纯洁性**:有无遗漏的 hobbyist/homelab 口吻?
|
||
- [ ] **双轨转化引导有效性**:是否有清晰的业务价值提炼与行动召唤(CTA)?
|
||
- [ ] **代码与生产安全性**:有无未脱敏的凭据、绝对内部私密路径或不安全的权限配置?
|
||
|
||
|
||
---
|
||
|
||
## 本批次文章目录索引
|
||
|
||
1. [case-studies] **如何用并行子代理在三小时内核查 20 家 VPS 服务商** (`how-i-vetted-20-vps-providers-with-parallel-subagents`) — ~11,778 字符
|
||
2. [case-studies] **没有 Coding Agent 的 Loop Engineering:撑起我这套基础设施的 11 个定时任务** (`loop-engineering-without-a-coding-agent`) — ~20,707 字符
|
||
3. [case-studies] **用一个 Prometheus 监控 unRaid、群晖 NAS 和 VPS:我做错的四件事** (`one-prometheus-for-unraid-synology-and-a-vps`) — ~12,936 字符
|
||
4. [case-studies] **一个人跑生产基础设施:三台主机、162 个容器** (`running-production-infrastructure-solo`) — ~11,669 字符
|
||
5. [case-studies] **数字商品的自愈式访问控制:NocoDB、n8n 与 AList** (`self-healing-digital-goods-entitlements`) — ~21,593 字符
|
||
6. [case-studies] **自建语音转文字服务:打字速度的五倍,而且数据不出内网** (`self-hosted-speech-to-text-api`) — ~22,254 字符
|
||
7. [case-studies] **从云端转本地:在 12GB 显卡与群晖 N8N 上搭建中英混读高保真 TTS 语音栈** (`self-hosted-tts-cosyvoice2-n8n-gpu`) — ~12,885 字符
|
||
8. [case-studies] **我如何在自家 NAS 上自托管 Mem0 记忆栈(让 AI 助手有记忆)** (`self-hosting-mem0-memory-stack`) — ~12,602 字符
|
||
9. [case-studies] **把 AI 修图工具做成 WordPress 插件:22 个版本换来的经验** (`shipping-an-ai-photo-editor-as-a-wordpress-plugin`) — ~20,578 字符
|
||
10. [case-studies] **在多台机器之间同步一个会自我学习的 AI Agent** (`syncing-a-self-improving-ai-agent-across-machines`) — ~13,517 字符
|
||
|
||
---
|
||
|
||
## 文章 01 / 10:如何用并行子代理在三小时内核查 20 家 VPS 服务商
|
||
- **Slug**: `how-i-vetted-20-vps-providers-with-parallel-subagents`
|
||
- **英文标题**: How I Vetted 20 VPS Providers in Three Hours with Parallel Subagents
|
||
- **分类**: `case-studies` | **发布日期**: 2025-11-12
|
||
- **线上地址**: https://blog.hoelee.com/posts/how-i-vetted-20-vps-providers-with-parallel-subagents/ (EN) | https://blog.hoelee.com/posts/zh/how-i-vetted-20-vps-providers-with-parallel-subagents/ (ZH)
|
||
- **本篇审核状态**: ⏳ 待审核 (Pending)
|
||
|
||
### ✍️ 顾问审阅意见区 (Review Feedback)
|
||
```text
|
||
【审阅结论】:[ ] 通过 [ ] 需微调 [ ] 需重构
|
||
【事实与数字核对】:
|
||
【人设与用词卫生】:
|
||
【CRO与转化建议】:
|
||
```
|
||
|
||
### 🇨🇳 中文版原文 (Chinese Markdown Twin)
|
||
````markdown
|
||
---
|
||
title: "如何用并行子代理在三小时内核查 20 家 VPS 服务商"
|
||
description: "一个关于编排并行 AI 子代理对 20 家主机服务商做尽职调查的案例研究——WHOIS、AUP 和口碑核查——把数小时的研究任务压缩成一份结构化、可追溯的供应商评分卡。"
|
||
pubDate: 2025-11-12
|
||
updatedDate: 2026-09-09
|
||
category: case-studies
|
||
blueprint: sme-digital-suite
|
||
blueprintLayer: L4-managed-ops-handover
|
||
tags: [ai-orchestration, subagents, due-diligence, hosting, devops]
|
||
ogImage: /og/zh-how-i-vetted-20-vps-providers-with-parallel-subagents.jpg
|
||
banner: /banners/how-i-vetted-20-vps-providers-with-parallel-subagents.jpg
|
||
---
|
||
|
||
## 为什么这很重要
|
||
|
||
选主机服务商,本质是用一张信用卡和一次 DNS 变更来下注。选错了,「保证在线率」
|
||
会变成凌晨两点的封停邮件,「注重隐私」会变成一条你从没读过的日志留存条款。
|
||
|
||
问题不是信息不够,而是信息散落在每家服务商的十几个页面里(WHOIS 记录、可接受使用
|
||
政策、隐私政策、价格页、第三方评测站),手工核查又慢又枯燥又容易出错。一家服务商
|
||
就是五个标签页,二十家就是一百个标签页和一下午搭进去的时间。
|
||
|
||
这个故事讲的是我怎么把那一整个下午压到大约三小时——不是靠更快地干活,而是靠编排
|
||
一支 AI 子代理小队并行跑完枯燥的部分,再用同一张清单给所有结果打分。
|
||
|
||
## 问题:我不能靠信仰去核实的那些声明
|
||
|
||
我要为一个有硬性要求的项目筛选服务商:具体的司法辖区、付款方式、流量条款。这些
|
||
没有一样是首页上诚实地写出来的。它们诚实地写在那些无聊的文档里——WHOIS 记录显示
|
||
域名才四个月、AUP 静悄悄地禁掉你正想跑的服务、隐私政策承认自己保留日志。
|
||
|
||
难就难在,核实一家服务商意味着读五份互相矛盾的文档。营销说「自 2012 年起」,
|
||
WHOIS 说「今年四月才注册」。特性页说「允许所有流量」,AUP 说「禁止 Tor 中继」。
|
||
一家服务商就是一次事实核查,二十家就是一个研究项目。
|
||
|
||
## 第一次尝试:一个 agent,一个大循环
|
||
|
||
我最先想到的当然是显而易见的那个——单个助手从头到尾挨个处理这份名单,逐家抓取
|
||
文档、记笔记、往下走。
|
||
|
||
它能跑。但它对这份工作的形状来说是错的工具。这活儿**天然可并行**:7 号服务商的
|
||
WHOIS 查询和 3 号服务商的隐私政策毫无关系。串行跑意味着总耗时是每次抓取之和,而且
|
||
——更重要的是——上下文窗口会被我已经翻过去的那几家的半成品笔记塞满。到第八九家
|
||
的时候,早期的发现就被后面的挤掉了。
|
||
|
||
教训是:一个对独立条目做扁平循环的任务,不是推理问题,而是扇出(fan-out)问题。
|
||
一个长长的上下文是装它的错误容器。
|
||
|
||
## 修复:用并行子代理扇出,然后统一打分
|
||
|
||
真正奏效的结构是三层:
|
||
|
||
**1. 一张不在乎指向谁的清单。** 在派发任何东西之前,我先写下对每家服务商而言
|
||
「已核实」具体意味着什么:
|
||
|
||
- 域名注册日期 对比 那个「since」声明
|
||
- 可接受使用政策(AUP),搜我关心的具体服务
|
||
- 隐私政策,读留存条款
|
||
- 第三方口碑(Trustpilot 看趋势,不看均值;社区提及)
|
||
- 流量条款(「防计量」还是一个计量上限)
|
||
|
||
这张清单就是契约。每个子代理都拿到同一份,外加一份要套用的服务商名单。
|
||
|
||
**2. 并行子代理,每个负责一批服务商。** 我把名单拆成几簇,每簇交给一个子代理。
|
||
每个子代理在隔离环境里工作,有自己的上下文、自己的一套抓取,最后为每家服务商
|
||
返回一份结构化的事实清单——不是一段话,而是能直接丢进评分卡的字段。
|
||
|
||
关键是子代理彼此不知道对方。这正是要点:1 号服务商的任何内容都不必和 14 号服务商
|
||
共享上下文空间,各自返回自洽的结果。
|
||
|
||
**3. 一次打分,由我来做,不派发。** 子代理产出发现,判断由我来下。一旦你让子代理
|
||
既*收集*事实又*排序*服务商,你就丢了审计链——只会得到一个没有背后证据支撑的结论。
|
||
把打分集中在自己手里,意味着我随时能说出*为什么*某个东西排到某个位置,并指出是哪条
|
||
WHOIS 记录或哪行 AUP 驱动的。
|
||
|
||
这和我做任何代码审查或重构时用的是一个模式:并行化机械的收集,集中化决策。
|
||
|
||
### 编排实际长什么样
|
||
|
||
大致上,每一批:
|
||
|
||
```text
|
||
子代理 → 「这是清单,这是你那 5 家服务商」
|
||
→ 逐家:抓 WHOIS、AUP、隐私政策、价格、评测
|
||
→ 返回 { 域名年龄, AUP红旗[], 留存条款, 口碑, 流量 }
|
||
我 → 合并进一张评分卡,套用清单,排序,写结论
|
||
```
|
||
|
||
三个子代理并行跑。整轮——二十家服务商、每家五份文档、大约一百次抓取——在手工
|
||
仔细做两三家服务商的时间里就完成了。
|
||
|
||
## 核查到底抓到了什么
|
||
|
||
评分卡暴露了首页永远不会告诉你的真问题:
|
||
|
||
- **一家声称「自 2012 年起值得信赖」的服务商,域名比这晚得多。** WHOIS 显示域名是
|
||
同一年的某个月才注册的——一个「从业多年」的四位数声明,配一个才几个月的域名。
|
||
这要么是换了马甲的壳,要么就是撒谎,无论哪种,它页面上所有其他声明在我眼里都要
|
||
降级。
|
||
|
||
- **两家的 AUP 禁掉了我正想跑的那个服务。** 一家在禁止活动条款里列了「TOR 节点」和
|
||
「匿名化服务」;另一家禁了「反向代理」和「隧道」。两家的特性页却还宣传着相反的话。
|
||
在 AUP 上花十分钟 `Ctrl-F` 就排除了它们——但前提是*我知道该去查 AUP*,而不是
|
||
特性页。
|
||
|
||
- **一家原本看着很便宜的服务商,读了流量条款后不是了。** 一个带 1 TB 计量上限的
|
||
计划上写「无限」,只是营销。对于既要接收又要转发的节点,真实成本翻倍——「便宜」
|
||
的那个选项并不便宜。
|
||
|
||
它们所有的共同点是:致命信息从来都没藏起来。它是*公开*的,躺在服务商法律上有义务
|
||
发布的文档里。这个技能不是秘密渠道,而是知道该读哪份文档,并拿它去对照营销话术。
|
||
|
||
## 我会怎么做不一样
|
||
|
||
子代理的交接能用,但太粗糙。下次我会提前给每个子代理*精确的返回字段*——一份严格的
|
||
输出 schema——而不是一段我事后还得重新解析的散文。结构化输出意味着最后一个子代理
|
||
返回时评分卡就已经建好了,不用再读一遍。
|
||
|
||
我也会更早钉死「这个声明能否独立验证?」这个测试。大多数红旗并不是服务商公然撒谎,
|
||
而是一条我无法对照任何公开记录去核实的声明。把「无法验证」本身当成一种信号,名单
|
||
很快就能缩下来。
|
||
|
||
## 结果
|
||
|
||
大约 20 家服务商、大约 100 次文档抓取,三个子代理并行,耗时相当于手工仔细做两家
|
||
服务商。最终评分卡里的每一项排名都能追溯到一条具体的公开记录——一个 WHOIS 日期、
|
||
一行 AUP 条款、一条留存条款——而不是一种感觉。
|
||
|
||
---
|
||
|
||
## 想为你的企业做这件事吗?
|
||
|
||
无论是 VPS、API 网关还是薪酬服务商,选供应商都是同一种问题:在签约*之前*,把你真正
|
||
依赖的那些声明对照无法被营销篡改的公开记录核实一遍。如果你手里有一份候选供应商或
|
||
工具的短名单,想在投入之前拿到一份结构化、有证据支撑的评估——我可以跑这轮尽职调查,
|
||
然后交给你一张评分卡,而不是一个猜测。
|
||
|
||
[WhatsApp 联系我](https://wa.me/60127972969) 或 [发邮件](mailto:[email protected]?subject=Vendor%20due-diligence%20evaluation) 到 hoelee.com——我帮企业选对基础设施,并搭建配套的自动化。
|
||
````
|
||
|
||
### 🇬🇧 英文版原文 (English Markdown Primary)
|
||
````markdown
|
||
---
|
||
title: "How I Vetted 20 VPS Providers in Three Hours with Parallel Subagents"
|
||
description: "A case study in orchestrating parallel AI subagents to run due diligence on 20 hosting providers — WHOIS, AUP, and reputation checks — collapsing a multi-hour research task into a structured, verifiable vendor scorecard."
|
||
pubDate: 2025-11-12
|
||
updatedDate: 2026-09-09
|
||
category: case-studies
|
||
blueprint: sme-digital-suite
|
||
blueprintLayer: L4-managed-ops-handover
|
||
tags: [ai-orchestration, subagents, due-diligence, hosting, devops]
|
||
ogImage: /og/how-i-vetted-20-vps-providers-with-parallel-subagents.jpg
|
||
banner: /banners/how-i-vetted-20-vps-providers-with-parallel-subagents.jpg
|
||
---
|
||
|
||
## Why it matters
|
||
|
||
Choosing a hosting provider is a bet you place with a credit card and a DNS
|
||
change. Get it wrong and "guaranteed uptime" becomes a suspension email at 2 AM,
|
||
or "privacy-friendly" becomes a log-retention clause you never read.
|
||
|
||
The problem isn't a lack of information — it's that the information is scattered
|
||
across a dozen pages per provider (WHOIS records, acceptable-use policies,
|
||
privacy policies, pricing pages, and third-party review sites), and checking them
|
||
manually is slow, boring, and error-prone. One provider is five tabs. Twenty
|
||
providers is a hundred tabs and an afternoon you don't get back.
|
||
|
||
This is the story of how I collapsed that afternoon into about three hours — not
|
||
by working faster, but by orchestrating a small team of AI subagents to run the
|
||
boring part in parallel, and scoring everything against one checklist.
|
||
|
||
## The problem: verifying claims I couldn't take on faith
|
||
|
||
I needed to shortlist providers for a project with hard requirements: specific
|
||
jurisdictions, payment methods, and traffic terms. None of those are written
|
||
honestly on a homepage. They're written honestly in the boring documents — the
|
||
WHOIS record that shows a domain is four months old, the AUP that quietly bans
|
||
the exact service you wanted to run, the privacy policy that admits to log
|
||
retention.
|
||
|
||
The hard part is that verifying one provider means reading five documents that
|
||
disagree with each other. The marketing says "since 2012"; the WHOIS says "this
|
||
April." The features page says "all traffic allowed"; the AUP says "Tor relays
|
||
prohibited." One provider is a fact-checking exercise. Twenty is a research
|
||
project.
|
||
|
||
## What I tried first: one agent, one big loop
|
||
|
||
My first instinct was the obvious one — a single assistant that works through the
|
||
list, provider by provider, fetching each document, taking notes, moving on.
|
||
|
||
It worked. It was also the wrong tool for the shape of the job. The work is
|
||
*embarrassingly parallel*: provider #7's WHOIS lookup has nothing to do with
|
||
provider #3's privacy policy. Running them one after another meant the total time
|
||
was the sum of every fetch, and — more importantly — the context window filled
|
||
with half-finished notes from providers I'd already moved past. By provider
|
||
eight or nine, early findings were getting crowded out by later ones.
|
||
|
||
The lesson: a task that's a flat loop over independent items isn't a reasoning
|
||
problem, it's a fan-out problem. One long context is the wrong container for it.
|
||
|
||
## The fix: fan out with parallel subagents, then score once
|
||
|
||
The structure that worked was three layers:
|
||
|
||
**1. A checklist that doesn't care which provider it's pointed at.** Before
|
||
spawning anything, I wrote down exactly what "verified" means per provider:
|
||
|
||
- domain registration date vs. the "since" claim
|
||
- acceptable-use policy, searched for the specific service I cared about
|
||
- privacy policy, read for the retention clause
|
||
- third-party reputation (Trustpilot trend, not average; community mentions)
|
||
- traffic terms ("unmetered" vs. a metered cap)
|
||
|
||
That checklist was the contract. Every subagent got the same one, plus a list of
|
||
providers to run it against.
|
||
|
||
**2. Parallel subagents, one per batch of providers.** I split the pool into
|
||
clusters and handed each cluster to its own subagent. Each one worked in
|
||
isolation, with its own context and its own set of fetches, and returned a
|
||
structured fact sheet per provider — not a paragraph, but fields I could drop
|
||
straight into a scorecard.
|
||
|
||
The key here is that the subagents don't know about each other. That's the
|
||
point: nothing from provider #1 has to share context space with provider #14.
|
||
Each returns a self-contained result.
|
||
|
||
**3. A single scoring pass, done by me, not delegated.** The subagents produced
|
||
findings; I did the judgment. The moment you let a subagent both *gather* the
|
||
facts and *rank* the providers, you lose the audit trail — you get a verdict
|
||
without the evidence behind it. Keeping scoring central means I can always say
|
||
*why* something ranked where it did, and point at the exact WHOIS record or AUP
|
||
line that drove it.
|
||
|
||
This mirrors a pattern I'd use for any code review or refactor: parallelize the
|
||
mechanical collection, centralize the decisions.
|
||
|
||
### What the orchestration actually looked like
|
||
|
||
Roughly, per batch:
|
||
|
||
```text
|
||
subagent → "here's the checklist, here are your 5 providers"
|
||
→ per provider: fetch WHOIS, AUP, privacy policy, pricing, reviews
|
||
→ return { domain_age, aup_flags[], retention, reputations, traffic }
|
||
me → merge into one scorecard, apply the checklist, rank, write up
|
||
```
|
||
|
||
Three subagents ran side by side. The whole pass — twenty providers, five
|
||
documents each, one hundred-ish fetches — landed in the time it would have taken
|
||
me to do two or three providers carefully by hand.
|
||
|
||
## What the verification actually caught
|
||
|
||
The scorecard surfaced real problems that a homepage never would have:
|
||
|
||
- **A provider whose "trusted since 2012" claim was younger than the domain.**
|
||
WHOIS said the domain was registered that same year — a four-figure "years in
|
||
business" claim on a domain months old. That's either a re-branded shell or a
|
||
lie, and either way it downgraded every other claim on the page in my eyes.
|
||
|
||
- **Two providers whose AUP banned the exact service I wanted to run.** One
|
||
listed "TOR nodes" and "anonymizing services" in its prohibited-activity
|
||
clause; another banned "reverse proxies" and "tunnels." Both still advertised
|
||
the opposite on their features pages. Ten minutes of `Ctrl-F` on the AUP is all
|
||
it took to rule them out — but only once I *knew to check the AUP* instead of
|
||
the features page.
|
||
|
||
- **A provider that looked cheap until I read the traffic terms.** "Unlimited" on
|
||
a plan with a metered 1 TB cap is marketing. For a relay that both receives and
|
||
forwards traffic, the real cost doubles — the "cheap" option wasn't.
|
||
|
||
The pattern across all of them: the disqualifying information was never hidden.
|
||
It was *public*, sitting in a document the provider is legally required to
|
||
publish. The skill isn't secret access — it's knowing which document to read and
|
||
checking it against the marketing.
|
||
|
||
## What I'd do differently
|
||
|
||
The subagent hand-off worked, but it was blunt. Next time I'd give each subagent
|
||
the *exact* fields to return up front — a strict output schema — rather than a
|
||
prose summary I then have to re-parse. Structured output means the scorecard is
|
||
built by the time the last subagent returns, with no re-reading.
|
||
|
||
I'd also pin the "is this claim independently verifiable?" test earlier. Most of
|
||
the red flags weren't a provider lying outright; they were a claim I couldn't
|
||
check against any public record. Treat "unverifiable" as its own signal, and the
|
||
shortlist shrinks fast.
|
||
|
||
## The result
|
||
|
||
~20 providers audited across ~100 document fetches, three subagents running in
|
||
parallel, in the time a careful manual pass would have spent on two providers.
|
||
Every ranking in the final scorecard traces back to a specific public record —
|
||
a WHOIS date, an AUP line, a retention clause — not a vibe.
|
||
|
||
---
|
||
|
||
## Want this for your business?
|
||
|
||
Choosing a vendor is the same shape of problem whether it's a VPS, an API
|
||
gateway, or a payroll provider: verify the claims you're relying on *before* you
|
||
sign, against public records that can't be edited by marketing. If you've got a
|
||
shortlist of vendors or tools and you want a structured, evidence-backed
|
||
evaluation before you commit — I can run the due-diligence pass and hand you a
|
||
scorecard, not a hunch.
|
||
|
||
[WhatsApp me](https://wa.me/60127972969) or [email me](mailto:[email protected]?subject=Vendor%20due-diligence%20evaluation) at hoelee.com — I help businesses pick the right infrastructure and build the automation around it.
|
||
````
|
||
|
||
---
|
||
|
||
## 文章 02 / 10:没有 Coding Agent 的 Loop Engineering:撑起我这套基础设施的 11 个定时任务
|
||
- **Slug**: `loop-engineering-without-a-coding-agent`
|
||
- **英文标题**: Loop Engineering Without a Coding Agent: The 11 Cron Jobs That Run My Infrastructure
|
||
- **分类**: `case-studies` | **发布日期**: 2026-10-01
|
||
- **线上地址**: https://blog.hoelee.com/posts/loop-engineering-without-a-coding-agent/ (EN) | https://blog.hoelee.com/posts/zh/loop-engineering-without-a-coding-agent/ (ZH)
|
||
- **本篇审核状态**: ⏳ 待审核 (Pending)
|
||
|
||
### ✍️ 顾问审阅意见区 (Review Feedback)
|
||
```text
|
||
【审阅结论】:[ ] 通过 [ ] 需微调 [ ] 需重构
|
||
【事实与数字核对】:
|
||
【人设与用词卫生】:
|
||
【CRO与转化建议】:
|
||
```
|
||
|
||
### 🇨🇳 中文版原文 (Chinese Markdown Twin)
|
||
````markdown
|
||
---
|
||
title: "没有 Coding Agent 的 Loop Engineering:撑起我这套基础设施的 11 个定时任务"
|
||
description: "Loop engineering 是 2026 年对「设计让 agent 自己反复跑的系统」的叫法。我把它用在自己的自托管基础设施上而不是代码库上:11 个 cron,其中 8 个完全没有 AI。"
|
||
pubDate: 2026-10-01
|
||
category: case-studies
|
||
blueprint: self-hosted-infrastructure
|
||
blueprintLayer: L3-observability-self-healing
|
||
tags: ["loop-engineering", "ai-agents", "cron", "self-hosting", "automation", "monitoring"]
|
||
ogImage: "/og/zh-loop-engineering-without-a-coding-agent.jpg"
|
||
banner: "/banners/loop-engineering-without-a-coding-agent.jpg"
|
||
draft: false
|
||
---
|
||
|
||
关于 loop engineering 的文章,几乎全都在讲 coding agent:Claude Code、Codex、`/goal`、`/loop`。例子永远是同一个形状——一个 agent 整晚替你重构某个代码仓库。
|
||
|
||
我没有这个问题。我自己搭了一套自托管的基础设施——一台 NAS、两台服务器、邮件、反向代理、CI runner——我的循环维持的是**这套东西**,不是代码库。这台机器上跑着 11 个定时任务:每五分钟跳一次的端点看门狗、一天两次的邮件分诊、平台优惠券审计、磁盘损坏检查、域名到期提醒,以及一个专门发现「某次升级偷偷把我的代理头配置重置了」的守卫。
|
||
|
||
这 11 个里面,有 8 个完全不含 AI。
|
||
|
||
## 为什么这件事比 agent 本身重要
|
||
|
||
凌晨两点挂掉的服务,只会一直挂到有人发现。域名到期,等于邮件在无声无息中停掉。SSD 损坏,等于我一个星期的工作没了。这些事都不会自己喊出来——它们只是静静地等,等到有人去看。
|
||
|
||
循环就是那个「有人」。它把「我该去看一下」变成「永远有东西在看,而且只在有事的时候才开口」。带来的好处不是什么魔法级自动化,而是我不再充当监控系统本身:真的出问题会有 Telegram 消息,没事的时候就是安静。
|
||
|
||
这就是全部的价值主张,值得说清楚,因为 2026 年围绕 loop 的炒作承诺的远不止这些。
|
||
|
||
## Loop engineering 到底是什么
|
||
|
||
这个说法是 2026 年 6 月出现的。Peter Steinberger 发帖说,你不该再去 prompt coding agent 了,应该去设计「prompt 这些 agent 的循环」。Anthropic 的 Claude Code 负责人 Boris Cherny 说得更短:*"I don't prompt Claude anymore. I have loops running that prompt Claude. My job is to write loops."* 随后 Addy Osmani 发表那篇给这个实践命名的文章,Anthropic 也在 6 月 30 日正式给了它一套四种循环类型的分类。
|
||
|
||
它是一条不断向外包一层的阶梯上最新的那圈:**prompt engineering**(2022–24,*我说清楚了吗?*)、**context engineering**(2025,*它看到对的东西了吗?*)、**harness engineering**(2026 年初,*它有没有一直做对?*)、**loop engineering**(2026,*它能不能不靠我在跑?*)。没有哪一层取代了前一层。我到现在还在写 prompt,只不过通常写在脚本里。
|
||
|
||
没人非得接受这个名词。The Register 在 6 月就管它叫最新一轮 buzzword,并且提了两点公允的批评:agent 本来就是循环;而最热衷推销「无人值守循环」的,恰恰是那些靠卖 token 赚钱的公司。有一份流传很广的报告声称某套常开的循环方案一个月烧了 130 万美元。连 Osmani 自己那篇文章的结尾都留了最重要的保留意见:*"The loop changes the work, it does not delete you from it."*
|
||
|
||
我的循环几乎不花钱,原因就是下面第一条设计规则。
|
||
|
||
## 清单
|
||
|
||
| 任务 | 触发 | 凭什么算它干成了 | 用模型? |
|
||
|---|---|---|---|
|
||
| 端点看门狗(7 个目标,自愈) | 每 5 分钟 | HTTP/TCP 探测 + 控制探测 | 否——纯脚本 |
|
||
| 磁盘损坏看门狗 | 每天 10:00 | SMART 计数对比基线 | 否 |
|
||
| 域名到期提醒 | 每天 09:00 | 30 天 / 7 天阈值 | 否 |
|
||
| 邮件分诊(`me@hoelee.com`) | 09:30 + 18:30 | 未读邮件,按 message-id 去重 | **是** |
|
||
| 平台优惠券审计 | 每天 09:00 | 只读抓取后台 | **是** |
|
||
| Real-IP + 机器人拦截回归守卫 | 每小时 :20 | 配置不变量 + 日志比例 | 否 |
|
||
| unRaid SSD 看门狗 | 每天 10:00 | 计数增量 | 否 |
|
||
| 邮箱连通性健康检查 | 每月 | IMAP/SMTP 连接 | 否 |
|
||
| 记忆备份 | 每周 | 归档文件写出来了 | 否 |
|
||
| 软件版本检查 | 每天 09:00 | npm 最新版 vs 本地版 | 否 |
|
||
| 研究项目检查点提醒 | 每月 1、15 号 | 读项目状态,提醒我 | **是** |
|
||
|
||
11 个循环,其中 8 个整条路径上没有任何模型。这个比例不是意外,也不是谦虚——它是我学到的最有用的一件事。
|
||
|
||
## 规则一:检查是确定性的,就别花模型去跑
|
||
|
||
我那个软件版本检查原本是 agent 任务。它跑了好几个星期,连续失败了 **29 次**,我才终于不再忽略那些通知。原因有点好笑:agent 模式的定时任务会记录创建时的模型,等我后来改了全局默认模型,这个任务不再悄悄改用新模型,而是干脆整个不跑,打印一行 `[drift_skip]` 就退出。连续 29 次。
|
||
|
||
任务本身其实极其简单:抓 `registry.npmjs.org/<pkg>/latest`,和本地版本比大小,只有远端更新才输出内容。这里面没有任何判断。所以我把它重写成 125 行 Python,每条分支都有明确出口,并把任务改成 `no-agent`——脚本的 stdout 直接作为通知内容,循环里没有 LLM。
|
||
|
||
从此一路全绿。Anthropic 自己的建议也是一句话:*"Use scripts for deterministic work — running a script is cheaper than reasoning through the steps."* 我想补一句更强的版本:如果停止条件是字符串比较,那么在这个循环里放一个模型,唯一的作用就是引入新的失败模式——而且它一定会在凌晨三点、无声无息地引入。
|
||
|
||
在我自己这套任务里的实测差异:11 个循环里有 8 个完全不花 token。用模型的 3 个,需要的都是我写不成代码的判断——这封邮件重不重要、这张券要不要人来处理、这个项目是不是卡住了。
|
||
|
||
## 规则二:验证器必须能大声说出「我自己坏了」
|
||
|
||
第二个我错了很久的地方:一个只在出事时才开口的看门狗,和一个已经死掉的看门狗,表现完全一样——都很安静。
|
||
|
||
所以这套脚本有一个统一契约:**退出码 0 表示「量过了,这是结果」,退出码 1 表示「我量不了」——而退出码 1 永远不静默。** 配置文件不存在、状态文件解析失败、状态目录写不进去、没预料到的异常,全都打印一行 `CANNOT MEASURE` 并退出 1。runner 又把 `main()` 整个包在一层兜底 handler 里,专门接住我没预料到的情况——因为唯一不能容忍的失败模式,是检查器自己悄悄死了。
|
||
|
||
端点看门狗走得更远,这也是整套东西里我最喜欢的一处设计。它在做任何判断之前,先探测一个**控制目标**——`https://one.one.one.one/`。如果这个也失败,那问题出在我自己的上行或 DNS,不是我的服务器,于是看门狗只报告、不动手。没有这道闸门,一次路由器重启看起来就和七个服务同时挂掉一模一样,而一个自动化循环会在这种情况下兴高采烈地去重启一台完全健康的虚拟机。
|
||
|
||
一个分不清「坏了」和「我看不见」的验证器,迟早会在某次网络故障中做出破坏性操作。我宁愿它知道区别。
|
||
|
||
这个循环里我最喜欢引用的数字:它已经连续跑了 **1,618 次**没有误报——因为要连续两次失败才会判定为 down,持续 down 的组会以很慢的节奏重复提醒而不是每个 tick 都喊一遍,恢复只播报一次并附带宕机时长。
|
||
|
||
## 规则三:给它「还能帮上忙」的最小权限
|
||
|
||
最诱人的设计是「让循环自己修好」。能活过生产的版本是三层,每个循环只属于其中一层:
|
||
|
||
**第一层——只报告。** 我大部分循环在这里。它们只观察、只告诉我。它们做什么都不可能弄坏东西,所以我可以周五下午上线。
|
||
|
||
**第二层——提议,人确认。** 优惠券审计每天跑,而且按契约是**只读**的。即使脚本打印出一行建议,prompt 也禁止创建或编辑优惠券,因为那个平台的优惠券没有草稿态:确认就等于上线并冻结押金,背后是真金白银。这个循环的任务是递给我一个十秒钟就能做完的决定。
|
||
|
||
**第三层——按白名单动手。** 整套任务里只有一个循环会动手,条件收得很窄:只有在客户机**从宿主机都不可达**时(用宿主机 ping + ARP 验证过)才重启虚拟机;客户机活着但服务挂了的情况从不自动重启——那是要修的 bug,不是要重启的机器。三次运行的冷却期防住了重启循环。而控制探测失败时,它压根不会启动。
|
||
|
||
这个模式可以推广:**每上一层,都必须用一个我宁可相信它、也不相信 agent 的验证器来换。** 我能不能走开?只有当那个判定「做完了」的东西是我在复盘时也愿意相信的东西时,才行。
|
||
|
||
第三层的克制,也是这些循环另一端的平台要求的。一个会「好心」自己修掉发现问题的审计循环,是违反平台条款的问题,不是战果。
|
||
|
||
## 坑一:一个永远失败的循环,和一个无事可报的循环长得一模一样
|
||
|
||
「健康则静默」这条约定是这些循环能被忍受的原因——没有每日状态刷屏,只有真消息。但它同时也藏住了一个**连续失败 29 次**的任务,因为失败的运行和干净的运行,往我手机上推的都是空。
|
||
|
||
后来有两件事把它修好了,而且适用于任何无人值守的循环:
|
||
|
||
- **一条独立的「我量不了」通路**(规则二)。它本该在第 1 次就暴露 drift,而不是拖到第 29 次。
|
||
- **去看 runner 自己的执行历史,而不只是看收件箱。** 证据一直在那个任务的执行日志里,我却一直相信「没有通知」这件事本身。现在每加一个新循环,我会显式看它头几次的执行记录,而不是等它来告诉我。
|
||
|
||
如果你的循环「已经安静一阵子」了,先去翻它最近十次运行,再下结论。
|
||
|
||
## 坑二:一个会删生产数据的验证器
|
||
|
||
这一条我到现在还疼。我给一条交付流水线写过一个端到端测试脚本,它的清理步骤执行了一条无条件的 `DELETE FROM orders`。它本来是清理自己制造的数据,它也照做了——只是顺带把当时恰好在同一张表里的 7 张真实订单删了,连同生成好的 PDF,而且没有备份可还原。
|
||
|
||
教训不是「要在副本上测」(对,但当时我确实是),而是更窄、更硬的一条:**验证器是一个有权限的程序,它的写入路径需要和它要验证的东西接受同等程度的审视。** 一个我敢让它无人值守运行的循环,只能对自己的产物具有破坏性。现在这套里每个验证脚本都会把清理范围限定在自己造的、带标记的行上——`WHERE id IN ($MINE)` 或者 `WHERE recipient LIKE '%@example.com'`——其中有一个脚本正是因为这次事故被重写的。
|
||
|
||
Osmani 讲的 comprehension debt 就落在这里。循环跑得越顺,你越不会去读它的输出;而它出错的那天,没人在看。这些循环产生的 diff 我都在读。这个习惯就是剩下那部分工作的全部。
|
||
|
||
## 我刻意没有自动化的东西
|
||
|
||
这 11 个循环里有一个,唯一的工作就是提醒我:每半个月提醒我某个研究项目还在,以及下一步该跑哪些命令。它不抓任何东西、不写任何东西、不开浏览器。循环的职责是让**某个**循环继续转动——不一定是它自己那个。
|
||
|
||
这条边界值得说清楚。这 11 个任务买回的是注意力和早期发现。它们不会替我做任何我没有预先交给它们的决定,判断仍然来自我。真正的变化是:我一天当中再也不会花任何时间去想「是不是哪里坏了」。
|
||
|
||
## 我会做得不一样的地方
|
||
|
||
- **从「只报告」这一层开始,并且在里面多待一会儿。** 我在还没有控制探测和冷却期的时候就写过会动手的循环——那是一次靠运气躲过、而不是靠设计躲过的错误。
|
||
- **每个脚本的第一版就带上「量不了」的出口。** 事后给 11 个任务补上花了我一个晚上;其实每个只要一段 `try/except`。
|
||
- **第一天就去看 runner 的执行日志**,而不是等某条通知「感觉该来了」。
|
||
- **在你需要之前就把状态文件写好。** 这里每个循环旁边都有一个小 JSON——第几次运行、上次的状态、什么时候开始 down。没有外部状态的循环,说不出它上一次知道什么,而「它恢复了吗」这件事,大部分答案都在那里。
|
||
|
||
## 结果
|
||
|
||
11 个循环,其中 8 个不带模型、因此也没有 token 账单,覆盖 7 个被监控的端点、一个邮箱、一个平台账号、一组 RAID 阵列,以及一组会被 CyberPanel 或 DSM 升级悄悄重置的代理不变量。端点看门狗已经连续完成 1,618 次 tick,并且把一台卡死的虚拟机从不可达自愈回健康状态,全程我没有碰它一下。整套任务里最贵的那个是每天一次、成本为零的版本检查——而如果我当时没有去读它的历史,它会一直失败下去。
|
||
|
||
如果你在跑任何必须一直活着的东西,那么「loop engineering」有用的那个版本不是一个 agent 舰队,而是:一个停止条件能被测试的 cron 任务、一个说得出「我看不见」的验证器、一条为没预料到的失败准备的出口,以及「允许它只做最小那件事」的权限。从你每周手动检查的那一件事开始,让它变成承重结构。
|
||
|
||
## 我目前的求职状态
|
||
|
||
我是全栈开发 / DevOps 工程师,正在找 remote 或 hybrid 的岗位——平台、基础设施、DevOps 或全栈方向。这个博客就是我的作品集:这里的每一篇,都是我真正做过、并且必须让它持续跑下去的东西,上面这 11 个循环是其中最不花哨、也最实用的部分。
|
||
|
||
**Email:[[email protected]](mailto:[email protected]) · [LinkedIn](https://www.linkedin.com/in/hoelee) · [GitHub](https://github.com/hoelee) · [hoelee.com](https://hoelee.com)**
|
||
````
|
||
|
||
### 🇬🇧 英文版原文 (English Markdown Primary)
|
||
````markdown
|
||
---
|
||
title: "Loop Engineering Without a Coding Agent: The 11 Cron Jobs That Run My Infrastructure"
|
||
description: "Loop engineering is 2026's term for designing the system that prompts and checks an agent. I applied it to self-hosted infrastructure, not a codebase: 11 cron jobs, 8 with no AI at all."
|
||
pubDate: 2026-10-01
|
||
category: case-studies
|
||
blueprint: self-hosted-infrastructure
|
||
blueprintLayer: L3-observability-self-healing
|
||
tags: ["loop-engineering", "ai-agents", "cron", "self-hosting", "automation", "monitoring"]
|
||
ogImage: "/og/loop-engineering-without-a-coding-agent.jpg"
|
||
banner: "/banners/loop-engineering-without-a-coding-agent.jpg"
|
||
draft: false
|
||
---
|
||
|
||
Every article about "loop engineering" is about a coding agent. Claude Code,
|
||
Codex, `/goal`, `/loop`. The examples are always the same shape: an agent
|
||
refactoring a repository overnight while you sleep.
|
||
|
||
I don't have that problem. I run my own self-hosted infrastructure — a NAS,
|
||
a couple of servers, mail, a reverse proxy, a CI runner — and my loops keep
|
||
*that* alive, not a codebase. Eleven scheduled jobs run on this machine: an
|
||
endpoint watchdog that fires every five minutes, mail triage twice a day, a
|
||
marketplace voucher audit, a disk-corruption check, a domain-expiry
|
||
reminder, a guard that notices when an upgrade silently reset my proxy
|
||
headers.
|
||
|
||
Eight of those eleven contain no AI at all.
|
||
|
||
## Why this matters more than the agent does
|
||
|
||
A service that is down at 2am stays down until someone notices. An expiring
|
||
domain is mail that silently stops arriving. A corrupt SSD is a week of my
|
||
work. None of these announce themselves; they all wait quietly until someone
|
||
looks.
|
||
|
||
A loop is that someone. It turns "I should check on that" into "something
|
||
checks on that, forever, and only speaks when there is news." The payoff is
|
||
not magic autonomy — it is that I stopped being the monitoring system. I get
|
||
a Telegram message when something is actually wrong, and silence when it
|
||
isn't.
|
||
|
||
That is the whole value proposition, and it is worth being precise about it,
|
||
because the 2026 hype around loops promises considerably more.
|
||
|
||
## What loop engineering actually is
|
||
|
||
The term arrived in June 2026. Peter Steinberger posted that you shouldn't
|
||
be prompting coding agents anymore — you should be designing the loops that
|
||
prompt them. Boris Cherny, who leads Claude Code at Anthropic, put it even
|
||
shorter: *"I don't prompt Claude anymore. I have loops running that prompt
|
||
Claude. My job is to write loops."* Addy Osmani published the essay that
|
||
gave the practice a name, and Anthropic made it official on June 30 with a
|
||
taxonomy of four loop types.
|
||
|
||
It is the newest ring of a ladder that keeps wrapping itself: **prompt
|
||
engineering** (2022–24, *did I say it clearly?*), **context engineering**
|
||
(2025, *does it see the right thing?*), **harness engineering** (early 2026,
|
||
*does it keep doing it right?*), and **loop engineering** (2026, *does it
|
||
run without me?*). Nothing replaced anything. I still write prompts, usually
|
||
inside a script.
|
||
|
||
Nobody has to adopt the word. The Register called it the latest buzzword in
|
||
June and made two fair points: agents have always been loops, and the
|
||
companies selling tokens are the companies most excited about loops that
|
||
spend tokens unattended. One widely-read report claimed a $1.3M monthly bill
|
||
for an always-on loop setup. Even Osmani's own essay ends with the caveat
|
||
that matters: *"The loop changes the work, it does not delete you from it."*
|
||
|
||
My loops cost me almost nothing, and the reason is the first design rule
|
||
below.
|
||
|
||
## The inventory
|
||
|
||
| Job | Trigger | What proves it worked | Model? |
|
||
|---|---|---|---|
|
||
| Endpoint watchdog (7 targets, self-heal) | every 5 min | HTTP/TCP probe + control probe | no — script |
|
||
| Disk-corruption watchdog | daily 10:00 | SMART counters vs baseline | no |
|
||
| Domain-expiry reminder | daily 09:00 | 30-day / 7-day thresholds | no |
|
||
| Mail triage (`me@hoelee.com`) | 09:30 + 18:30 | unread mail, deduped | **yes** |
|
||
| Marketplace voucher audit | daily 09:00 | read-only portal scrape | **yes** |
|
||
| Real-IP + bot-block regression guard | hourly :20 | config invariants + log ratios | no |
|
||
| unRaid SSD watchdog | daily 10:00 | counter deltas | no |
|
||
| Mailbox health | monthly | IMAP/SMTP connect | no |
|
||
| Memory backup | weekly | archive written | no |
|
||
| Package version check | daily 09:00 | npm latest vs local | no |
|
||
| Research checkpoint reminder | 1st + 15th | reads project state, reminds me | **yes** |
|
||
|
||
Eleven loops, eight of them with no model anywhere in the path. That ratio
|
||
is not an accident and it is not modesty — it is the single most useful
|
||
thing I learned.
|
||
|
||
## Rule 1 — if the check is deterministic, do not spend a model on it
|
||
|
||
My package version check used to be an agent job. It ran for weeks and
|
||
failed 29 times in a row before I stopped ignoring the notifications. The
|
||
cause was almost funny: an agent-mode job records the model it was created
|
||
with, and when my global default model later changed, the job refused to run
|
||
at all rather than silently adopt the new one. It printed `[drift_skip]` and
|
||
exited. Twenty-nine times.
|
||
|
||
The task itself is trivial: fetch `registry.npmjs.org/<pkg>/latest`, compare
|
||
it with the local version, print something only if the remote is newer.
|
||
There is no judgment in that. So I rewrote it as 125 lines of Python with an
|
||
explicit exit path for every branch, and set the job to `no-agent` — the
|
||
script's stdout is delivered as the notification, no LLM in the loop.
|
||
|
||
It has run green ever since. Anthropic's own guidance says the same thing in
|
||
one line: *"Use scripts for deterministic work — running a script is cheaper
|
||
than reasoning through the steps."* I'd add the stronger version: if the
|
||
stop condition is a string comparison, a model in that loop can only
|
||
introduce failure modes, and it will, at 3am, silently.
|
||
|
||
The measured difference in my own fleet: 8 of 11 loops run with zero tokens.
|
||
The three that use a model all need judgment I cannot express as code — is
|
||
this email important, does this voucher need a human, is this project
|
||
stalled.
|
||
|
||
## Rule 2 — the verifier must be able to fail loudly about itself
|
||
|
||
The second thing I got wrong for a long time: a watchdog that only speaks
|
||
when something is broken is indistinguishable from a watchdog that has
|
||
stopped working. Both are silent.
|
||
|
||
So every script in the fleet has one contract: **exit code 0 means
|
||
"measured, here is what I found" and exit code 1 means "I could not measure"
|
||
— and exit 1 is never silent.** A missing config file, an unparseable state
|
||
file, an unwritable state directory, an unexpected exception: all of them
|
||
print a `CANNOT MEASURE` line and exit 1. The runner wraps `main()` in a
|
||
blanket handler that catches anything I failed to anticipate, because the
|
||
one failure mode I cannot tolerate is a checker that has quietly died.
|
||
|
||
The endpoint watchdog goes further, and this is my favourite piece of the
|
||
whole setup. Before it judges anything, it probes a **control target** —
|
||
`https://one.one.one.one/`. If that fails, the problem is my own uplink or
|
||
DNS, not my servers, and the watchdog reports instead of acting. Without
|
||
that gate, a router reboot would look exactly like seven simultaneous
|
||
outages, and an automated loop would have cheerfully restarted a perfectly
|
||
healthy VM in the middle of it.
|
||
|
||
A verifier that cannot tell "broken" from "I can't see" will eventually take
|
||
a destructive action during a network outage. I would rather it know the
|
||
difference.
|
||
|
||
The number I like quoting from this loop: it has ticked **1,618 times**
|
||
without a false alarm, because two consecutive failures are required before
|
||
anything is called down, a group that stays down is re-reported on a slow
|
||
cadence rather than every tick, and recovery is announced once with the
|
||
downtime window.
|
||
|
||
## Rule 3 — give it the smallest autonomy that still helps
|
||
|
||
The tempting design is "the loop fixes things." The design that survives
|
||
contact with production has three tiers, and each loop sits in exactly one:
|
||
|
||
**Tier 1 — report only.** Most of my loops. They observe and tell me. Nothing they do can break anything, which means I can deploy them on a Friday.
|
||
|
||
**Tier 2 — propose, human confirms.** The voucher audit runs daily and is *read-only by contract*. The prompt forbids creating or editing a voucher even if the script prints a proposal, because vouchers on that platform have no draft state: confirming means live and escrowed, with money attached. The loop's job is to hand me a decision I can make in ten seconds.
|
||
|
||
**Tier 3 — act, within an allowlist.** Exactly one loop in the fleet acts, and the conditions are narrow: it restarts a VM only when the guest is *unreachable from the hypervisor* (verified by ping and ARP from the host), never when the guest is up but its service is failing — that is a bug to fix, not a machine to bounce. A three-run cooldown prevents a restart loop. And it never runs at all when the control probe failed.
|
||
|
||
The pattern generalises: **each tier up must earn its right with a verifier
|
||
I trust more than the agent.** Am I allowed to walk away? Only if the thing
|
||
that decides "done" is something I would trust in a post-mortem.
|
||
|
||
That restraint is also what the platform on the receiving end requires. An
|
||
audit that "helpfully" fixed its own findings would be a terms-of-service
|
||
problem, not a win.
|
||
|
||
## Trap 1: a loop that fails forever looks exactly like a loop with nothing to report
|
||
|
||
My silent-when-healthy convention is what makes these loops tolerable — no
|
||
daily status spam, only real news. It also hid a job that had failed **29
|
||
consecutive times**, because a failed run and a clean run both delivered
|
||
nothing to my phone.
|
||
|
||
Two things fixed it, and they apply to any unattended loop:
|
||
|
||
- **A distinct "I could not measure" path** (Rule 2). It would have surfaced the drift on the first run instead of the twenty-ninth.
|
||
- **Check the runner's own history, not just the inbox.** The job's execution log had the evidence the whole time; I trusted the absence of a notification instead. Now, when I add a loop, I check its first few runs explicitly rather than waiting for it to tell me something.
|
||
|
||
If your loop has ever been "quiet for a while", go look at its last ten runs
|
||
before you conclude it is working.
|
||
|
||
## Trap 2: a verifier that deletes production data
|
||
|
||
This one still stings. I had an end-to-end test script for a delivery
|
||
pipeline, and its cleanup step ran an unconditional `DELETE FROM orders`. It
|
||
was written to clean up after itself and it did — along with the seven real
|
||
orders that happened to be in the same table, and their generated PDFs, with
|
||
no backup to restore from.
|
||
|
||
The lesson is not "test on a copy" (true, but I had). It is narrower and
|
||
harder: **a verifier is a program with permissions, and its write path needs
|
||
the same scrutiny as the thing it is verifying.** A loop I trust to run
|
||
unattended must only be destructive to what it created itself. Every
|
||
verification script in the fleet now scopes its cleanup to rows carrying its
|
||
own marker — `WHERE id IN ($MINE)` or `WHERE recipient LIKE '%@example.com'`
|
||
— and one of them did get rewritten after that incident for exactly this
|
||
reason.
|
||
|
||
Osmani's point about comprehension debt lands here. The more smoothly the
|
||
loop runs, the less you read its output — and the day it is wrong, nobody
|
||
was watching. I read the diffs these loops produce. That habit is the entire
|
||
remaining job.
|
||
|
||
## What I deliberately did not automate
|
||
|
||
One of the eleven loops does nothing but remind me, twice a month, that a
|
||
research project exists and here are the commands to run next. It fetches
|
||
nothing, writes nothing, opens no browser. A loop's job is to keep *a* loop
|
||
turning — not necessarily its own.
|
||
|
||
That is the honest boundary. These eleven jobs buy back attention and catch
|
||
failures early. They never make a decision I haven't already handed them,
|
||
and the judgement still comes from me. What changed is that I no longer
|
||
spend any part of my day wondering whether something is broken.
|
||
|
||
## What I would do differently
|
||
|
||
- **Start with the report-only tier and stay there longer.** I wrote one acting loop before I had the control probe and the cooldown, which is a mistake I got lucky on rather than deserved to avoid.
|
||
- **Add the "cannot measure" exit path to the first version of every script.** Retrofitting it across eleven jobs took an evening; it is one `try/except` in each.
|
||
- **Check the runner's execution log on day one**, not when a notification feels overdue.
|
||
- **Write the state file before you need it.** Every loop here keeps a small JSON next to it — tick number, last-known status, when something went down. A loop with no external state cannot tell you what it knew last time, which is most of what "did this recover?" means.
|
||
|
||
## The result
|
||
|
||
Eleven loops, eight of them running with no model and therefore no token
|
||
bill, covering seven monitored endpoints, a mailbox, a marketplace account,
|
||
a RAID array and a set of proxy invariants that a CyberPanel or DSM upgrade
|
||
can silently reset. The endpoint watchdog has completed 1,618 consecutive
|
||
ticks and has self-healed a hung VM from unreachable to healthy without me
|
||
touching it. The most expensive job in the fleet is a daily version check
|
||
that costs nothing and would have kept failing forever if I hadn't read its
|
||
history.
|
||
|
||
If you are running anything you have to keep alive, the useful version of
|
||
"loop engineering" is not a fleet of agents. It is one cron job with a stop
|
||
condition you can test, a verifier that says when it cannot see, an exit
|
||
path for the failure you did not anticipate — and permission to do the
|
||
smallest thing that helps. Start with the one thing you check manually every
|
||
week, and make it load-bearing.
|
||
|
||
## Open to work
|
||
|
||
I'm a full-stack developer and DevOps engineer, and I'm open to remote or
|
||
hybrid roles — platform, infrastructure, DevOps, or full-stack. This blog is
|
||
the work sample: every post here is something I actually built and then had
|
||
to keep running, and the eleven loops above are the least glamorous and most
|
||
useful part of it.
|
||
|
||
**Email: [[email protected]](mailto:[email protected]) · [LinkedIn](https://www.linkedin.com/in/hoelee) · [GitHub](https://github.com/hoelee) · [hoelee.com](https://hoelee.com)**
|
||
````
|
||
|
||
---
|
||
|
||
## 文章 03 / 10:用一个 Prometheus 监控 unRaid、群晖 NAS 和 VPS:我做错的四件事
|
||
- **Slug**: `one-prometheus-for-unraid-synology-and-a-vps`
|
||
- **英文标题**: One Prometheus for unRaid, a Synology NAS, and a VPS: What I Got Wrong
|
||
- **分类**: `case-studies` | **发布日期**: 2026-07-29
|
||
- **线上地址**: https://blog.hoelee.com/posts/one-prometheus-for-unraid-synology-and-a-vps/ (EN) | https://blog.hoelee.com/posts/zh/one-prometheus-for-unraid-synology-and-a-vps/ (ZH)
|
||
- **本篇审核状态**: ⏳ 待审核 (Pending)
|
||
|
||
### ✍️ 顾问审阅意见区 (Review Feedback)
|
||
```text
|
||
【审阅结论】:[ ] 通过 [ ] 需微调 [ ] 需重构
|
||
【事实与数字核对】:
|
||
【人设与用词卫生】:
|
||
【CRO与转化建议】:
|
||
```
|
||
|
||
### 🇨🇳 中文版原文 (Chinese Markdown Twin)
|
||
````markdown
|
||
---
|
||
title: "用一个 Prometheus 监控 unRaid、群晖 NAS 和 VPS:我做错的四件事"
|
||
description: "三台主机、一个 Prometheus、一个 Grafana:覆盖矩阵、把同一个 NAS 卷算成三次的\"总容量\",以及那台完全不导出 CPU 频率的虚拟机。"
|
||
pubDate: 2026-07-29
|
||
updatedDate: 2026-09-29
|
||
category: case-studies
|
||
blueprint: self-hosted-infrastructure
|
||
blueprintLayer: L3-observability-self-healing
|
||
tags: [prometheus, grafana, unraid, synology, dsm, cadvisor, monitoring, self-hosting]
|
||
ogImage: /og/zh-one-prometheus-for-unraid-synology-and-a-vps.jpg
|
||
banner: /banners/one-prometheus-for-unraid-synology-and-a-vps.jpg
|
||
draft: false
|
||
---
|
||
|
||
## 为什么这件事重要
|
||
|
||
当一套自托管基础设施在跑别人的网站、邮件和文件时,它就不是玩具了。糟糕的一周和糟糕的**一个月**之间,差别通常只是你多早发现:一块出现重分配扇区的盘、一个只剩 20 GB 的卷、一台被宿主机饿死的虚拟机、一个夜里重启四次的容器。
|
||
|
||
我有三台机器——unRaid(日常主力)、群晖 NAS(存储与服务)和 VPS(对外)——以及三套**各自**都不知道它们在干什么的方式。这篇文章讲它们如何变成一块屏,以及我路上做错的四件事——其中三个你也会踩。
|
||
|
||
## 架构
|
||
|
||
一个 Prometheus 加一个 Grafana,跑在永不关机的那台机器上。每台被监控主机跑两个 exporter:
|
||
|
||
| 机器 | 主机指标 | 容器指标 | 抓取路径 |
|
||
|---|---|---|---|
|
||
| unRaid | node_exporter (`:9100`) | cAdvisor (`:8080`) | 直连 |
|
||
| 群晖 DSM | node_exporter (`:9100`) | cAdvisor (`:8082`) | 局域网 |
|
||
| ServerHosh VPS | node_exporter (`:9100`) | cAdvisor (`:8081`) | VPN 隧道 + `nginx` stream 中转 |
|
||
|
||
**node_exporter 与 cAdvisor 不是替代关系——这是最容易搞错的一点。** node_exporter 看的是**主机**:CPU、内存、网络、磁盘、文件系统、温度;它对 cgroup 一无所知,说不出是哪个容器吃掉了内存。cAdvisor 只看**容器**。想要主机健康和按容器记账,两个都得跑;少一个,那个洞会在几个月后表现为一次无法解释的负载高峰。
|
||
|
||
## 错误一:cAdvisor 里那些\"不是容器的容器\"
|
||
|
||
我的容器规则开始对不是容器的东西告警。cAdvisor 会为 **systemd slice** 和整机 cgroup 导出序列——其中一条没有名字的序列报告了约 58 GB 的\"内存使用\",却没有对应的容器。那就是整台主机,被描述成了一个容器。
|
||
|
||
修法是加一个过滤条件,但你得先知道要写它:
|
||
|
||
```promql
|
||
# container metrics: anything with a name, and only that
|
||
container_memory_working_set_bytes{job=~"cadvisor.*", name!=""}
|
||
```
|
||
|
||
少了 `name!=""`,一条\"容器内存超过 10 GB\"的规则会对主机自己告警。
|
||
|
||
## 错误二:我的\"总容量\"是虚构的
|
||
|
||
聚合面板好看,但就是错的。原因:**同一个文件系统会在指标里出现多次。**
|
||
|
||
- 在 NAS 上,主卷是 `/volume1`,而 `/opt` 是**同一个** btrfs 文件系统,只是换了个挂载点。
|
||
- 在 unRaid 上,同一个 NAS 卷又以 CIFS 挂载成 `/mnt/remotes/<nas>_ActiveBackup`。
|
||
- unRaid 的 `/var/lib/docker` 是那个池的子卷,而 `/mnt/ssd` 已经代表过同一个池——同样的字节,第二个身份。
|
||
|
||
所以朴素的 `sum(node_filesystem_size_bytes)` 报出了我并不存在的容量。诚实的写法是明确列出什么算数据存储:
|
||
|
||
```promql
|
||
node_filesystem_size_bytes{
|
||
mountpoint=~"/volume[0-9]+|/mnt/ssd|/mnt/disk[0-9]+",
|
||
fstype!~"fuse.*|tmpfs|rootfs"
|
||
} or node_filesystem_size_bytes{job="vps-host", mountpoint="/"}
|
||
```
|
||
|
||
还有两条应该写进面板说明的诚实备注,因为没人能解释的数字比没有数字更糟:
|
||
|
||
- **校验盘对内核不可见。** unRaid 的奇偶校验盘没有文件系统,所以从不出现在指标里——这个和是可用容量,不是硬盘数量。
|
||
- **镜像会虚增裸和。** 两块镜像 SSD 会各报一次自己的字节,和不是你能存的量。
|
||
|
||
还有那个以后一定会咬我的遗漏:unRaid 的 shfs 联合挂载(`/mnt/user`)报告 `avail=0`。把它算进\"剩余空间低于 X\"的规则里,就会产生一条永远无法解除的告警。
|
||
|
||
## 错误三:那台不导出 CPU 频率的虚拟机
|
||
|
||
为了算全家的\"总 CPU 频率\",我直接用 node_exporter 的 cpufreq collector。unRaid 和 NAS 都按核心报出了 `node_cpu_scaling_frequency_hertz`;VPS **什么都没有**——它是 KVM 客户机,而客户机没有 `/sys/devices/system/cpu/cpu0/cpufreq`。这个指标在那里无法存在。
|
||
|
||
修法是 textfile collector:一个小脚本读客户机**能**看到的东西(`/proc/cpuinfo`),把 Prometheus 格式指标写进 node_exporter 会抓取的目录:
|
||
|
||
```sh
|
||
# /opt/node-exporter-textfile/cpu-mhz.sh — cron 每 5 分钟
|
||
awk -F: '
|
||
/^processor/ { c = $2; gsub(/[ \t]/, "", c) }
|
||
/^cpu MHz/ { f = $2; gsub(/[ \t]/, "", f); printf "node_cpu_mhz_current_hz{core=\"%s\"} %.0f\n", c, f * 1000000 }
|
||
' /proc/cpuinfo
|
||
```
|
||
|
||
配合:
|
||
|
||
```yaml
|
||
command:
|
||
- '--collector.textfile.directory=/textfile'
|
||
volumes:
|
||
- /opt/node-exporter-textfile:/textfile:ro
|
||
```
|
||
|
||
两个刻意的决定:指标名**故意不同**于 node_exporter 自己的(用 `node_cpu_mhz_current_hz`,不用 `node_cpu_scaling_frequency_hertz`),这样万一以后宿主机暴露真实 cpufreq,不会出现重复序列冲突;仪表盘则显式合并两个来源:
|
||
|
||
```promql
|
||
sum(node_cpu_scaling_frequency_hertz or node_cpu_mhz_current_hz)
|
||
```
|
||
|
||
## 错误四:exporter 把容器名当成了主机名
|
||
|
||
仪表盘的主机下拉框里出现了 `9f9afcccc962`。那是个容器 ID:node_exporter 的 `uname` collector 读到的是**进程自己的** UTS namespace,而容器的 hostname 默认就是它自己的 ID。指标没错,标签毫无意义。compose 里一行解决:
|
||
|
||
```yaml
|
||
services:
|
||
node_exporter:
|
||
hostname: 2.hoelee.com # otherwise `nodename` = the container ID
|
||
```
|
||
|
||
## 我下次会怎么做
|
||
|
||
- **刻意把总览屏留到最后做。** \"总容量是多少\"这个问题会逼出全部去重工作;先做完三台主机面板再发现,就得在每个地方重做这个数字。
|
||
- **一开始就给容器钉 hostname。** 一行成本,省掉一个让人困惑的下拉框。
|
||
- **假设每个虚拟化或家电式主机都会藏掉一类指标。** NAS 可能限制你的容器监控(DSM 的 Docker API 版本把我的 cAdvisor 钉在 v0.53.0——更新的版本要更新的 Docker API);虚拟机藏掉 cpufreq;路由器藏掉自己的 CPU。找缺口的方法是**数你期待的东西**,而不是相信\"采集器成功了\"。
|
||
|
||
## 结果
|
||
|
||
三台主机、**7 个抓取目标、一个 Grafana、16 条告警规则**,以及一块屏:**47 个 CPU 核心 · 当前 158 GHz(标称上限 205 GHz)· 142 GB 内存 · 64 TB 存储 · 155 个运行中容器**,并且每台机器克隆同一套主机/容器面板布局,三台读起来完全一致。告警进 Telegram 和邮件,Prometheus 保留 30 天。
|
||
|
||
最有用的产出不是仪表盘,而是重写存储规则那天触发的一条告警:一个只剩 21 GB 的 NAS 卷——它一直藏在\"99% 满\"的百分比阈值背后,而那个巨物早已变成背景噪声。
|
||
|
||
## 需要为你的业务做这个吗?
|
||
|
||
如果你有 NAS、VPS 和几台服务器,却没有一个地方能同时看它们,我可以帮你搭这样的自托管监控流水线——Prometheus + Grafana 覆盖你的机器,主机**与**容器指标,真正有意义的磁盘健康与容量规则,通知推到 Telegram 或邮件。
|
||
|
||
**WhatsApp:[+60 12-797 2969](https://wa.me/60127972969)** · **邮箱:[[email protected]](mailto:[email protected]?subject=Self-hosted%20monitoring%20setup)** · **[hoelee.com](https://hoelee.com)**
|
||
|
||
网站设计与开发是我的主业;服务器加固与自托管基础设施是它的另一半。
|
||
````
|
||
|
||
### 🇬🇧 英文版原文 (English Markdown Primary)
|
||
````markdown
|
||
---
|
||
title: "One Prometheus for unRaid, a Synology NAS, and a VPS: What I Got Wrong"
|
||
description: "Three hosts, one Prometheus, one Grafana. The coverage matrix, the storage total that counted one NAS volume three times, and the VM that exports no CPU frequency at all."
|
||
pubDate: 2026-07-29
|
||
updatedDate: 2026-09-29
|
||
category: case-studies
|
||
blueprint: self-hosted-infrastructure
|
||
blueprintLayer: L3-observability-self-healing
|
||
tags: [prometheus, grafana, unraid, synology, dsm, cadvisor, monitoring, self-hosting]
|
||
ogImage: /og/one-prometheus-for-unraid-synology-and-a-vps.jpg
|
||
banner: /banners/one-prometheus-for-unraid-synology-and-a-vps.jpg
|
||
draft: false
|
||
---
|
||
|
||
## Why this matters
|
||
|
||
Self-hosted infrastructure is not a toy when it's running other people's websites, mail and files. The
|
||
difference between a bad week and a bad *month* is usually how early you found out: a
|
||
disk with a reallocated sector, a volume with 20 GB left, a VM being starved of CPU by
|
||
its host, a container that restarted four times overnight while you slept.
|
||
|
||
I had three machines — unRaid (the daily driver), a Synology NAS (the storage and
|
||
services box) and a VPS (the public-facing one) — and three separate ways of *not*
|
||
knowing what they were doing. This is how they became one screen, and the four things I
|
||
got wrong on the way, because three of them are traps you will hit too.
|
||
|
||
## The architecture
|
||
|
||
One Prometheus and one Grafana, running on the host that never sleeps. Every monitored
|
||
host runs two exporters:
|
||
|
||
| Machine | Host metrics | Container metrics | Scrape path |
|
||
|---|---|---|---|
|
||
| unRaid | node_exporter (`:9100`) | cAdvisor (`:8080`) | direct |
|
||
| Synology DSM | node_exporter (`:9100`) | cAdvisor (`:8082`) | LAN |
|
||
| ServerHosh VPS | node_exporter (`:9100`) | cAdvisor (`:8081`) | VPN tunnel + `nginx` stream relay |
|
||
|
||
**node_exporter and cAdvisor are not substitutes — this is the first thing people get
|
||
wrong.** node_exporter sees the *host*: CPU, memory, network, disks, filesystems,
|
||
temperatures. It is cgroup-blind: it cannot tell you which container is eating your RAM.
|
||
cAdvisor sees *containers only*. If you want both host health and per-container
|
||
accounting, you run both. Dropping either one leaves a hole that shows up months later
|
||
as an unexplained load spike.
|
||
|
||
## Wrong #1: cAdvisor's "containers" that aren't containers
|
||
|
||
My container rules started firing on things that were not containers. cAdvisor exports
|
||
cgroup series for **systemd slices** and for the machine-wide cgroup — including one
|
||
unnamed series that reported roughly 58 GB of "memory usage" with no container attached
|
||
to it. That is the whole host, described as a container.
|
||
|
||
The fix is one filter, but you have to know to write it:
|
||
|
||
```promql
|
||
# container metrics: anything with a name, and only that
|
||
container_memory_working_set_bytes{job=~"cadvisor.*", name!=""}
|
||
```
|
||
|
||
Without `name!=""`, a "container using more than 10 GB" rule alerts on the host itself.
|
||
|
||
## Wrong #2: my "total storage" number was fiction
|
||
|
||
The aggregate panel looked great and was simply wrong. The reason: **one filesystem
|
||
appears in the metrics more than once.**
|
||
|
||
- On the NAS, the primary volume is `/volume1` — and `/opt` is the *same* btrfs
|
||
filesystem, exposed under a second mount point.
|
||
- On unRaid, that same NAS volume is mounted again over CIFS as
|
||
`/mnt/remotes/<nas>_ActiveBackup`.
|
||
- unRaid's `/var/lib/docker` is a subvolume of the pool that `/mnt/ssd` already
|
||
represents — same bytes, second identity.
|
||
|
||
A naive `sum(node_filesystem_size_bytes)` therefore reported capacity for disks I don't
|
||
have. The honest selector names exactly what counts as data storage:
|
||
|
||
```promql
|
||
node_filesystem_size_bytes{
|
||
mountpoint=~"/volume[0-9]+|/mnt/ssd|/mnt/disk[0-9]+",
|
||
fstype!~"fuse.*|tmpfs|rootfs"
|
||
} or node_filesystem_size_bytes{job="vps-host", mountpoint="/"}
|
||
```
|
||
|
||
Two more honesty notes that belong *in the panel description*, because a number nobody
|
||
can interpret is worse than no number:
|
||
|
||
- **Parity disks are invisible to the kernel.** unRaid's parity drive has no filesystem,
|
||
so it never appears — the sum is usable capacity, not raw spindle count.
|
||
- **A mirror inflates a raw sum.** Two mirrored SSDs report their bytes twice; the sum
|
||
is not what you can store.
|
||
|
||
And the omission that would have bitten me later: unRaid's shfs union mount (`/mnt/user`)
|
||
reports `avail=0`. Including it in a "free space below X" rule produces an alert that
|
||
can never be resolved.
|
||
|
||
## Wrong #3: the VM that exports no CPU frequency
|
||
|
||
Wanting "total CPU frequency" across the lab, I reached for node_exporter's cpufreq
|
||
collector. unRaid and the NAS reported `node_cpu_scaling_frequency_hertz` per core. The
|
||
VPS reported **nothing at all** — it's a KVM guest, and a guest has no
|
||
`/sys/devices/system/cpu/cpu0/cpufreq`. The metric cannot exist there.
|
||
|
||
The fix is the textfile collector: a small script that reads what the guest *can* see
|
||
(`/proc/cpuinfo`) and writes Prometheus-format metrics into a directory node_exporter
|
||
scrapes:
|
||
|
||
```sh
|
||
# /opt/node-exporter-textfile/cpu-mhz.sh — run from cron every 5 minutes
|
||
awk -F: '
|
||
/^processor/ { c = $2; gsub(/[ \t]/, "", c) }
|
||
/^cpu MHz/ { f = $2; gsub(/[ \t]/, "", f); printf "node_cpu_mhz_current_hz{core=\"%s\"} %.0f\n", c, f * 1000000 }
|
||
' /proc/cpuinfo
|
||
```
|
||
|
||
with
|
||
|
||
```yaml
|
||
command:
|
||
- '--collector.textfile.directory=/textfile'
|
||
volumes:
|
||
- /opt/node-exporter-textfile:/textfile:ro
|
||
```
|
||
|
||
Two deliberate decisions: the metric is published under a **different name** than
|
||
node_exporter's own (`node_cpu_mhz_current_hz`, not `node_cpu_scaling_frequency_hertz`)
|
||
so that if the host ever exposes real cpufreq there is no duplicate-series conflict, and
|
||
the dashboards merge the two sources explicitly:
|
||
|
||
```promql
|
||
sum(node_cpu_scaling_frequency_hertz or node_cpu_mhz_current_hz)
|
||
```
|
||
|
||
## Wrong #4: my exporter was reporting the container's name as the host's
|
||
|
||
The host dropdown in the dashboard offered `9f9afcccc962` as a machine. That's a container
|
||
ID: node_exporter's `uname` collector reports the *process's* UTS namespace, and a
|
||
container's hostname defaults to its own ID. The metric was correct, the label was
|
||
meaningless. One line in compose fixes it:
|
||
|
||
```yaml
|
||
services:
|
||
node_exporter:
|
||
hostname: 2.hoelee.com # otherwise `nodename` = the container ID
|
||
```
|
||
|
||
## What I'd do differently
|
||
|
||
- **Build the aggregate/overview screen last, deliberately.** Deciding "what is total
|
||
storage?" is what forces the deduplication work — discovering it after building three
|
||
host dashboards means rebuilding the number everywhere.
|
||
- **Pin container `hostname` from the start.** It costs one line and saves a confusing
|
||
dropdown.
|
||
- **Assume every virtualised or appliance host hides one class of metric.** A NAS may
|
||
cap your container monitor (DSM's Docker API version pinned my cAdvisor to v0.53.0 —
|
||
newer releases need a newer Docker API); a VM hides cpufreq; a router hides its own
|
||
CPU. Find the gap by *counting what you expected* rather than trusting that the
|
||
collector succeeded.
|
||
|
||
## The result
|
||
|
||
Three hosts, **7 scrape targets, one Grafana, 16 alert rules**, and a single screen that
|
||
reads: **47 CPU cores · 158 GHz currently clocked (205 GHz nominal) · 142 GB RAM · 64 TB
|
||
storage · 155 running containers**, with the same host and container dashboard layout
|
||
cloned per machine so the three read identically. Alerts land in Telegram and email;
|
||
Prometheus keeps 30 days.
|
||
|
||
The most useful outcome wasn't the dashboard. It was the alert that fired the day the
|
||
storage rule was rewritten: a NAS volume with 21 GB left, which had been hidden behind a
|
||
percentage threshold on a volume so large that "99% full" had become background noise.
|
||
|
||
## Want this for your business?
|
||
|
||
If you run a NAS, a VPS and a couple of servers and have no single place to see them, I
|
||
set up self-hosted monitoring pipelines like this one — Prometheus + Grafana across your
|
||
machines, host *and* container metrics, disk-health and capacity rules that mean
|
||
something, and alerts pushed to Telegram or email.
|
||
|
||
**WhatsApp: [+60 12-797 2969](https://wa.me/60127972969)** · **Email: [[email protected]](mailto:[email protected]?subject=Self-hosted%20monitoring%20setup)** · **[hoelee.com](https://hoelee.com)**
|
||
|
||
Website design and development is my main line of work; server hardening and
|
||
self-hosted infrastructure is the other half of it.
|
||
````
|
||
|
||
---
|
||
|
||
## 文章 04 / 10:一个人跑生产基础设施:三台主机、162 个容器
|
||
- **Slug**: `running-production-infrastructure-solo`
|
||
- **英文标题**: Running Production Infrastructure Solo: 162 Containers Across Three Hosts
|
||
- **分类**: `case-studies` | **发布日期**: 2026-10-06
|
||
- **线上地址**: https://blog.hoelee.com/posts/running-production-infrastructure-solo/ (EN) | https://blog.hoelee.com/posts/zh/running-production-infrastructure-solo/ (ZH)
|
||
- **本篇审核状态**: ⏳ 待审核 (Pending)
|
||
|
||
### ✍️ 顾问审阅意见区 (Review Feedback)
|
||
```text
|
||
【审阅结论】:[ ] 通过 [ ] 需微调 [ ] 需重构
|
||
【事实与数字核对】:
|
||
【人设与用词卫生】:
|
||
【CRO与转化建议】:
|
||
```
|
||
|
||
### 🇨🇳 中文版原文 (Chinese Markdown Twin)
|
||
````markdown
|
||
---
|
||
title: "一个人跑生产基础设施:三台主机、162 个容器"
|
||
description: "一个人、三台主机、78 个 compose stack 里的 162 个容器——Traefik、SSO、监控、邮件、CI/CD 与备份,以及两次改变了我「怎么核对数字」的故障。"
|
||
pubDate: 2026-10-06
|
||
category: case-studies
|
||
blueprint: self-hosted-infrastructure
|
||
blueprintLayer: L1-compute-storage-network
|
||
tags: [docker, traefik, monitoring, infrastructure, devops]
|
||
ogImage: /og/zh-running-production-infrastructure-solo.jpg
|
||
banner: /banners/running-production-infrastructure-solo.jpg
|
||
draft: false
|
||
---
|
||
|
||
## 为什么这件事重要
|
||
|
||
卖软件的公司其实同时需要两样东西:一个能干活的应用,以及底下那套让它随时可达、有备份、够安全的机器。大多数情况是这两件事被拆开——开发的人看不见服务器,托管公司又读不懂代码。
|
||
|
||
我两件都做。也就是说,写这个应用的人,也是在 TLS 自动续期挂掉时被叫醒的人,而且能直接修应用,而不是把问题推给平台。
|
||
|
||
这是我自己的生产环境:三台自管的 Docker 主机,162 个容器分布在 78 个 compose stack 上,跑着真正对外的服务——客户网站、邮件平台、CI/CD、工作流自动化、访问统计,以及这个博客。没有云平台把它粘在一起,也没有团队在运维。下面是这套架构,以及两次改变了我「怎么检查自己的工作」的故障。
|
||
|
||
## 它的样子
|
||
|
||
| 主机 | 承担什么 | 容器 | Compose stack |
|
||
|---|---|---|---|
|
||
| Synology DSM | 存储、SSO、大部分内部服务 | 86 | 44 |
|
||
| unRaid | CI runner、媒体流水线、监控 | 37 | 21 |
|
||
| Ubuntu 24.04 VPS | 公网入口、邮件平台、客户站点 | 39 | 13 |
|
||
|
||
这个划分是刻意的,不是历史遗留。VPS 承担的是「家里网断了也必须可达、必须快」的东西,因为公网流量和客户邮件都落在那里。Synology 承担需要磁盘和稳定文件系统的部分,以及所有其他服务都信任的身份源。unRaid 跑 CI runner 和那些又重又突发的批处理任务——否则它们会和服务抢内存。
|
||
|
||
## 让三台主机像一套系统的东西
|
||
|
||
**统一的入口模式。** 每台主机都跑一个 Traefik 反向代理,配自动化的 ACME 证书,所以证书自己续期,也没有哪个服务需要自己保管证书文件。后面是一套统一的路由和跳转约定,公网域名前面再套 Cloudflare。
|
||
|
||
**统一的身份源。** authentik 用 OIDC 和 proxy provider 做 SSO,所以新增一个内部服务是「在一个地方加一个应用」,而不是「在表格里再加一个密码」。对外的服务保持匿名可访问;其余的都从这里认证。
|
||
|
||
**统一的监控。** Prometheus、Grafana、cAdvisor 和 node-exporter 铺在三台主机上,收进同一个 Grafana 而不是三块面板——因为真正有意思的故障,都是跨主机的那种。
|
||
|
||
**统一的交付路径。** 自建的 Gitea Actions runner 负责构建和部署。这个博客就是走这条流水线:提交、runner 接单、容器重建、Cloudflare 把新构建送出去。
|
||
|
||
**经过验证、而不是假设的备份。** NAS 上的快照备份,加上 Duplicati 和 restic 任务,并把恢复步骤写下来——因为没验证过的备份只是一种感觉,不是备份。
|
||
|
||
## 失败一:仪表盘在骗我
|
||
|
||
搭监控的时候我选择相信 Grafana 显示的东西,结果有三块面板是错的。
|
||
|
||
cAdvisor 报出来的「容器」其实是 cgroup 的伪条目,把容器数量虚报了。我的「总容量」面板把一个 NAS 卷算了三遍,因为三个看起来差不多的挂载点被当成独立文件系统抓取了——这个数字看起来完全合理,而「看起来合理」正是它危险的地方。还有一台虚拟机根本不导出 CPU 频率,于是那块面板一直是空的,而我把它读成「暂时没数据」,而不是「这个 exporter 配错了」。
|
||
|
||
这三件事都没有弄坏任何服务。但三件事都会让我向客户报出一个假数字,因为仪表盘上的错数字和真数字长得一模一样。整个过程我写在 [One Prometheus for unRaid, a Synology NAS, and a VPS](https://blog.hoelee.com/posts/one-prometheus-for-unraid-synology-and-a-vps/) 里了。
|
||
|
||
## 失败二:少了一个配置文件,三种故障模式
|
||
|
||
我的团队密码管理器 Passbolt 开始返回 504,它的定时任务看起来卡住了。最后发现是三种不同的故障模式、同一个根因:一个只存在于运行中的容器里、从来没进 compose 文件的配置值。
|
||
|
||
空的 GPG fingerprint 让邮件发不出去,而发邮件这一步被放在定时任务里,于是整个任务挂住,UI 跟着一起挂。修好之后确实好了——直到容器被重建,配置被抹掉,原来的症状又回来了,看起来像问题自己复发。接着我为了追这两个问题引入的 `ssl.force`,在反向代理后面造成了跳转循环。
|
||
|
||
三个症状、三个晚上、一个教训:没有进版本控制的配置,就不算配置。完整的过程写在 [Passbolt UI Kept Hanging — Three Failure Modes From One Missing Config File](https://blog.hoelee.com/posts/passbolt-hang-three-failure-modes/)。
|
||
|
||
## 我怎么让数字保持诚实
|
||
|
||
简历上的数字会悄悄过期。我的数字是可以重新算出来的:一个小脚本通过 Portainer API 读活的 Docker 端点,逐台主机统计容器和 compose stack 的数量,所以「162 个容器、78 个 compose stack」是按需重新测量,而不是记住它曾经为真的那一天。同一个脚本还会打印出一份「绝不能出现在任何对客户材料里」的服务清单。
|
||
|
||
背后的规则很简单:一个无法被重新核对的数字,就是一个没人能在面试里、在报价里、在客户问「你怎么算出来的」那一通电话里守住的说法。凡是不能重新测量的数字,就不写进文档。
|
||
|
||
## 我会做得不一样的地方
|
||
|
||
**第一天就把每一个配置值放进 compose 文件**,包括那些感觉「属于机器而不是属于服务」的。Passbolt 那次复发,只因为一个修复活在容器里。
|
||
|
||
**对「没有数据」告警,而不是只对「坏数据」告警。** 一块空白的面板和一台健康服务,在仪表盘上长得一样。如果某个 exporter 十分钟没送来任何东西,那就是该告警的事件。
|
||
|
||
**用专门用来衡量可用性的东西去衡量可用性。** 指标流水线告诉你系统现在表现如何,它并不统计「成功请求 ÷ 总请求」。如果一个百分比要出现在客户面前,它需要一个按计划探测端点并记录结果的探针;否则诚实的回答是「有监控」,而不是一个数字。这个区别比数字本身更重要。
|
||
|
||
## 结果
|
||
|
||
三台主机、162 个容器、78 个 compose stack、一个人——加上自动化证书、统一 SSO、跨主机监控、经过验证的备份和自建 CI/CD。它同时跑过客户网站、一个邮件平台、一个 Telegram 客服 bot、排程自动化和这个博客;也正是它让我能把项目从「这是需求」做到「已经上线、有监控、有备份」,而不用把后半段交给别人。
|
||
|
||
## 想给你的生意也做一套?
|
||
|
||
如果你需要一个既能写应用、又能跑它脚下那套基础设施的人——Docker 和 Traefik、自动化 TLS、SSO、监控、邮件、备份、CI/CD——我做的就是这个,而且我更想聊你的环境,而不是发一份宣传单。
|
||
|
||
**WhatsApp:[+60 12-797 2969](https://wa.me/60127972969)** · **Email:[[email protected]](mailto:[email protected]?subject=Infrastructure%20setup%20enquiry)** · **[hoelee.com](https://hoelee.com)**
|
||
|
||
网站设计开发是我的主业;自托管基础设施、监控与自动化是它的另一半。
|
||
````
|
||
|
||
### 🇬🇧 英文版原文 (English Markdown Primary)
|
||
````markdown
|
||
---
|
||
title: "Running Production Infrastructure Solo: 162 Containers Across Three Hosts"
|
||
description: "One operator, three hosts, 162 containers in 78 compose stacks — Traefik, SSO, monitoring, mail, CI/CD and backups — and the two failures that changed how I verify my own numbers."
|
||
pubDate: 2026-10-06
|
||
category: case-studies
|
||
blueprint: self-hosted-infrastructure
|
||
blueprintLayer: L1-compute-storage-network
|
||
tags: [docker, traefik, monitoring, infrastructure, devops]
|
||
ogImage: /og/running-production-infrastructure-solo.jpg
|
||
banner: /banners/running-production-infrastructure-solo.jpg
|
||
draft: false
|
||
---
|
||
|
||
## Why this matters
|
||
|
||
A business that sells software needs two things at once: an application that
|
||
does the job, and the machinery underneath that keeps it reachable, backed
|
||
up and secure. Agencies usually split those two between a developer and a
|
||
hosting company, which is how you end up with a developer who cannot see the
|
||
server and a hosting company that cannot read the code.
|
||
|
||
I run both. That means the person who wrote the application is also the
|
||
person who gets woken up when TLS renewal stops working, and who can fix the
|
||
application rather than blame the platform.
|
||
|
||
This is my own production footprint: three self-managed Docker hosts running
|
||
162 containers across 78 compose stacks, serving live public services —
|
||
client websites, a mail platform, CI/CD, workflow automation, analytics and
|
||
this blog. No cloud platform holds it together, and no team operates it.
|
||
Here is the architecture, and the two failures that changed how I check my
|
||
own work.
|
||
|
||
## The shape of it
|
||
|
||
| Host | What it carries | Containers | Compose stacks |
|
||
|---|---|---|---|
|
||
| Synology DSM | storage, SSO, the bulk of internal services | 86 | 44 |
|
||
| unRaid | CI runner, media pipeline, monitoring | 37 | 21 |
|
||
| Ubuntu 24.04 VPS | public entry point, mail platform, client sites | 39 | 13 |
|
||
|
||
The split is deliberate rather than historical. The VPS carries what must
|
||
stay reachable and fast when the home connection is not, because that is
|
||
where public traffic and client mail land. The Synology carries what needs
|
||
disk and a stable filesystem, plus the identity provider that every other
|
||
service trusts. unRaid runs the CI runner and the heavy, spiky batch work
|
||
that would otherwise compete with the services for RAM.
|
||
|
||
## What makes three hosts one system
|
||
|
||
**One ingress pattern.** Each host runs a Traefik reverse proxy with automated ACME TLS, so certificates renew themselves and no service owns a certificate file. Behind it there is one convention for routing and redirects, and Cloudflare sits in front of the public names.
|
||
|
||
**One identity provider.** authentik handles SSO with OIDC and proxy providers, so a new internal service is a new application in one place instead of a new password in a spreadsheet. Public services stay anonymous; everything else authenticates through it.
|
||
|
||
**One monitoring stack.** Prometheus, Grafana, cAdvisor and node-exporter across the hosts, in a single Grafana rather than three dashboards, because the interesting failures are the ones that cross host boundaries.
|
||
|
||
**One delivery path.** Self-hosted Gitea Action runners build and deploy. This blog ships through that pipeline — commit, runner picks it up, container rebuilds, Cloudflare serves the new build.
|
||
|
||
**Backups that are tested rather than assumed.** Snapshot-based backup on the NAS plus Duplicati and restic jobs, with restore procedures written down, because an untested backup is a feeling, not a backup.
|
||
|
||
## Failure 1: the dashboard was lying to me
|
||
|
||
When I built the monitoring stack I trusted what Grafana showed me, and
|
||
three of the panels were wrong.
|
||
|
||
cAdvisor reported "containers" that were really cgroup pseudo-entries, which
|
||
inflated the container count. My total-storage panel counted one NAS volume
|
||
three times, because three near-identical mount points were being scraped as
|
||
separate filesystems — the number looked plausible, which is exactly what
|
||
made it dangerous. And one virtual machine exported no CPU frequency at all,
|
||
so its panel stayed empty and I read that as "no data yet" instead of "this
|
||
exporter is misconfigured".
|
||
|
||
None of those broke a service. All three would have made me report something
|
||
false to a client, because a wrong number on a dashboard is
|
||
indistinguishable from a right one. I wrote the whole thing up in
|
||
[One Prometheus for unRaid, a Synology NAS, and a VPS](https://blog.hoelee.com/posts/one-prometheus-for-unraid-synology-and-a-vps/).
|
||
|
||
## Failure 2: one missing config file, three failure modes
|
||
|
||
Passbolt, my team password manager, started returning 504s and its cron job
|
||
appeared to hang. It turned out to be three separate failure modes with one
|
||
root cause: a configuration value that existed inside the running container
|
||
but never in the compose file.
|
||
|
||
A null GPG fingerprint stalled mail delivery, and because the mail send sat
|
||
inside the scheduled job, the whole job hung and took the UI with it. The
|
||
fix worked — until the container was recreated, which wiped it and restored
|
||
the original symptom, so the problem appeared to come back on its own. Then
|
||
`ssl.force` behind a reverse proxy produced a redirect loop that I had
|
||
introduced myself while chasing the other two.
|
||
|
||
Three symptoms, three sessions, one lesson: configuration that is not in
|
||
version control is not configuration. The full sequence is in
|
||
[Passbolt UI Kept Hanging — Three Failure Modes From One Missing Config File](https://blog.hoelee.com/posts/passbolt-hang-three-failure-modes/).
|
||
|
||
## How I keep the numbers honest
|
||
|
||
Numbers on a CV go stale quietly. Mine are re-derivable: a small script
|
||
reads the live Docker endpoints through the Portainer API and counts
|
||
containers and compose stacks per host, so "162 containers across 78+
|
||
compose stacks" is re-measured on demand rather than remembered from the day
|
||
it was true. The same script prints the list of services that must never
|
||
appear in anything client-facing.
|
||
|
||
The rule behind it is simple. A number that cannot be re-checked becomes a
|
||
claim nobody can defend — in an interview, in a proposal, or on a call when
|
||
a client asks how you got it. If I cannot re-measure a figure, it does not
|
||
go in the document.
|
||
|
||
## What I would do differently
|
||
|
||
**Every configuration value in the compose file from day one**, including the ones that feel like secrets of the machine rather than of the service. The Passbolt relapse existed only because a fix lived in a container.
|
||
|
||
**Alert on the absence of data, not just on bad data.** A blank panel and a healthy service look identical on a dashboard. If nothing arrives from an exporter for ten minutes, that is the alert.
|
||
|
||
**Measure availability with something built to measure availability.** A metrics pipeline tells you how a system is behaving; it does not count successful requests against total requests. If a percentage is going to appear in front of a client, it needs a probe checking endpoints on a schedule and recording the result — otherwise the honest answer is "monitored", not a number. That distinction matters more than the number.
|
||
|
||
## The result
|
||
|
||
Three hosts, 162 containers, 78 compose stacks, one operator — with
|
||
automated TLS, central SSO, cross-host monitoring, tested backups and
|
||
self-hosted CI/CD. It has run client websites, a mail platform, a Telegram
|
||
support bot, scheduling automation and this blog at the same time, and it is
|
||
the reason I can take a project from "here is the requirement" to "it is
|
||
live, monitored and backed up" without handing the second half to somebody
|
||
else.
|
||
|
||
## Want this for your business?
|
||
|
||
If you need someone who can build the application **and** run the
|
||
infrastructure it lives on — Docker and Traefik, automated TLS, SSO,
|
||
monitoring, mail, backups, CI/CD — I do exactly this, and I would rather
|
||
talk about your setup than send a brochure.
|
||
|
||
- WhatsApp: [wa.me/60127972969](https://wa.me/60127972969)
|
||
- Email: [[email protected]](mailto:[email protected]?subject=Infrastructure%20setup%20enquiry)
|
||
- More: [hoelee.com](https://hoelee.com)
|
||
````
|
||
|
||
---
|
||
|
||
## 文章 05 / 10:数字商品的自愈式访问控制:NocoDB、n8n 与 AList
|
||
- **Slug**: `self-healing-digital-goods-entitlements`
|
||
- **英文标题**: Self-Healing Access Control for Digital Goods: NocoDB, n8n, and AList
|
||
- **分类**: `case-studies` | **发布日期**: 2026-09-18
|
||
- **线上地址**: https://blog.hoelee.com/posts/self-healing-digital-goods-entitlements/ (EN) | https://blog.hoelee.com/posts/zh/self-healing-digital-goods-entitlements/ (ZH)
|
||
- **本篇审核状态**: ⏳ 待审核 (Pending)
|
||
|
||
### ✍️ 顾问审阅意见区 (Review Feedback)
|
||
```text
|
||
【审阅结论】:[ ] 通过 [ ] 需微调 [ ] 需重构
|
||
【事实与数字核对】:
|
||
【人设与用词卫生】:
|
||
【CRO与转化建议】:
|
||
```
|
||
|
||
### 🇨🇳 中文版原文 (Chinese Markdown Twin)
|
||
````markdown
|
||
---
|
||
title: "数字商品的自愈式访问控制:NocoDB、n8n 与 AList"
|
||
description: "我如何用五个工作流搭出一套权限系统,自动授予、到期失效并持续修复客户的文件访问——包括一个构建期代码共享技巧,以及一个设计上刻意不泄露任何信息的公开接口。"
|
||
pubDate: 2026-09-18
|
||
category: case-studies
|
||
blueprint: sme-digital-suite
|
||
blueprintLayer: L3-entitlement-backoffice
|
||
tags: [n8n, nocodb, alist, access-control, docker, automation, digital-goods]
|
||
ogImage: /og/zh-self-healing-digital-goods-entitlements.jpg
|
||
banner: /banners/self-healing-digital-goods-entitlements.jpg
|
||
---
|
||
|
||
我卖数字产品——文件、美术素材、授权资源——并通过一个自建的文件门户交付。真正的难题从来不是存储,而是**授权**:确保客户在购买时拿到恰好他们买下的目录,拿到恰好他们付费的时长,并且在停止付费时访问权限真的被收回。
|
||
|
||
手工做这件事,前十个客户没问题。一百个就不行了,而且失败的方�式很具体、也很讨厌:静默失败。订阅到期而客户继续下载时,不会有任何报错。你只是一直在给一个几个月前就停止付费的人供文件。
|
||
|
||
所以我把它做成五个 n8n 工作流,把访问权限当作**派生状态**来处理——从我的业务数据库计算得出,应用到文件服务器上,并持续重新校验。下面是它的架构、让它可维护的代码共享技巧,以及那个公开接口背后的安全推理。
|
||
|
||
## 为什么这件事重要
|
||
|
||
对一个数字商品生意来说,访问控制*就是*产品本身。你保护的不是一座仓库,你保护的是你卖掉的那个东西。两种失败模式会真金白银地亏钱:
|
||
|
||
- **授予不足**——付费客户拿不到他买的东西,而你是从愤怒的消息里而不是监控告警里知道的。
|
||
- **授予过度**——已到期或已撤销的客户继续有访问权,而泄露会一直不可见,直到有人转卖你的目录。
|
||
|
||
手工管理最终会必然地导致这两种。解法是不要再把一次授权当成*你做的一件事*,而把它当成*你数据的一个函数*:给定客户当前的购买记录,他现在应该能访问什么?算出来、应用它,然后按计划证明它仍然成立。
|
||
|
||
## 系统的形状
|
||
|
||
五个工作流,每个只做一件事:
|
||
|
||
| 工作流 | 触发器 | 职责 |
|
||
|---|---|---|
|
||
| **W1** — Customer Provision & Status Lifecycle | NocoDB webhook(客户行) | 创建/更新文件服务器用户;状态变更时启用或禁用 |
|
||
| **W2** — CustomerProduct Sync | NocoDB webhook(购买行) | 重新计算并应用该客户被允许的路径 |
|
||
| **W3** — Expiry Sync | Cron,每 5 分钟 | 扫描即将到期的授权;移除已失效的路径 |
|
||
| **W4** — Daily Full Reconciliation | Cron 03:00 + 手动 webhook | 对比全体客户的*期望*与*实际*;修复漂移;记录日志 |
|
||
| **W5** — Footer Purchase Check | 公开 GET webhook | 让门户展示客户自己的购买记录;只读 |
|
||
|
||
数据存在 **NocoDB**(一个自建的 Airtable 类数据库)里,包括 Customers、CustomerProducts、Products、Resources 和 AccessGrants 几张表。文件服务器是 **AList**,它为每个客户提供一个用户和一个角色,角色的 `permission_scopes` 就是一串路径。
|
||
|
||
至关重要的设计决策:**NocoDB 是业务真相来源,AList 只是执行状态。** 同步是单向的。在 AList 管理后台手动改一笔不算配置变更——那叫漂移,W4 会把它修复回去。
|
||
|
||
## 算法:这个客户*应该*有什么?
|
||
|
||
一切都系于一个函数。客户的期望路径是两个来源的并集:
|
||
|
||
1. 所有可从**有效的、未过期**购买记录到达的资源。
|
||
2. 所有通过**有效的、未过期**手工授权直接授予的资源。
|
||
|
||
有意思的情况是:同一个资源可以通过*两个不同*产品到达。如果客户买了产品 A(30 天后到期)和产品 B(200 天后到期),而两者都包含同一个目录,那么正确的到期时间是**较晚**的那一个——多买一样东西永远不该缩短你对它的访问权。
|
||
|
||
```js
|
||
// 对每个产品的资源,按路径保留最大的 expires_at。
|
||
for (const c of cps) {
|
||
if (c.status && c.status !== 'active') continue;
|
||
if (c.expires_at && String(c.expires_at) <= today) continue; // 已过期
|
||
const pid = linkId(c.product);
|
||
if (!pid) continue;
|
||
const res = (await ncGet(ctx,
|
||
`/api/v2/tables/${T_PROD}/links/${LNK_PROD_RES}/records/${pid}`)).list || [];
|
||
const exp = c.expires_at;
|
||
for (const r of res) {
|
||
const p = resPath[r.Id];
|
||
if (!p) continue;
|
||
const cur = desired[p];
|
||
if (!cur || !cur.expires || (exp && exp > cur.expires)) {
|
||
desired[p] = { expires: exp || null, permission: cur?.permission ?? 0 };
|
||
}
|
||
}
|
||
}
|
||
```
|
||
|
||
注意边界:`<= today`。**当天到期就算已过期。** 到期检查上的一个差一错误,就是订阅期与白送一天之间的区别;如果你不把它写明确,你一定会写错,而且会错在对客户有利的那一边。
|
||
|
||
## 问题所在:n8n 的 Code 节点无法共享代码
|
||
|
||
这个约束塑造了整个代码库。n8n 的 Code 节点是自包含的:没有 `require`、没有 `import`、也没有访问共享模块的文件系统权限。所以最自然的结构——一个授权算法,被 W1、W2、W3、W4 调用——恰恰是这个平台不让你做的事。
|
||
|
||
把那个函数复制粘贴进四个节点,注定是一场维护灾难。四份到期规则的拷贝,就是四次它们互相不一致的机会,而一个用四种方式计算访问权限的系统,比没有系统更糟。
|
||
|
||
解法是让共享发生在**构建期**而不是运行期:
|
||
|
||
- `shared/effective-grants.js` 是唯一真相来源,而且它被写成自包含的:没有 `require`、没有 `process.exit`、函数外没有顶层 `return`。它通过一个 `ctx` 参数(`{ $env, helpers }`)接收配置,而不是去抓全局变量——这带来一个令人愉快的副作用:它**可以在 n8n 之外做单元测试**。
|
||
- `gen_w1.js`、`gen_w2.js`、`gen_w3.js`、`gen_w4.js` 读取这个文件,把它内联进工作流的 Code 节点主体,并更新工作流。
|
||
|
||
结果是:一个算法、四个工作流、零运行期依赖——而且这个函数可以在碰到任何线上系统之前,用纯 Node 测试。代码在*产物*里重复,但在*源码*里从不重复,这和打包器做的是同一笔交易。
|
||
|
||
一个 n8n 特有的细节值得知道:**自定义环境变量只有在 Code 节点里通过 `$env` 才可靠可读——`process.env` 在那里不可靠。** 这就是为什么每个工作流都有一个显式的「Load Env」节点,把它需要的值提升到 item 上,而不是哪里方便就在哪里读配置。
|
||
|
||
## 让到期处理可以安全自动化
|
||
|
||
W3 每五分钟跑一次,对即将到期的授权做对账。有两个细节让一个 cron 任务可以安全地改动线上权限:
|
||
|
||
**只有当访问权限真的用完时才禁用。** 一个天真的「如果没有期望路径就禁用用户」规则是危险的——它会乐于禁用一位只是还没被授予任何东西的新客户。守卫条件是显式的:
|
||
|
||
```js
|
||
// 只在「曾经有权限、现在一个都没有」的客户身上禁用。
|
||
// currentPaths.length > 0 避免干掉一个全新的、尚未授权的客户。
|
||
const shouldDisable = AUTO_DISABLE && nowEmpty
|
||
&& cust.status === 'active' && currentPaths.length > 0;
|
||
```
|
||
|
||
**它有 dry-run 模式。** 容器上的 `W3_DRY_RUN=true`(或 W4 手动 webhook 上的查询参数)会让扫描计算并报告它的计划,同时**执行零写入**。能在让一个计划任务动手之前先问「你会做什么?」,是我在任何自动化里加过的最有用的安全功能。
|
||
|
||
```js
|
||
const DRY_RUN = ($env.W3_DRY_RUN || '').toLowerCase() === 'true';
|
||
```
|
||
|
||
## 每日修复:假定你一定会漂移
|
||
|
||
W4 是那个我会说才是真正产品的工作流。它在 03:00 运行,遍历每个客户,对比期望状态与实际状态——然后修复差异并**验证修复**。
|
||
|
||
它处理的漂移矩阵:
|
||
|
||
- **应当是有效的** → 用户必须存在(**先用用户名查找**,以避免在存储的 ID 丢失时创建重复用户)、处于启用状态,并且恰好带有计算出的角色权限范围。
|
||
- **应当是无效的** → 禁用,并清空权限范围。待处理客户完全不建用户——不自动创建。
|
||
- **悬空引用** → 存储的用户或角色 ID 指向一个已不存在的记录。按名字查找,找到就收编,找不到就重建。
|
||
- **用户名漂移** → 只检测并*记录日志*,绝不做破坏性迁移。
|
||
|
||
每一次修复之后都会重新读取文件服务器状态来验证。失败验证会被记为 `verify_failed` 而不是假定成功,而对账日志只接收**漂移、修复和错误三类记录**——健康客户不产生任何行。最后这个选择正是让日志可用的原因:如果它是空的,一切正常,你不必读着一千行「无变化」去找那一条重要的。
|
||
|
||
## 那个公开接口,以及为什么没有 HMAC
|
||
|
||
W5 让文件门户的页脚能展示已登录客户自己的购买记录和到期日期。它是一个**公开** webhook,而它的安全推理是我最刻意对待的部分。
|
||
|
||
直觉是用 HMAC 给请求签名。我没这么做,理由值得直说:**密钥必须发到浏览器,所以签名只是表演。** 一个每个客户端都持有的共享密钥什么都保护不了——它只增加了一层仪式,让这个接口*看起来*经过验证。
|
||
|
||
所以这个接口依赖的是真正成立的东西:
|
||
|
||
- **CORS 锁定单一来源。** 响应带有
|
||
`Access-Control-Allow-Origin: https://drive.example.com`,所以只有门户自己的页面能在浏览器里读取响应。
|
||
- **数据最小化是设计出来的。** 响应只返回产品名、到期日期、展示状态和公开目录路径。没有内部数据库 ID、没有客户个人信息、没有任何其他客户的信息。
|
||
- **边缘限流**,通过请求路径上的一条 WAF 规则,削弱用户名枚举。
|
||
|
||
还有一个细微的架构选择:**用户名来自调用者自己的会话 token,在客户端解码**,而不是来自一个客户端可以自由设置的参数。这个接口从不向文件服务器认证,从而避开了一整类连接状态与设备注册副作用——否则每次页脚渲染都会引入这些副作用。
|
||
|
||
诚实的说法是:这个接口不是信任边界,我也不假装它是。它向客户展示的只是他们本来就知道的关于自己的信息,走的是一个对任何其他人无用的响应形状。
|
||
|
||
## 教会我最多的那个 bug:公网路径与级联故障
|
||
|
||
W5 最初是通过 NocoDB 的**公网**主机名——穿过一个 Cloudflare 隧道——去取数据的。测试中它工作良好。在真实负载下,它产生了这样一条链:
|
||
|
||
1. 公网往返延迟在负载下超过 60 秒。
|
||
2. nginx 上游超时触发 → **504**。
|
||
3. 页脚客户端 fetch 的 8 秒超时**每秒重试一次**。
|
||
4. 重试堆积了连接。
|
||
5. 这些连接耗尽连接池 → 无关请求收到 **503**。
|
||
|
||
一个慢依赖变成了一次不同服务的级联故障。修法是停止跨过整个互联网去访问同一个 Docker 网络上的东西:
|
||
|
||
```js
|
||
// n8n 与 NocoDB 同处 bridge_hoelee 网络;NocoDB 监听 :10380。
|
||
// 走公网路由会引入 CF 隧道抖动,且可能超过代理超时。
|
||
const NOCODB_URL = 'http://nocodb:10380';
|
||
```
|
||
|
||
**内部约 30 ms,公网 300 ms 以上,且没有隧道抖动**——整条故障链消失了,因为触发条件(数秒级延迟)已不可能出现。
|
||
|
||
这个教训可以很好地泛化到这个技术栈之外:**当一个服务和它的依赖在同一个容器网络里时,用公网主机名就是一个等着负载来触发的 bug。** 而当你看到一个 503 出现在一个 504 的下游时,去找那个激进重试的客户端——重试循环通常才是放大器,而不是原始问题。
|
||
|
||
## 我会怎么做得不一样
|
||
|
||
1. **先做漂移修复,而不是最后做。** 我先写授权路径,然后到期扫描,最后才对账。回头看,对账才是让另外两个可以安全运行的东西,它应该从第一天就存在——因为「假定你一定会漂移」是一种设计立场,不是一个功能。
|
||
2. **在任何工作流之前先写期望状态函数。** 它能待在 `shared/` 里、能在 n8n *之外*做单元测试,正是整个系统在四个工作流之间保持连贯的原因。如果我一开始就把逻辑粘贴进节点,我就会发布四份微妙的、彼此不同的到期规则。
|
||
3. **永远不要在同一台主机的两个容器之间走公网。** 这条让我真的经历了一次故障,而它现在是我默认应用的规则,而不是每个集成都要重新发现一次。
|
||
4. **从第一天就把 dry-run 开关放进去。** 事后加 `DRY_RUN` 很容易;而在没有它的情况下运行一个会改动权限的计划任务,是几周完全不必要的提心吊胆。
|
||
|
||
## 结果
|
||
|
||
五个工作流跑完整个授权生命周期:数据库里的一笔购买在几秒内变成可用访问,到期每五分钟扫一次,每夜的完整对账修复任何漂移并验证每次修复。一切健康时对账日志是空的——而大多数日子里,它说的就是这件事。
|
||
|
||
值得带走的设计原则,是让这件事变得可控的那一条:**别再「管理」访问权限,开始「断言」它。** 把客户应该拥有什么定义成业务数据的纯函数,在数据变化时应用这个函数,并按计划重新断言它以捕获其他所有情况。这样系统就不需要你小心翼翼——它只需要你在一个函数里,一次性地正确。
|
||
|
||
---
|
||
|
||
## 想让你的生意也用上这套?
|
||
|
||
如果你卖数字产品,还在手工授予文件访问权限——或者你不确定上个月到期的客户是否真的已经失去访问权——我搭的正是这套东西:自建授权系统,访问权限从你的数据计算得出、自动到期、每夜自我修复。我熟悉 NocoDB、n8n、AList 和 Docker,并且会把文档一并交付,让你不用依赖我也能运维。
|
||
|
||
欢迎联系 [[email protected]](mailto:[email protected]?subject=%E6%95%B0%E5%AD%97%E5%95%86%E5%93%81%E8%AE%BF%E9%97%AE%E6%8E%A7%E5%88%B6)
|
||
或 WhatsApp [+60 12-797 2969](https://wa.me/60127972969),也可以看看我在
|
||
[hoelee.com](https://hoelee.com) 做什么。
|
||
````
|
||
|
||
### 🇬🇧 英文版原文 (English Markdown Primary)
|
||
````markdown
|
||
---
|
||
title: "Self-Healing Access Control for Digital Goods: NocoDB, n8n, and AList"
|
||
description: "How I built a five-workflow entitlement system that grants, expires, and continuously repairs customer file access — with a build-time code-sharing trick and a public endpoint designed to leak nothing."
|
||
pubDate: 2026-09-18
|
||
category: case-studies
|
||
blueprint: sme-digital-suite
|
||
blueprintLayer: L3-entitlement-backoffice
|
||
tags: [n8n, nocodb, alist, access-control, docker, automation, digital-goods]
|
||
ogImage: /og/self-healing-digital-goods-entitlements.jpg
|
||
banner: /banners/self-healing-digital-goods-entitlements.jpg
|
||
---
|
||
|
||
I sell digital products — files, artwork, licensed assets — and deliver them
|
||
through a self-hosted file portal. The hard problem was never storage. It was
|
||
**entitlement**: making sure that when someone buys, they get exactly the
|
||
folders they paid for, for exactly as long as they paid for, and that when
|
||
they stop paying, the access actually goes away.
|
||
|
||
Doing that by hand works for the first ten customers. It does not work for a
|
||
hundred, and it fails in a specific and nasty way: silently. Nothing errors
|
||
when a subscription expires and the customer keeps downloading. You just keep
|
||
serving files to someone who stopped paying months ago.
|
||
|
||
So I built it as five n8n workflows that treat access as **derived state** —
|
||
computed from my business database, applied to the file server, and
|
||
continuously re-verified. Here's the architecture, the code-sharing trick that
|
||
makes it maintainable, and the security reasoning behind the one public
|
||
endpoint.
|
||
|
||
## Why it matters
|
||
|
||
For a digital-goods business, access control *is* the product. You're not
|
||
protecting a warehouse; you're protecting the thing you sold. Two failure modes
|
||
cost real money:
|
||
|
||
- **Under-granting** — a paying customer can't reach what they bought, and you
|
||
find out from an angry message rather than a monitoring alert.
|
||
- **Over-granting** — expired or revoked customers keep access, and the leak
|
||
is invisible until someone resells your catalog.
|
||
|
||
Manual administration guarantees both, eventually. The fix is to stop treating
|
||
a grant as a *thing you do* and start treating it as a *function of your data*:
|
||
given the customer's current purchases, what should they be able to reach right
|
||
now? Compute it, apply it, and then prove it's still true on a schedule.
|
||
|
||
## The shape of the system
|
||
|
||
Five workflows, each with one job:
|
||
|
||
| Workflow | Trigger | Responsibility |
|
||
|---|---|---|
|
||
| **W1** — Customer Provision & Status Lifecycle | NocoDB webhook (customer row) | Create/update the file-server user; enable or disable on status change |
|
||
| **W2** — CustomerProduct Sync | NocoDB webhook (purchase row) | Recompute and apply that customer's allowed paths |
|
||
| **W3** — Expiry Sync | Cron, every 5 minutes | Sweep expiring entitlements; deselect paths that lapsed |
|
||
| **W4** — Daily Full Reconciliation | Cron, 03:00 + manual webhook | Compare *desired* vs *actual* for everyone; repair drift; log |
|
||
| **W5** — Footer Purchase Check | Public GET webhook | Let the portal show a customer their own purchases; read-only |
|
||
|
||
The data lives in **NocoDB** (a self-hosted Airtable-style database) as
|
||
Customers, CustomerProducts, Products, Resources, and AccessGrants. The file
|
||
server is **AList**, which gives each customer a user and a role whose
|
||
`permission_scopes` is a list of paths.
|
||
|
||
The crucial design decision: **NocoDB is the business source of truth. AList is
|
||
only enforcement state.** Sync runs one way. A manual tweak in the AList admin
|
||
UI is not a configuration change — it's drift, and W4 repairs it back.
|
||
|
||
## The algorithm: what *should* this customer have?
|
||
|
||
Everything hinges on one function. Desired paths for a customer is the union of
|
||
two sources:
|
||
|
||
1. Every resource reachable from an **active, not-yet-expired** purchase.
|
||
2. Every resource granted directly via an **active, not-yet-expired** manual grant.
|
||
|
||
The interesting case is a resource reachable through *two* different products.
|
||
If a customer bought Product A (expires in 30 days) and Product B (expires in
|
||
200 days) and both include the same folder, the correct expiry is the **latest**
|
||
one — buying more of something should never shorten your access to it.
|
||
|
||
```js
|
||
// For each product's resources, keep the MAX expiry per path.
|
||
for (const c of cps) {
|
||
if (c.status && c.status !== 'active') continue;
|
||
if (c.expires_at && String(c.expires_at) <= today) continue; // expired
|
||
const pid = linkId(c.product);
|
||
if (!pid) continue;
|
||
const res = (await ncGet(ctx,
|
||
`/api/v2/tables/${T_PROD}/links/${LNK_PROD_RES}/records/${pid}`)).list || [];
|
||
const exp = c.expires_at;
|
||
for (const r of res) {
|
||
const p = resPath[r.Id];
|
||
if (!p) continue;
|
||
const cur = desired[p];
|
||
if (!cur || !cur.expires || (exp && exp > cur.expires)) {
|
||
desired[p] = { expires: exp || null, permission: cur?.permission ?? 0 };
|
||
}
|
||
}
|
||
}
|
||
```
|
||
|
||
Note the boundary: `<= today`. **Expiring today counts as expired.** Off-by-one
|
||
on an expiry check is the difference between a subscription period and a free
|
||
extra day, and if you're not explicit about it you'll get it wrong in the
|
||
customer's favour.
|
||
|
||
## The problem: n8n Code nodes can't share code
|
||
|
||
Here's the constraint that shaped the whole codebase. n8n Code nodes are
|
||
self-contained: there's no `require`, no `import`, no filesystem access to a
|
||
shared module. So the obvious structure — one grants algorithm, called by W1,
|
||
W2, W3, and W4 — is exactly what the platform prevents.
|
||
|
||
Copy-pasting that function into four nodes would have been a guaranteed
|
||
maintenance disaster. Four copies of an expiry rule is four chances for them to
|
||
disagree, and a system that computes access four different ways is worse than
|
||
no system.
|
||
|
||
The fix was to make the sharing happen at **build time** instead of run time:
|
||
|
||
- `shared/effective-grants.js` is the single source of truth, and it's written
|
||
to be self-contained: no `require`, no `process.exit`, no top-level `return`
|
||
outside a function. It also takes its config through a `ctx` argument
|
||
(`{ $env, helpers }`) rather than reaching for globals — which has the happy
|
||
side effect that it's **unit-testable outside n8n entirely**.
|
||
- `gen_w1.js`, `gen_w2.js`, `gen_w3.js`, `gen_w4.js` read that file, inline it
|
||
into the workflow's Code node body, and update the workflow.
|
||
|
||
The result is one algorithm, four workflows, zero runtime dependencies — and a
|
||
version of the function that I can test with plain Node before it ever touches
|
||
a live system. The code is duplicated in *artifacts* but never in *sources*,
|
||
which is the same tradeoff a bundler makes.
|
||
|
||
One n8n-specific wrinkle worth knowing: **custom environment variables are only
|
||
reliably readable via `$env` inside a Code node — `process.env` is not
|
||
dependable there.** That's why every workflow has an explicit "Load Env" node
|
||
that lifts the values it needs onto the item, rather than reading config
|
||
wherever it's convenient.
|
||
|
||
## Making expiry safe to automate
|
||
|
||
W3 runs every five minutes and reconciles expiring entitlements. Two details
|
||
make it safe to let a cron job modify live access:
|
||
|
||
**It only disables when access genuinely ran out.** A naive "if no desired
|
||
paths, disable the user" rule is dangerous — it will happily disable a
|
||
brand-new customer who simply hasn't been granted anything yet. The guard is
|
||
explicit:
|
||
|
||
```js
|
||
// Only disable when a customer that HAD scopes now has none.
|
||
// currentPaths.length > 0 avoids killing a fresh, not-yet-granted customer.
|
||
const shouldDisable = AUTO_DISABLE && nowEmpty
|
||
&& cust.status === 'active' && currentPaths.length > 0;
|
||
```
|
||
|
||
**It has a dry-run mode.** `W3_DRY_RUN=true` on the container (or a query
|
||
parameter on the manual webhook for W4) makes the sweep compute and report its
|
||
plan while performing **zero writes**. Being able to ask "what would you do?"
|
||
before letting a schedule do it is the single most useful safety feature I've
|
||
added to any automation.
|
||
|
||
```js
|
||
const DRY_RUN = ($env.W3_DRY_RUN || '').toLowerCase() === 'true';
|
||
```
|
||
|
||
## The daily repair: assuming you'll drift
|
||
|
||
W4 is the workflow I'd argue is the real product. It runs at 03:00, walks every
|
||
customer, and compares desired state against actual state — then repairs the
|
||
difference and **verifies the repair**.
|
||
|
||
The drift matrix it handles:
|
||
|
||
- **Should be active** → user must exist (looked up *by username first*, to
|
||
avoid creating duplicates if a stored ID was lost), be enabled, and carry
|
||
exactly the computed role scopes.
|
||
- **Should be inactive** → disabled, with scopes emptied. Pending customers
|
||
stay without a user entirely — no auto-creation.
|
||
- **Dangling references** → a stored user or role ID points at a record that no
|
||
longer exists. Look it up by name, adopt it if found, recreate if not.
|
||
- **Username drift** → detected and *logged*, never destructive-migrated.
|
||
|
||
Every repair is verified by re-reading the file server's state afterwards. A
|
||
failed verification is logged as `verify_failed` rather than assumed successful,
|
||
and the reconciliation log only receives **drift, repair, and error rows** —
|
||
healthy customers produce nothing. That last choice is what makes the log
|
||
usable: if it's empty, everything is fine, and you don't have to read past a
|
||
thousand "no change" lines to find the one that matters.
|
||
|
||
## The public endpoint, and why there's no HMAC
|
||
|
||
W5 lets the file portal's footer show a signed-in customer their own purchases
|
||
and expiry dates. It's a **public** webhook, and the security reasoning is the
|
||
part I'm most deliberate about.
|
||
|
||
The obvious instinct is to sign requests with an HMAC. I didn't, and the reason
|
||
is worth stating plainly: **the key would have to ship to the browser, so the
|
||
signature would be theatre.** A shared secret that every client holds protects
|
||
nothing — it just adds ceremony that makes the endpoint *look* verified.
|
||
|
||
So the endpoint relies on things that actually hold:
|
||
|
||
- **CORS locked to one origin.** The response carries
|
||
`Access-Control-Allow-Origin: https://drive.example.com`, so only the portal's
|
||
own pages can read the response in a browser.
|
||
- **Minimal data by design.** The response returns product name, expiry date,
|
||
display state, and public folder paths. No internal database IDs, no customer
|
||
PII, nothing about other customers.
|
||
- **Rate limiting at the edge,** via a WAF rule on the request path, to blunt
|
||
username enumeration.
|
||
|
||
And one subtle architectural choice: **the username comes from the caller's own
|
||
session token, decoded client-side**, rather than from a parameter the client
|
||
can set freely. The endpoint never authenticates to the file server, which
|
||
avoids a whole class of connection state and device-registration side effects
|
||
that a server-side login would introduce on every footer render.
|
||
|
||
The honest framing: this endpoint is not a trust boundary, and I don't pretend
|
||
it is. It shows a customer what they already know about themselves, over a
|
||
response shape that's useless to anyone else.
|
||
|
||
## The bug that taught me the most: public path, cascading failure
|
||
|
||
W5 originally fetched data by calling NocoDB at its **public** hostname —
|
||
through a Cloudflare tunnel. It worked in testing. Under real load it produced
|
||
this chain:
|
||
|
||
1. Public round-trip latency exceeded 60 seconds under load.
|
||
2. nginx upstream timeout fired → **504**.
|
||
3. The footer's client-side fetch had an 8-second timeout and retried **every
|
||
second**.
|
||
4. Retries piled up connections.
|
||
5. Those connections exhausted the pool → **503** for unrelated requests.
|
||
|
||
A slow dependency became a cascading outage of a different service. The fix
|
||
was to stop crossing the internet to reach something on the same Docker
|
||
network:
|
||
|
||
```js
|
||
// n8n and NocoDB share the `bridge_hoelee` network; NocoDB listens on :10380.
|
||
// The public route added CF-tunnel jitter and could exceed the proxy timeout.
|
||
const NOCODB_URL = 'http://nocodb:10380';
|
||
```
|
||
|
||
**~30 ms internal versus 300 ms+ public, with no tunnel variance** — and the
|
||
entire failure chain disappeared, because the trigger condition (multi-second
|
||
latency) can no longer occur.
|
||
|
||
The lesson generalises well beyond this stack: **when a service and its
|
||
dependency are in the same container network, the public hostname is a bug
|
||
waiting for load.** And when you see a 503 downstream of a 504, look for a
|
||
client that retries aggressively — the retry loop is usually the amplifier, not
|
||
the original problem.
|
||
|
||
## What I'd do differently
|
||
|
||
1. **Build the drift repair first, not last.** I wrote the grant path, then the
|
||
expiry sweep, then the reconciliation. In retrospect the reconciliation is
|
||
what makes the other two safe to operate, and it should have existed from
|
||
day one — because "assume you will drift" is a design stance, not a feature.
|
||
2. **Write the desired-state function before any workflow.** Having it live in
|
||
`shared/` and be unit-testable *outside* n8n is why the whole system stayed
|
||
coherent across four workflows. If I'd started by pasting logic into nodes,
|
||
I'd have shipped four subtly different expiry rules.
|
||
3. **Never cross the public internet between two containers on the same host.**
|
||
This one cost me a genuine outage, and it's a rule I now apply by default
|
||
rather than discovering per-integration.
|
||
4. **Put the dry-run switch in from the beginning.** Adding `DRY_RUN` after the
|
||
fact was easy; operating a scheduled job that mutates access *without* one
|
||
was an unnecessary few weeks of nerves.
|
||
|
||
## The result
|
||
|
||
Five workflows run the full entitlement lifecycle: a purchase in the database
|
||
becomes usable access within seconds, expiries sweep every five minutes, and a
|
||
nightly full reconciliation repairs any drift and verifies each repair. The
|
||
reconciliation log is empty when everything is healthy — which, most days, is
|
||
what it says.
|
||
|
||
The design principle worth taking away is the one that made it tractable:
|
||
**stop administrating access, and start asserting it.** Define what a customer
|
||
should have as a pure function of your business data, apply that function
|
||
whenever the data changes, and re-assert it on a schedule to catch everything
|
||
else. Then the system doesn't need you to be careful — it just needs you to be
|
||
correct once, in one function.
|
||
|
||
---
|
||
|
||
## Want this for your business?
|
||
|
||
If you sell digital products and you're still granting file access by hand —
|
||
or you're not certain that expired customers lost access last month — I build
|
||
exactly this: self-hosted entitlement systems where access is computed from
|
||
your data, expires on its own, and repairs itself nightly. I work with
|
||
NocoDB, n8n, AList, and Docker, and I hand it back documented so you can
|
||
operate it without me.
|
||
|
||
Reach me at [[email protected]](mailto:[email protected]?subject=Access%20control%20for%20digital%20goods)
|
||
or WhatsApp [+60 12-797 2969](https://wa.me/60127972969), or see what I do at
|
||
[hoelee.com](https://hoelee.com).
|
||
````
|
||
|
||
---
|
||
|
||
## 文章 06 / 10:自建语音转文字服务:打字速度的五倍,而且数据不出内网
|
||
- **Slug**: `self-hosted-speech-to-text-api`
|
||
- **英文标题**: Your Own Speech-to-Text Server: Faster Than Typing, Private by Default
|
||
- **分类**: `case-studies` | **发布日期**: 2026-09-19
|
||
- **线上地址**: https://blog.hoelee.com/posts/self-hosted-speech-to-text-api/ (EN) | https://blog.hoelee.com/posts/zh/self-hosted-speech-to-text-api/ (ZH)
|
||
- **本篇审核状态**: ⏳ 待审核 (Pending)
|
||
|
||
### ✍️ 顾问审阅意见区 (Review Feedback)
|
||
```text
|
||
【审阅结论】:[ ] 通过 [ ] 需微调 [ ] 需重构
|
||
【事实与数字核对】:
|
||
【人设与用词卫生】:
|
||
【CRO与转化建议】:
|
||
```
|
||
|
||
### 🇨🇳 中文版原文 (Chinese Markdown Twin)
|
||
````markdown
|
||
---
|
||
title: "自建语音转文字服务:打字速度的五倍,而且数据不出内网"
|
||
description: "我用一台带 GPU 的电脑自建了语音转文字 API。Windows、iPhone、iPad、Android 都能语音输入——私密、不限量,速度是打字的大约 5 倍。"
|
||
pubDate: 2026-09-19
|
||
category: case-studies
|
||
tags: [whisper, cuda, stt, n8n, nginx, self-hosting, ai]
|
||
ogImage: /og/zh-self-hosted-speech-to-text-api.jpg
|
||
banner: /banners/self-hosted-speech-to-text-api.jpg
|
||
---
|
||
|
||
打字的办公效率里面,它是最慢的一环。一般人打字速度约每分钟 40 个字,但
|
||
**说话是 130 字**。每一封邮件、每一份报价、每一份报告、每一次客服回复、每一
|
||
条聊天消息,公司都在为这个差距付税——而付税的人通常是键盘打得最快的那个。
|
||
|
||
语音转文字可以把这个税省掉。但多数人采用的那套方案有两个问题:按人头收月费,
|
||
而且把你的声音——内部讨论、客户姓名、报价、合约内容——全部送到别人的云端。
|
||
|
||
所以我做了另一个版本:**一台办公室里的普通电脑,用它自己的 GPU,跑起一套
|
||
语音转文字 API。**我的开发电脑、iPhone、iPad、Android 手机都通过它来语音输入。
|
||
比打字快,不限量,而且没有任何数据离开我的内网。
|
||
|
||
以下是怎么做的——包括花掉我大半天时间的四个坑。
|
||
|
||
## 为什么值得做
|
||
|
||
语音转文字是办公自动化里杠杆最高、却又最不花哨的一环。具体来说,自建方案能给
|
||
你这些东西:
|
||
|
||
- **大约是打字的 5 倍吞吐量。**说话 130 wpm 对比打字约 40 wpm,口述一封 500 字
|
||
的邮件大约是说 4 分钟,而不是打 12 分钟。一天写 10 封邮件的人,每天省下一
|
||
小时。
|
||
- **成本跟着硬件走,不跟人头走。**云端听写是按用户按月收费,而且一直收。这套
|
||
跑在你自己买的机器上。加到第 10 个员工,边际成本是零。
|
||
- **不限长度,没有额度的焦虑。**没有分钟数上限,不会在星期五下午四点跳出来
|
||
说"你已用完本月额度"。
|
||
- **你的音频还是你的。**医疗记录、法律草稿、人事对话、客户报价——语音天生
|
||
就是敏感数据。自建意味着转写内容不会离开公司。
|
||
- **在任何已经获得焦点的程序里都能用。**不是那种"先转写、再复制粘贴"的网页
|
||
工具,而是可以直接在 Outlook、WhatsApp Web、CRM 或你自家内部系统里用的
|
||
输入键盘。
|
||
|
||
如果你公司里有一群人整天在写字,这件事的意义跟当年从拨号换到宽带是同一个
|
||
量级——而且它花的只是一张你可能早就有的显卡。
|
||
|
||
## 需要准备什么
|
||
|
||
| 部件 | 我用的是 | 说明 |
|
||
|---|---|---|
|
||
| GPU 电脑 | RTX 3060(12 GB)的台式机 | 任何显存 ≥6 GB 的 NVIDIA 显卡都行,可以就是一台普通办公电脑 |
|
||
| 转写引擎 | `whisper.cpp` + CUDA | 开源免费 |
|
||
| 模型 | `large-v3`(约 2.9 GB) | 准确率最好;小模型占显存更少 |
|
||
| 分发层 | n8n + nginx 网关 | 加上认证,端点才能安全共享 |
|
||
| 客户端 | 桌面程序、iPhone、iPad、Android | 任何支持 OpenAI 转写 API 的客户端 |
|
||
|
||
这台电脑不必专用。我的同时还在做开发、跑本地大模型推理和图像生成——模型在
|
||
有请求时加载、空闲时卸载,所以它不会长期占着显存。
|
||
|
||
## 整体架构
|
||
|
||
最重要的设计决定是:**手机从来不直接连 GPU。**中间有一个看门人负责认证,GPU
|
||
本身一直待在私有网络里。
|
||
|
||
```text
|
||
iPhone / iPad / Android / 办公电脑
|
||
│
|
||
│ HTTPS + 每台设备独立的 API key
|
||
▼
|
||
┌───────────────────────────┐
|
||
│ https://stt.example.com │ 公网 HTTPS 入口
|
||
│ reverse proxy │
|
||
└─────────────┬─────────────┘
|
||
▼
|
||
┌───────────────────────────┐
|
||
│ nginx 网关容器 │ 转发认证头,固定路由
|
||
└─────────────┬─────────────┘
|
||
▼
|
||
┌───────────────────────────┐
|
||
│ n8n 工作流 │ 校验 key,不符返回 401/403
|
||
│ (音频永不落库) │
|
||
└─────────────┬─────────────┘
|
||
▼
|
||
┌───────────────────────────┐
|
||
│ PC 上的 whisper.cpp │ GPU 转写
|
||
│ :20129 → {"text": …} │
|
||
└───────────────────────────┘
|
||
```
|
||
|
||
四层,每层只做一件事:代理终结 TLS,网关修好路由,n8n 负责授权,whisper 负责
|
||
转写。最终对外是 `POST /v1/audio/transcriptions`——跟 OpenAI 同一个形状,所以
|
||
任何 OpenAI 兼容的客户端都能零改动接上。
|
||
|
||
## 开始动手
|
||
|
||
whisper 需要 CUDA 和 CMake 工具链。在 Windows 上就是装三样东西然后编译:
|
||
|
||
```bash
|
||
git clone https://github.com/ggerganov/whisper.cpp
|
||
cd whisper.cpp
|
||
cmake -B build -DGGML_CUDA=ON -DCMAKE_CUDA_ARCHITECTURES=86
|
||
cmake --build build --config Release -j
|
||
```
|
||
|
||
然后取模型并启动:
|
||
|
||
```bash
|
||
# large-v3, ~2.9 GB
|
||
cd models && sh ./download-ggml-model.sh large-v3 && cd ..
|
||
./build/bin/Release/whisper-server.exe \
|
||
-m models/ggml-large-v3.bin \
|
||
--host 0.0.0.0 --port 20129 \
|
||
--convert
|
||
```
|
||
|
||
`--convert` 比看上去重要:有了它,服务可以接受 MP3 等压缩格式(内部调用
|
||
ffmpeg 转码),而不是逼每个客户端都发原始 WAV。多数手机 App 发的都是压缩音频。
|
||
|
||
到这里服务已经是一个可以用的转写 API 了。后面所有的工作,都是让它能够安全地
|
||
从手机访问。
|
||
|
||
## 坑一:CUDA Toolkit 装了一个不完整的编译器
|
||
|
||
CUDA Toolkit 安装程序的默认组件里包含 `nvcc`——但**不包含 `nvcc` 真正编译时
|
||
需要的那些部件**。我前两次 CMake 都因为缺头文件失败,而错误信息指向的是我的
|
||
编译配置,不是一个残缺的工具链。
|
||
|
||
解决办法是把三个组件显式勾上:
|
||
|
||
```text
|
||
crt_13.x → C 运行时头文件(缺的就是 <crt/host_config.h>)
|
||
nvvm_13.x → 里面有 cicc,才是真正的 CUDA 编译器后端
|
||
cublas_13.x → cuBLAS,运行时链接需要
|
||
```
|
||
|
||
要留意的症状:`nvcc --version` 能正常输出,但编译立刻因为缺头文件挂掉。
|
||
**能跑的 nvcc 不等于装好的工具链。**
|
||
|
||
## 坑二:它只监听 localhost,防火墙是无辜的
|
||
|
||
whisper 默认绑定 `127.0.0.1`——只有本机回环。不管防火墙怎么设,网络上的其他
|
||
设备都到不了。
|
||
|
||
我在这里浪费了不少时间,因为我认定是防火墙问题,反复测防火墙(甚至整个关掉),
|
||
而真正的原因在绑定地址上。loopback-only **在定义上**就拒绝所有其他网卡。
|
||
|
||
```bash
|
||
# 端口活着但没对外暴露时,长这样
|
||
netstat -an | grep 20129
|
||
# TCP 127.0.0.1:20129 0.0.0.0:0 LISTENING ← 只有你能连
|
||
```
|
||
|
||
改掉绑定,情况就不一样了:
|
||
|
||
```bash
|
||
--host 0.0.0.0
|
||
```
|
||
|
||
```text
|
||
TCP 0.0.0.0:20129 0.0.0.0:0 LISTENING ← 网络能连了
|
||
```
|
||
|
||
**先看绑定,再去碰防火墙。**这两种故障的表现完全一样——连接超时——而只有其中
|
||
一种真的是防火墙问题。
|
||
|
||
还有一个相关的小坑:Windows 防火墙的配置文件状态会自动恢复。一条限定
|
||
`Private,Domain` 的规则,在 Windows 把这个网络重新归类成 *Public* 之后就会
|
||
静默失效;某次更新把配置文件重新打开也有同样效果。规则要按网段限定,而不是按
|
||
配置文件名称:
|
||
|
||
```powershell
|
||
New-NetFirewallRule -DisplayName 'Whisper STT' -Direction Inbound -Action Allow `
|
||
-Protocol TCP -LocalPort 20129 -Profile Any -RemoteAddress LocalSubnet
|
||
```
|
||
|
||
`-RemoteAddress LocalSubnet` 让它在内网可用、在公网不可达——即使前面已经有
|
||
认证,这也才是正确的姿势。
|
||
|
||
## 坑三:n8n 会把你的音频丢掉(两次)
|
||
|
||
把 n8n 放在链路里是刻意的——API key 校验就住在那里——但它有两个行为会静默地
|
||
把代理弄坏。
|
||
|
||
**第一:Code 节点会丢弃二进制数据。**我的流程是 Webhook → Code(校验 key)→
|
||
HTTP Request(转发音频)。Code 节点返回的是 JSON,而 n8n 的二进制负载——也就
|
||
是音频本身——根本没穿过它。随后报错:*"Make sure that the previous node
|
||
outputs a binary file."*
|
||
|
||
n8n 的 Webhook 节点会接收 multipart 上传并存为二进制。要在校验 key 的同时把
|
||
它保住,Code 节点必须显式把二进制引用传下去,而不只是返回 JSON。而那个 key 的
|
||
名字,你绝对猜不到:
|
||
|
||
```text
|
||
┌──────────────┬────────────────────────────┐
|
||
│ 上传的字段名 │ n8n 里的 binary key │
|
||
├──────────────┼────────────────────────────┤
|
||
│ file │ data0 │
|
||
│ (第二个) │ data1 │
|
||
└──────────────┴────────────────────────────┘
|
||
```
|
||
|
||
multipart 字段叫 `file`,但 n8n 把它索引成 `data0`。转发 `$binary.data` 会失败,
|
||
`$binary.data0` 才行。
|
||
|
||
**第二:执行记录会把音频存下来。**n8n 默认保留执行数据——包括二进制负载——也
|
||
就是说每一次口述都会被写进工作流数据库。对音频来说这是不可接受的。关掉它:
|
||
|
||
```json
|
||
"settings": { "saveDataSuccessExecution": "none" }
|
||
```
|
||
|
||
⚠ **这是最有杀伤力的一个坑。**如果你通过 n8n API 改工作流而漏掉了 `settings`
|
||
对象,这次更新会**静默重置它**,于是你又开始记录音频了。系统不会有任何提示。
|
||
每次改完工作流都要验证:
|
||
|
||
```bash
|
||
curl -s -H "X-N8N-API-KEY: $KEY" \
|
||
http://localhost:5678/api/v1/workflows/<id> \
|
||
| jq '.settings'
|
||
```
|
||
|
||
## 坑四:nginx 自带的默认配置劫持了 80 端口
|
||
|
||
我的网关是一个 nginx 容器。它对那些明明配置好的路径一直返回 404——因为自带的
|
||
`default.conf` 同样在 80 端口声明了一个 server 块,而它作为默认 server 抢走了
|
||
流量。我的配置加载正常、内容正确,只是根本收不到请求。
|
||
|
||
```dockerfile
|
||
# 启动前删掉自带配置
|
||
command: >
|
||
sh -c "rm -f /etc/nginx/conf.d/default.conf && nginx -g 'daemon off;'"
|
||
```
|
||
|
||
同一个构建里还有两个小经验,部署到 NAS 之前值得先知道:
|
||
|
||
- **不能挂载一个还不存在的配置文件**——部署会失败,报 *"Bind mount failed:
|
||
... does not exist."* 在 DSM 上,从另一个容器里把文件写出来这个常见绕法也不行,
|
||
因为容器只看得见自己的挂载,看不见真正的主机文件系统。我最后把配置 base64
|
||
内嵌进 compose 的 `command`,启动时再写出来——完全不需要碰主机文件系统。
|
||
- **容器能看到的 `/volume1` 挂载是只读的**,所以那些看上去能写的路径都是封的。
|
||
|
||
## 授权模型,说实话
|
||
|
||
两层,值得讲清楚每一层到底买到了什么。
|
||
|
||
**每台设备独立的 API key。**每台设备有自己的 key,所以挂失一台手机不影响其他
|
||
设备:
|
||
|
||
```json
|
||
{
|
||
"iphone": "stt_<random>",
|
||
"ipad": "stt_<random>",
|
||
"laptop": "stt_<random>"
|
||
}
|
||
```
|
||
|
||
n8n 工作流拿 `Authorization` 头去比对这份名单,不匹配就返回真正的 403。有个
|
||
细节:API key 放在 URL 查询串里会落进代理日志和浏览器历史——始终放在请求头。
|
||
|
||
**这层保护了什么。**它阻止别人白用你的 GPU,也让这个端点不至于变成互联网上一个
|
||
人人可用的转写服务。它**不**负责加密音频——那是代理层的 TLS,这也是公网入口
|
||
只走 HTTPS 的原因。
|
||
|
||
这是**一个私有服务的访问控制**,不是一个加固过的公开 API。目前没有限流,也没有
|
||
按 key 的配额。对于几台已知设备的内网办公部署,这个比例是合适的;如果要开放给
|
||
第三方,那就得再加上限流、日志和轮换。
|
||
|
||
## 如果重来一次
|
||
|
||
1. **先验证绑定地址,而不是防火墙。**两个小时花在测错误的层上,而这件事
|
||
`netstat` 一行就能回答。两种故障都表现为"连接超时",而我本该知道
|
||
loopback-only 不管防火墙什么状态都会拒绝一切。
|
||
2. **确认安装程序到底装了什么。**我把 `nvcc --version` 当成了工具链可用的证据。
|
||
一个能跑、但找不到自己头文件的编译器,并不算装好了——而它的报错不会告诉你
|
||
这一点。
|
||
3. **在搭管线之前就定好日志策略,而不是搭完之后。**我是在构建过程中设上
|
||
`saveDataSuccessExecution: none` 的,但同一次修改如果走 API 就会静默地把
|
||
音频留存重新打开,毫无提示。能被无关操作重置的隐私设置,需要一个验证步骤。
|
||
|
||
## 结果
|
||
|
||
四类设备——一台 Windows 开发电脑、iPhone、iPad、Android——都在通过我自己网络上
|
||
的一张 GPU 做语音输入。短句转写通常远低于一秒,穿过四层之后的完整请求大约
|
||
2 秒返回真实文本。
|
||
|
||
最值得说的量化收益是显存。因为模型空闲时会卸载,一个开关就能把 GPU 占用从
|
||
**4,906 MiB 降到 1,321 MiB**——回收约 3.6 GB——机器可以回去做开发、本地大模型
|
||
推理或图像生成,下一次口述时再把模型加载回来。
|
||
|
||
关于速度,说句公道话:**大约比打字快 5 倍**这个数字对散文体(说话 130 wpm
|
||
对比打字约 40 wpm)是成立的。写代码就没这么夸张,因为那更多是在思考而不是在
|
||
打字。收益最大的是办公室真正被淹没的那部分工作——邮件、文档、笔记、合约、
|
||
客服回复。
|
||
|
||
## 这套东西能用在你的公司吗?
|
||
|
||
部件都不花哨,回报却很直接:一台带 GPU 的机器、开源软件,再加一层负责认证的
|
||
分发层。没有按人头的月费,没有分钟数配额,没有音频离开你的场地——全公司从打字
|
||
切换到语音输入。
|
||
|
||
我做的就是这类内部基础设施:带正规认证的自建服务、能合理共享硬件的 GPU 负载,
|
||
以及让它们在员工手上已有的设备里真正可用的集成层。如果你想让语音转文字(或者
|
||
其他内部 API)跑在你自己的硬件上——哪怕是公司现成的一台工作站——这正是我在做
|
||
的事。
|
||
|
||
联系我:[[email protected]](mailto:[email protected]?subject=自建语音转文字服务)
|
||
或 WhatsApp [+60 12-797 2969](https://wa.me/60127972969),也可以看看我在做什么:
|
||
[hoelee.com](https://hoelee.com)。
|
||
````
|
||
|
||
### 🇬🇧 英文版原文 (English Markdown Primary)
|
||
````markdown
|
||
---
|
||
title: "Your Own Speech-to-Text Server: Faster Than Typing, Private by Default"
|
||
description: "I run a self-hosted speech-to-text API on a single GPU PC. Dictation works from Windows, iPhone, iPad and Android — private, unlimited, and about 5x faster than typing."
|
||
pubDate: 2026-09-19
|
||
category: case-studies
|
||
tags: [whisper, cuda, stt, n8n, nginx, self-hosting, ai]
|
||
ogImage: /og/self-hosted-speech-to-text-api.jpg
|
||
banner: /banners/self-hosted-speech-to-text-api.jpg
|
||
---
|
||
|
||
Typing is the slowest thing most offices do all day. An average person types
|
||
40 words per minute; they *speak* 130. Every email, quotation, report, support
|
||
reply and chat message in your business pays that tax — and the tax is usually
|
||
paid by whoever is fastest at the keyboard.
|
||
|
||
Speech-to-text removes it. But the version most people adopt has two problems:
|
||
it costs a monthly subscription per seat, and it ships your voice — your
|
||
internal discussions, customer names, pricing, contracts — to someone else's
|
||
cloud.
|
||
|
||
So I built the other version: **one speech-to-text API running on a single
|
||
desktop PC in my office, with my own GPU doing the work.** My development PC,
|
||
my iPhone, an iPad and Android phones all dictate through it. It's faster than
|
||
typing, it's unlimited, and nothing leaves my network.
|
||
|
||
This is how it works — including the four traps that cost me most of a day.
|
||
|
||
## Why this matters
|
||
|
||
Speech-to-text is the highest-leverage office automation that isn't an AI
|
||
chatbot. Concretely, what a self-hosted setup buys you:
|
||
|
||
- **Roughly 5x the throughput of typing.** At 130 wpm spoken versus ~40 wpm
|
||
typed, dictating a 500-word email is about 4 minutes of talking instead of
|
||
12 minutes of typing. Someone who writes 10 emails a day gets an hour back —
|
||
every day.
|
||
- **Cost scales with hardware, not headcount.** Cloud dictation is priced per
|
||
user per month, forever. This one runs on hardware you own. Add the tenth
|
||
employee and the marginal cost is zero.
|
||
- **Unlimited length, no quota anxiety.** No minute caps, no "you've reached
|
||
your monthly limit" at 4pm on a Friday.
|
||
- **Your audio stays yours.** Medical notes, legal drafts, HR conversations,
|
||
customer pricing — voice is sensitive by default. Self-hosted means the
|
||
transcription never leaves the building.
|
||
- **It works in whatever app already has focus.** Not a separate transcribe-then-
|
||
paste website — a keyboard you use inside Outlook, WhatsApp Web, your CRM,
|
||
or your own internal tools.
|
||
|
||
If you run an office where people write all day, this is the same class of win
|
||
as moving from dial-up to broadband, and it costs a GPU you may already own.
|
||
|
||
## What you need
|
||
|
||
| Piece | What I used | Notes |
|
||
|---|---|---|
|
||
| GPU machine | Desktop PC with an RTX 3060 (12 GB) | Any NVIDIA card with ≥6 GB VRAM works; it can be a normal work PC |
|
||
| Whisper build | `whisper.cpp` with CUDA | Free, open source |
|
||
| Model | `large-v3` (~2.9 GB) | Best accuracy; smaller models use less VRAM |
|
||
| Delivery layer | n8n + nginx gateway | Adds auth, so the endpoint can be shared safely |
|
||
| Clients | Desktop app, iPhone, iPad, Android | Any client that speaks OpenAI's transcription API |
|
||
|
||
The PC doesn't have to be dedicated. Mine also runs development work,
|
||
local LLM inference and image generation — the model loads when a request
|
||
arrives and unloads when idle, so it isn't permanently holding VRAM.
|
||
|
||
## The architecture
|
||
|
||
The important design decision is that **the phones never talk to the GPU
|
||
directly.** There's a gatekeeper in between that handles authentication,
|
||
so the GPU itself stays on a private network.
|
||
|
||
```text
|
||
iPhone / iPad / Android / Work PCs
|
||
│
|
||
│ HTTPS + per-device API key
|
||
▼
|
||
┌───────────────────────────┐
|
||
│ https://stt.example.com │ public HTTPS entry
|
||
│ reverse proxy │
|
||
└─────────────┬─────────────┘
|
||
▼
|
||
┌───────────────────────────┐
|
||
│ nginx gateway container │ strips/forwards auth, fixed routes
|
||
└─────────────┬─────────────┘
|
||
▼
|
||
┌───────────────────────────┐
|
||
│ n8n workflow │ validates the key → 401/403 if wrong
|
||
│ (no audio ever logged) │
|
||
└─────────────┬─────────────┘
|
||
▼
|
||
┌───────────────────────────┐
|
||
│ whisper.cpp on the PC │ GPU transcription
|
||
│ :20129 → {"text": …} │
|
||
└───────────────────────────┘
|
||
```
|
||
|
||
Four layers, each doing one job: the proxy terminates TLS, the gateway fixes
|
||
routing, n8n authorises, whisper transcribes. The result is
|
||
`POST /v1/audio/transcriptions` — the same shape OpenAI uses, which means any
|
||
OpenAI-compatible client works with zero custom code.
|
||
|
||
## The build
|
||
|
||
Whisper needs CUDA and a CMake toolchain. On Windows that's three installs and
|
||
a build:
|
||
|
||
```bash
|
||
git clone https://github.com/ggerganov/whisper.cpp
|
||
cd whisper.cpp
|
||
cmake -B build -DGGML_CUDA=ON -DCMAKE_CUDA_ARCHITECTURES=86
|
||
cmake --build build --config Release -j
|
||
```
|
||
|
||
Then fetch the model and run it:
|
||
|
||
```bash
|
||
# large-v3, ~2.9 GB
|
||
cd models && sh ./download-ggml-model.sh large-v3 && cd ..
|
||
./build/bin/Release/whisper-server.exe \
|
||
-m models/ggml-large-v3.bin \
|
||
--host 0.0.0.0 --port 20129 \
|
||
--convert
|
||
```
|
||
|
||
`--convert` matters more than it looks: it lets the server accept MP3 and
|
||
other compressed formats by shelling out to ffmpeg, instead of forcing every
|
||
client to send raw WAV. Most mobile apps send compressed audio.
|
||
|
||
The server is now a working transcription API. Everything after this point
|
||
is about making it safe to reach from a phone.
|
||
|
||
## Trap 1: CUDA Toolkit installs an incomplete compiler
|
||
|
||
The CUDA Toolkit installer's default component selection includes `nvcc` — but
|
||
*not* the pieces `nvcc` needs to actually compile. My first two CMake runs both
|
||
failed on missing headers, and the errors pointed at my build config rather
|
||
than at a partial toolchain.
|
||
|
||
The fix is to add three components explicitly:
|
||
|
||
```text
|
||
crt_13.x → C runtime headers (the missing <crt/host_config.h>)
|
||
nvvm_13.x → contains cicc, the actual CUDA compiler backend
|
||
cublas_13.x → cuBLAS, required to link at runtime
|
||
```
|
||
|
||
Symptom to watch for: `nvcc --version` succeeds, but the build fails immediately
|
||
with a missing-header error. A working `nvcc` is not a working toolkit.
|
||
|
||
## Trap 2: it listens on localhost, so your firewall is innocent
|
||
|
||
Whisper's default bind is `127.0.0.1` — loopback only. Nothing else on the
|
||
network can reach it, no matter what your firewall says.
|
||
|
||
I lost real time here, because I assumed a firewall problem and tested the
|
||
firewall repeatedly (including turning it off entirely) while the actual cause
|
||
was the bind address. Loopback-only is *defined* to refuse every other
|
||
interface.
|
||
|
||
```bash
|
||
# what it looks like when the port is live but not exposed
|
||
netstat -an | grep 20129
|
||
# TCP 127.0.0.1:20129 0.0.0.0:0 LISTENING ← only you can reach it
|
||
```
|
||
|
||
Change the bind, and the picture changes:
|
||
|
||
```bash
|
||
--host 0.0.0.0
|
||
```
|
||
|
||
```text
|
||
TCP 0.0.0.0:20129 0.0.0.0:0 LISTENING ← the network can reach it
|
||
```
|
||
|
||
**Check the bind before you touch the firewall.** The two failures present
|
||
identically — a connection that times out — and only one of them is a firewall
|
||
problem.
|
||
|
||
One related gotcha: Windows Firewall profiles can re-enable themselves. A rule
|
||
scoped to `Private,Domain` will silently stop working on a network Windows has
|
||
since reclassified as *Public*, and an update that re-enables a profile has the
|
||
same effect. Scope the rule to the LAN subnet rather than to a profile name:
|
||
|
||
```powershell
|
||
New-NetFirewallRule -DisplayName 'Whisper STT' -Direction Inbound -Action Allow `
|
||
-Protocol TCP -LocalPort 20129 -Profile Any -RemoteAddress LocalSubnet
|
||
```
|
||
|
||
`-RemoteAddress LocalSubnet` keeps it reachable from your office while staying
|
||
unreachable from the internet — which is the correct posture even with auth in
|
||
front.
|
||
|
||
## Trap 3: n8n throws away your audio (twice)
|
||
|
||
Putting n8n in the path is deliberate — it's where the API key check lives — but
|
||
it has two behaviours that silently break a proxy.
|
||
|
||
**First: Code nodes discard binary data.** My workflow was Webhook → Code
|
||
(validate key) → HTTP Request (forward audio). The Code node returned JSON, and
|
||
n8n's binary payload — the audio itself — never made it past it. Subsequent
|
||
error: *"Make sure that the previous node outputs a binary file."*
|
||
|
||
n8n's Webhook node accepts multipart uploads and stores them as binary. To
|
||
preserve that through an auth check, the Code node must pass the binary
|
||
reference through explicitly, not just return JSON. And the key name is not
|
||
what you'd guess:
|
||
|
||
```text
|
||
┌──────────────┬────────────────────────────┐
|
||
│ input field │ binary key in n8n │
|
||
├──────────────┼────────────────────────────┤
|
||
│ file │ data0 │
|
||
│ (second) │ data1 │
|
||
└──────────────┴────────────────────────────┘
|
||
```
|
||
|
||
The multipart field is named `file`, but n8n indexes it as `data0`. Forwarding
|
||
`$binary.data` fails; `$binary.data0` works.
|
||
|
||
**Second: execution logging stores the audio.** By default n8n persists
|
||
execution data — including binary payloads — which means every dictation is
|
||
written to the workflow database. For audio that's unacceptable. Disabling it:
|
||
|
||
```json
|
||
"settings": { "saveDataSuccessExecution": "none" }
|
||
```
|
||
|
||
⚠ **This is the trap with teeth.** If you edit a workflow via the n8n API and
|
||
omit the `settings` object, the update **silently resets it** and you go back to
|
||
logging audio. Nothing warns you. Verify after every workflow change:
|
||
|
||
```bash
|
||
curl -s -H "X-N8N-API-KEY: $KEY" \
|
||
http://localhost:5678/api/v1/workflows/<id> \
|
||
| jq '.settings'
|
||
```
|
||
|
||
## Trap 4: the stock nginx config hijacks port 80
|
||
|
||
I run the gateway as an nginx container. It kept returning 404s for paths that
|
||
were definitely configured — because the stock `default.conf` also declares a
|
||
server block on port 80, and it wins as the default server. My config was
|
||
loaded and correct, and simply never saw the traffic.
|
||
|
||
```dockerfile
|
||
# remove the stock config before starting
|
||
command: >
|
||
sh -c "rm -f /etc/nginx/conf.d/default.conf && nginx -g 'daemon off;'"
|
||
```
|
||
|
||
Two smaller notes from the same build, both worth knowing before you deploy to
|
||
a NAS:
|
||
|
||
- **You can't bind-mount a config file you haven't created yet** — the deploy
|
||
fails with *"Bind mount failed: ... does not exist."* On DSM the obvious
|
||
workaround of writing the file from inside another container doesn't work
|
||
either, because containers see only their own mounts, never the real host
|
||
filesystem. I ended up base64-embedding the config in the compose `command`
|
||
and writing it at startup — no host filesystem access needed at all.
|
||
- **The `/volume1` mounts available to containers are read-only**, so the
|
||
obvious write paths are closed.
|
||
|
||
## The authorisation model, honestly
|
||
|
||
Two layers, and it's worth being precise about what each one buys you.
|
||
|
||
**Per-device API keys.** Each device gets its own key, so revoking a lost phone
|
||
doesn't affect anyone else:
|
||
|
||
```json
|
||
{
|
||
"iphone": "stt_<random>",
|
||
"ipad": "stt_<random>",
|
||
"laptop": "stt_<random>"
|
||
}
|
||
```
|
||
|
||
The n8n workflow checks the `Authorization` header against this list and
|
||
returns a real 403 when it doesn't match. One subtlety: an API key in a URL
|
||
query string lands in proxy logs and browser history — keep it in the header.
|
||
|
||
**What this protects.** It stops unauthorised use of your GPU and keeps the
|
||
endpoint from being an open transcription service on the internet. What it does
|
||
not do is encrypt the audio — that's TLS at the proxy layer, which is why the
|
||
public entry point is HTTPS-only.
|
||
|
||
This is **access control for a private service**, not a hardened public API.
|
||
There's no rate limiting and no per-key quota yet. For an internal office
|
||
deployment across a handful of known devices that's proportionate; if you were
|
||
opening it to third parties you'd want limits, logging and rotation on top.
|
||
|
||
## What I'd do differently
|
||
|
||
1. **Verify the bind address first, not the firewall.** Two hours went into
|
||
testing the wrong layer for a problem that `netstat` answers in one line.
|
||
Both failures are "connection timed out", and I should have known that
|
||
loopback-only refuses everything regardless of firewall state.
|
||
2. **Check what the toolkit installer actually installed.** I trusted
|
||
`nvcc --version` as proof of a working toolchain. A compiler that runs but
|
||
can't find its own headers is not installed, and the error message will not
|
||
tell you that.
|
||
3. **Set logging policy before wiring the pipeline, not after.** I configured
|
||
`saveDataSuccessExecution: none` during the build, but the same edit through
|
||
the API would have silently re-enabled audio retention with no warning.
|
||
Privacy settings that can be reset by an unrelated update need a verification
|
||
step.
|
||
|
||
## The result
|
||
|
||
Four devices — a Windows development PC, an iPhone, an iPad and Android — all
|
||
dictating through one GPU on my own network. Typical transcription of a short
|
||
sentence is well under a second, and the end-to-end request through all four
|
||
layers returns a real transcript in about 2 seconds.
|
||
|
||
The measured win that matters most is memory. Because the model unloads when
|
||
idle, a toggle drops GPU usage from **4,906 MiB to 1,321 MiB** — about 3.6 GB
|
||
returned — so the machine can go back to development work, local LLM inference
|
||
or image generation, then load the model again on the next dictation.
|
||
|
||
And the honest framing on speed: **roughly 5x faster than typing** is the
|
||
correct figure for prose (130 wpm spoken vs ~40 typed). It's less dramatic for
|
||
code, where you're thinking more than typing. The gain is largest for exactly
|
||
the work offices drown in — email, documentation, notes, contracts, support
|
||
replies.
|
||
|
||
## Could this work for your office?
|
||
|
||
The pieces are unglamorous and the payoff is immediate: one machine with a GPU,
|
||
open-source software, and a delivery layer for authentication. No per-seat
|
||
subscription, no minute quotas, no audio leaving your premises — and the whole
|
||
office dictating instead of typing.
|
||
|
||
I build exactly this kind of internal infrastructure: self-hosted services with
|
||
proper auth, GPU workloads that share hardware sensibly, and the integration
|
||
layer that makes them usable from the devices your staff already carry. If you
|
||
want speech-to-text (or another internal API) running on your own hardware —
|
||
or on a workstation you already own — that's the work I do.
|
||
|
||
Reach me at [[email protected]](mailto:[email protected]?subject=Self-hosted%20speech-to-text)
|
||
or WhatsApp [+60 12-797 2969](https://wa.me/60127972969), or see what I do at
|
||
[hoelee.com](https://hoelee.com).
|
||
````
|
||
|
||
---
|
||
|
||
## 文章 07 / 10:从云端转本地:在 12GB 显卡与群晖 N8N 上搭建中英混读高保真 TTS 语音栈
|
||
- **Slug**: `self-hosted-tts-cosyvoice2-n8n-gpu`
|
||
- **英文标题**: How I Replaced Cloud TTS with a Self-Hosted Neural Voice Stack on an RTX 3060
|
||
- **分类**: `case-studies` | **发布日期**: 2026-10-22
|
||
- **线上地址**: https://blog.hoelee.com/posts/self-hosted-tts-cosyvoice2-n8n-gpu/ (EN) | https://blog.hoelee.com/posts/zh/self-hosted-tts-cosyvoice2-n8n-gpu/ (ZH)
|
||
- **本篇审核状态**: ⏳ 待审核 (Pending)
|
||
|
||
### ✍️ 顾问审阅意见区 (Review Feedback)
|
||
```text
|
||
【审阅结论】:[ ] 通过 [ ] 需微调 [ ] 需重构
|
||
【事实与数字核对】:
|
||
【人设与用词卫生】:
|
||
【CRO与转化建议】:
|
||
```
|
||
|
||
### 🇨🇳 中文版原文 (Chinese Markdown Twin)
|
||
````markdown
|
||
---
|
||
title: "从云端转本地:在 12GB 显卡与群晖 N8N 上搭建中英混读高保真 TTS 语音栈"
|
||
description: "记录如何将内部自动化工作流从依赖公网 TTS API 迁移至本地 RTX 3060 12GB 显卡,基于 CosyVoice 2 与群晖 N8N 实现中英混读与多音色零样本克隆。"
|
||
pubDate: 2026-10-22
|
||
category: case-studies
|
||
blueprint: ai-agent-automation
|
||
blueprintLayer: L3-local-gpu-inference
|
||
tags: ["tts", "ai", "n8n", "gpu", "cosyvoice", "self-hosting"]
|
||
ogImage: "/og/zh-self-hosted-tts-cosyvoice2-n8n-gpu.jpg"
|
||
banner: "/banners/self-hosted-tts-cosyvoice2-n8n-gpu.jpg"
|
||
draft: false
|
||
---
|
||
|
||
在过去两年中,我们的内部业务自动化管线、Telegram 智能机器人以及视频知识库转写系统,一直依赖云端 Text-to-Speech(文本转语音)服务。起初,社区封装的 Microsoft Edge-TTS 提供了一个零成本的过渡方案;但依赖公网未公开接口的爬虫调用本质上极其脆弱——微软端点频繁变更签名、国内与海外网络抖动、以及跨国链路的偶发限流,经常导致自动化链路在半夜静默失败。而转用商业级 Azure Speech 或 Google Cloud TTS,在面对大批量长文本合成时,按字符计费的月度账单又显得不合算。
|
||
|
||
随着我们在 Unraid 服务器上为 Windows 11 虚拟机配置了直通的 **NVIDIA RTX 3060 12GB** 独立显卡,我们决定将整套语音合成系统完全收敛到本地局域网。
|
||
|
||
本文记录我们如何选型阿里巴巴开源的 **CosyVoice 2**,将其接入群晖 NAS 的 **n8n** 自动化集群,实现显存按需管理与开机常驻,并构建覆盖女童、正太、青年解说与纯正中英双语的零样本语音栈。
|
||
|
||
---
|
||
|
||
## 1. 核心需求与设计指标
|
||
|
||
在开工搭建之前,我们确立了四个关键要求:
|
||
|
||
1. **丝滑的中英混读(Code-switching)能力**:在马来西亚与东南亚的业务沟通场景中,日常对话几乎都是中英双语交织(例如:“*请确认这个 webhook 已经 trigger,并检查 logs*”)。传统的 TTS 模型在遇到英文字词时往往会生硬卡顿、甚至读错音素,引擎必须能够自然过渡。
|
||
2. **零样本(Zero-shot)多音色快速切换**:需要支持多种人设音色——讲故事需要的活泼童声、科技资讯需要的沉稳播音男声、以及客服交互需要的自然女声,且无需耗时数小时重新微调。
|
||
3. **显存共存与无痛调度**:12GB 显存是宝贵资产,这台工作机平时还要承载 LM Studio 的 Qwen 大模型推理以及 ComfyUI 生图生视频任务。TTS 引擎要么显存占用极小,要么能够随时一键启停释放显存。
|
||
4. **无缝替换群晖 n8n 旧节点**:自动化调度中心跑在群晖 DSM 的 n8n (`192.168.1.1:5678`) 上,本地新接口必须兼容通用 HTTP Webhook,无需重构现有工作流业务逻辑。
|
||
|
||
---
|
||
|
||
## 2. 模型选型:为什么是 CosyVoice 2?
|
||
|
||
针对中文、英文以及核心的**中英混读**场景,我们横向对比了目前主流的本地开源方案:
|
||
|
||
| 模型方案 | 优势 | 不足 | 选型结论 |
|
||
| :--- | :--- | :--- | :--- |
|
||
| **Edge-TTS / Piper** | 超轻量、纯 CPU 即可跑 | 音质机械感明显、无法自主克隆 | 彻底淘汰 |
|
||
| **ChatTTS** | 拟人化笑声与叹气细节好 | 经常胡言乱语、英文发音偏弱、长句难控 | 仅供玩票 |
|
||
| **GPT-SoVITS (v2)** | 特定人物音色克隆还原度极高 | 语种切换边界容易卡顿顿挫、中英混读较硬 | 备选 / 按需冷启 |
|
||
| **CosyVoice 2 (0.5B)** | **中英混读极度自然、首包延迟仅 300ms** | 常驻需要约 3.2GB 显存 | **生产主力首选** |
|
||
|
||
阿里开源的 **CosyVoice 2**(0.5B 自回归语言模型 + 流匹配 Flow Matching 解码器)在多语种混排上展现出了目前开源界的最佳水准。英文单词直接嵌入在中文句子中读出时,发音地道、重音准确,完全没有传统音素拼接的违和感。
|
||
|
||
---
|
||
|
||
## 3. 局域网网络与硬件拓扑
|
||
|
||
整套系统的部署拓扑如下:
|
||
|
||
```
|
||
[ 外部调用 / 终端应用 ]
|
||
│
|
||
▼
|
||
[ 群晖 DSM NAS (192.168.1.1) ]
|
||
├── 反向代理网关 (Traefik / Nginx)
|
||
└── n8n 自动化调度集群 (Stack 272)
|
||
│ 局域网 HTTP POST / GET (/webhook/ltts)
|
||
▼ (千兆内网无公网延迟)
|
||
[ Unraid 7.x 主机 (192.168.1.6) ]
|
||
└── Windows 11 虚拟机 (GPU 直通)
|
||
├── NVIDIA GeForce RTX 3060 12GB
|
||
└── CosyVoice 2 FastAPI 服务 (127.0.0.1:50000)
|
||
```
|
||
|
||
通过在 CosyVoice 的服务脚本中直接挂载 FastAPI 路由,我们在 Windows 本地 `50000` 端口暴露出 `/tts` 端点,内网其他服务只需向 `http://192.168.1.123:50000/tts` 发送请求即可在 2 秒内拿回二进制 WAV 音频。
|
||
|
||
---
|
||
|
||
## 4. 显存治理:常驻守护与一键开关
|
||
|
||
12GB 显存如果任由各个 AI 工具同时加载,瞬间就会爆显存(OOM)。我们采取了“分级常驻 + 幂等开关”策略:
|
||
|
||
1. **低显存常驻(日常状态)**:CosyVoice 2 推理仅占用 **3.2 GB 显存**,剩余近 9 GB 显存完全足以同时运行日常的系统桌面和轻量任务。我们将其写入 Windows 开机启动项(`shell:startup\CosyVoice 2.lnk`),开机静默常驻后台。
|
||
2. **一键切换脚本(高负载避让)**:当需要运行 ComfyUI 渲染整首 MV 或加载 14B 大语言模型时,桌面上放有一个免人工干预的批处理快捷方式 `CosyVoice 2 (开·关).bat`:
|
||
|
||
```bat
|
||
@echo off
|
||
title CosyVoice 2 Toggle
|
||
for /f "tokens=5" %%a in ('netstat -aon ^| findstr :50000') do (
|
||
taskkill /F /PID %%a >nul 2>&1
|
||
echo STOPPED. GPU 显存已完全释放。
|
||
exit /b
|
||
)
|
||
:: 若未运行,拉起后台推理服务
|
||
start /b python webui.py --port 50000 --model_dir pretrained_models/CosyVoice2-0.5B
|
||
echo ONLINE - CosyVoice 2 已加载至显卡,服务就绪。
|
||
```
|
||
|
||
双击一次即刻杀掉进程、半秒内退还 3.2GB 显存;渲染完毕后再双击一次,25 秒内重新完成模型加载。
|
||
|
||
---
|
||
|
||
## 5. 群晖 N8N 联动接入
|
||
|
||
我们在群晖 n8n 上配置了名为 **`Local TTS API (CosyVoice)`** 的独立工作流,绑定路径为 `/webhook/ltts`:
|
||
|
||
- **GET 支持**:`http://192.168.1.1:5678/webhook/ltts?text=你好Hello&voice=child`,浏览器或监控告警可直接单链调用下载。
|
||
- **POST 支持**:接收标准 JSON 体 `{"text": "...", "voice": "..."}`,供各类聊天机器人与后台脚本程序化触发。
|
||
|
||
在工作流内部,我们使用 JavaScript Code 节点对传入文本做字符解码与清洗,再通过 HTTP Request 节点转发给本地 50000 端口,最终以 `firstEntryBinary` 模式直接将音频流送还客户端。
|
||
|
||
---
|
||
|
||
## 6. 音色库扩展:零样本克隆实践
|
||
|
||
得益于 CosyVoice 2 的 Zero-shot 能力,只需提供 3~5 秒无杂音的人声样音,模型即可实时复刻其声线特征。我们在服务内部预制了常用音色表:
|
||
|
||
| 音色代号 | 声音风格 | 样音来源与特色 |
|
||
| :--- | :--- | :--- |
|
||
| `child` / `girl` | 活泼女童声 | 纯净 4 秒学前童声对话,清脆甜美 |
|
||
| `boy` | 清脆男童声(正太音) | 5 秒少儿动漫旁白 |
|
||
| `male` / `yunxi` | 阳光青年男声 | 5 秒科技解说,**中英专业词汇混读极佳** |
|
||
| `news` | 沉稳新闻男声 | 5 秒纪录片解说样本 |
|
||
| `female` | 温暖知性女声 | 5 秒电台散文朗诵 |
|
||
| `default` | 旗舰高保真女声 | CosyVoice 官方基准母声 |
|
||
|
||
调用时只需指定 `voice` 参数,无需重启后端或切换模型权重,即可实现毫秒级换人合成。
|
||
|
||
---
|
||
|
||
## 7. 运行成效
|
||
|
||
在本地 RTX 3060 上运行实测:
|
||
- **生成效率**:实时率(RTF)稳定在 **0.18** 左右,合成一段 10 秒的标准语音仅耗时约 **1.8 秒**。
|
||
- **首包响应**:n8n 收到请求至音频开始回传约 **320 毫秒**,完全满足交互式即时语音应答的要求。
|
||
- **自主掌控**:不再受制于第三方厂商的封号、限频与网络审查,所有音频资产与 Prompt 完全留存在本地内网。
|
||
|
||
自托管高品质 AI 语音不再是大型服务器集群的专利。借助新一代自回归+扩散语音架构与消费级显卡,一套完全受控、零月租且音质超越商业云服务的全天候语音栈,已经完全可以在自托管生产环境中稳定运转。
|
||
````
|
||
|
||
### 🇬🇧 英文版原文 (English Markdown Primary)
|
||
````markdown
|
||
---
|
||
title: "How I Replaced Cloud TTS with a Self-Hosted Neural Voice Stack on an RTX 3060"
|
||
description: "How I migrated our production automation workflows from cloud speech APIs to a self-hosted CosyVoice 2 pipeline on a 12GB RTX 3060, integrated with Synology N8N."
|
||
pubDate: 2026-10-22
|
||
category: case-studies
|
||
blueprint: ai-agent-automation
|
||
blueprintLayer: L3-local-gpu-inference
|
||
tags: ["tts", "ai", "n8n", "gpu", "cosyvoice", "self-hosting"]
|
||
ogImage: "/og/self-hosted-tts-cosyvoice2-n8n-gpu.jpg"
|
||
banner: "/banners/self-hosted-tts-cosyvoice2-n8n-gpu.jpg"
|
||
draft: false
|
||
---
|
||
|
||
For nearly two years, our internal business workflows, Telegram bots, and automated learning summaries relied on cloud-hosted text-to-speech APIs. Initially, Microsoft Edge-TTS provided a generous, zero-cost bridge. But running production workloads over unofficial browser-endpoint scraping is inherently fragile: sudden upstream schema changes, IP rate limits, and latency spikes across international transit routes routinely caused intermittent delivery drops. Commercial APIs like Azure Speech or Google Cloud TTS offered stability, but recurring meter billing scales awkwardly when generating long-form narration.
|
||
|
||
With a dedicated RTX 3060 12GB GPU passed through to a Windows 11 VM on our Unraid server, we decided to bring our entire speech synthesis stack fully on-premises.
|
||
|
||
Here is how we architected a self-hosted neural TTS pipeline using Alibaba's open-source **CosyVoice 2**, hooked it into our Synology DSM **n8n** automation cluster, managed GPU memory alongside our other local AI models, and achieved instant sub-second audio responses across Chinese, English, and mixed-language speech.
|
||
|
||
---
|
||
|
||
## 1. The Design Goals
|
||
|
||
Before touching code, our target operational envelope required four non-negotiable criteria:
|
||
|
||
1. **Fluid Bilingual Code-Switching**: In Malaysian and Southeast Asian business communication, text is almost never purely monolingual. Sentences naturally mix Chinese syntax with English technical terms (e.g., *"请检查这个 pull request 并确认 webhook 状态"*). The engine must articulate both languages without sudden cadence jumps or unnatural accent shifts.
|
||
2. **Zero-Shot Voice Variety**: We needed distinct voice profiles—cheerful child voices for storybook projects, authoritative male anchors for news roundups, and clear conversational female tones for support bots—cloned from brief reference clips without days of fine-tuning.
|
||
3. **Constrained VRAM Footprint**: The RTX 3060 has 12GB of VRAM. Our VM regularly runs local LLMs (Qwen GGUF on LM Studio) and ComfyUI image/video pipelines. The TTS engine had to either idle under ~3.5GB of VRAM or provide frictionless cold-start toggles.
|
||
4. **Drop-in Webhook Compatibility**: Our central automation runs on Synology DSM via n8n (`192.168.1.1:5678`). Replacing cloud nodes could not require rewriting dozens of downstream workflow schemas.
|
||
|
||
---
|
||
|
||
## 2. Model Selection: Why CosyVoice 2 Won
|
||
|
||
We evaluated the primary open-source contenders against our bilingual requirement:
|
||
|
||
| Model Architecture | Strengths | Drawbacks | Verdict |
|
||
| :--- | :--- | :--- | :--- |
|
||
| **Edge-TTS / Piper** | Ultra-lightweight, CPU-only | Robotic cadence, rigid voices, cloud dependency | Deprecated |
|
||
| **ChatTTS** | Conversational laughter, pause tags | Unpredictable halluncinations, weak English | Not suitable |
|
||
| **GPT-SoVITS v2** | Unrivaled character cloning accuracy | Phoneme boundaries stumble on mixed Chinese-English | Secondary / On-demand |
|
||
| **CosyVoice 2 (0.5B)** | **Superb bilingual flow, 300ms first-packet latency** | 3.2GB VRAM baseline | **Primary Production Engine** |
|
||
|
||
CosyVoice 2 (the 0.5B parameter variant from Alibaba's FunAudioLLM team) emerged as the definitive winner. By combining an autoregressive language model with flow-matching diffusion decoders, it treats cross-lingual text-to-speech as a unified sequence. English terms embedded inside Chinese phrases flow with native pronunciation and natural human breath pauses.
|
||
|
||
---
|
||
|
||
## 3. Infrastructure & Network Topology
|
||
|
||
Our self-managed infrastructure runs on a tiered hardware split:
|
||
|
||
```
|
||
[ Internet / Clients ]
|
||
│
|
||
▼
|
||
[ Synology DSM NAS (192.168.1.1) ]
|
||
├── Portainer / Traefik Reverse Proxy
|
||
└── n8n Automation Engine (Stack 272)
|
||
│ HTTP POST / GET (/webhook/ltts)
|
||
▼ (Local 1Gbps LAN)
|
||
[ Unraid 7.x Server (192.168.1.6) ]
|
||
└── Windows 11 VM (GPU Passthrough)
|
||
├── NVIDIA GeForce RTX 3060 12GB
|
||
└── CosyVoice 2 FastAPl Service (127.0.0.1:50000)
|
||
```
|
||
|
||
The Windows VM hosts the CUDA 12.x PyTorch runtime. We exposed a lightweight FastAPI wrapper inside CosyVoice’s runtime script (`webui.py`), allowing our Synology n8n instance to trigger generation over LAN via `http://192.168.1.123:50000/tts`.
|
||
|
||
---
|
||
|
||
## 4. Managing GPU Memory: Resident vs. On-Demand
|
||
|
||
Leaving every AI model loaded simultaneously will exhaust 12GB of VRAM instantly. We designed a dual-tier lifecycle:
|
||
|
||
1. **CosyVoice 2 as the Resident Daemon**: Consuming only **3.2 GB of VRAM**, CosyVoice 2 runs as an auto-starting background service when Windows boots (`shell:startup\CosyVoice 2.lnk`). This leaves 8.8 GB free for general desktop and lightweight inference.
|
||
2. **One-Click State Toggle Batches**: For heavy tasks (such as running 1080p video generation in ComfyUI or 14B LLMs), we created an idempotent batch script on the desktop:
|
||
|
||
```bat
|
||
@echo off
|
||
title CosyVoice 2 Toggle
|
||
for /f "tokens=5" %%a in ('netstat -aon ^| findstr :50000') do (
|
||
taskkill /F /PID %%a >nul 2>&1
|
||
echo STOPPED. GPU memory freed.
|
||
exit /b
|
||
)
|
||
:: If stopped, launch background worker
|
||
start /b python webui.py --port 50000 --model_dir pretrained_models/CosyVoice2-0.5B
|
||
echo ONLINE - CosyVoice 2 loaded to GPU.
|
||
```
|
||
|
||
A single double-click halts the process and reclaims all 3.2GB within 500ms; clicking it again restores the service in under 25 seconds.
|
||
|
||
---
|
||
|
||
## 5. Integrating with Synology N8N
|
||
|
||
In n8n, we configured a dedicated workflow: **`Local TTS API (CosyVoice)`** listening on `/webhook/ltts`.
|
||
|
||
To ensure total interoperability with existing scripts, the workflow accepts both:
|
||
- **`GET /webhook/ltts?text=Hello&voice=child`**: Ideal for browser testing and simple URL triggers.
|
||
- **`POST /webhook/ltts`** with JSON body `{"text": "...", "voice": "..."}`: Used by our bots and backend services.
|
||
|
||
The n8n pipeline consists of three streamlined nodes:
|
||
1. **Webhook Node**: Receives incoming requests.
|
||
2. **Parse & Clean Text (Code Node)**: Normalizes character encodings and defaults voice selections.
|
||
3. **HTTP Request Node**: Forwards the JSON payload to `http://192.168.1.123:50000/tts` and streams the binary `audio/wav` response directly back to the requester.
|
||
|
||
---
|
||
|
||
## 6. Curating Zero-Shot Reference Voices
|
||
|
||
CosyVoice 2 synthesizes speech using zero-shot voice cloning: feeding a 3- to 5-second clean audio sample allows the model to clone the acoustic timbre instantly.
|
||
|
||
We packaged a library of curated reference samples into `asset/voices/` and mapped them to intuitive alias parameters:
|
||
|
||
| Voice Key | Style Profile | Sample Source |
|
||
| :--- | :--- | :--- |
|
||
| `child` / `girl` | Cheerful female child voice | Clean 4s preschool dialogue clip |
|
||
| `boy` | Energetic young boy (anime style) | 5s youth animation dialogue |
|
||
| `male` / `yunxi` | Engaging, modern tech male anchor | 5s professional narration |
|
||
| `news` | Deep, formal broadcast presenter | 5s documentary voiceover |
|
||
| `female` | Warm, conversational support agent | 5s acoustic reading sample |
|
||
| `default` | Original CosyVoice high-fidelity voice | Model's baseline reference |
|
||
|
||
Switching voices is as simple as passing `&voice=child` in the query string or `{"voice": "male"}` in the POST payload.
|
||
|
||
---
|
||
|
||
## 7. Real-World Performance
|
||
|
||
Running on the RTX 3060:
|
||
- **Generation Speed**: Real-time factor (RTF) averages **0.18**. A 10-second sentence renders in under **1.8 seconds**.
|
||
- **Latency**: First audio packet arrives at n8n in approximately **320ms**, enabling near-instant voice replies on Telegram.
|
||
- **Cost & Privacy**: Zero monthly cloud API charges, zero audio data leaving our local subnet, and complete immunity to external provider outages.
|
||
|
||
Self-hosting modern neural TTS is no longer an exercise in brittle compile scripts and robotic phoneme tables. With open-source diffusion models and a modest 12GB workstation GPU, you can run a private, high-fidelity voice engine that surpasses commercial cloud offerings in customization and control.
|
||
````
|
||
|
||
---
|
||
|
||
## 文章 08 / 10:我如何在自家 NAS 上自托管 Mem0 记忆栈(让 AI 助手有记忆)
|
||
- **Slug**: `self-hosting-mem0-memory-stack`
|
||
- **英文标题**: How I Self-Hosted a Mem0 Memory Stack (So My AI Agent Remembers)
|
||
- **分类**: `case-studies` | **发布日期**: 2026-09-16
|
||
- **线上地址**: https://blog.hoelee.com/posts/self-hosting-mem0-memory-stack/ (EN) | https://blog.hoelee.com/posts/zh/self-hosting-mem0-memory-stack/ (ZH)
|
||
- **本篇审核状态**: ⏳ 待审核 (Pending)
|
||
|
||
### ✍️ 顾问审阅意见区 (Review Feedback)
|
||
```text
|
||
【审阅结论】:[ ] 通过 [ ] 需微调 [ ] 需重构
|
||
【事实与数字核对】:
|
||
【人设与用词卫生】:
|
||
【CRO与转化建议】:
|
||
```
|
||
|
||
### 🇨🇳 中文版原文 (Chinese Markdown Twin)
|
||
````markdown
|
||
---
|
||
title: "我如何在自家 NAS 上自托管 Mem0 记忆栈(让 AI 助手有记忆)"
|
||
description: "一套私有、自托管的 AI 助手记忆层——mem0 API + LiteLLM + PostgreSQL/pgvector,跑在 Synology NAS 上。语义记忆由你掌控,而不是第三方手里。"
|
||
pubDate: 2026-09-16
|
||
category: case-studies
|
||
tags: [mem0, docker, postgres, pgvector, litellm, ai, sharing]
|
||
ogImage: /og/zh-self-hosting-mem0-memory-stack.jpg
|
||
banner: /banners/self-hosting-mem0-memory-stack.jpg
|
||
---
|
||
|
||
一个每次对话后都忘光一切的 AI 助手,就是一个每轮都要你重新自我介绍的工具。我的 AI 助手(就是驱动这个博客工作流的那个)曾经每场会话都从零开始——直到我给它加了一层**记忆**:一套自托管的 [mem0](https://mem0.ai) 栈,负责存储它学到的事实、按语义检索、并跨会话存活。
|
||
|
||
这就是我在自家 Synology NAS 上自托管它的故事——私有、完全由我掌控、数据绝不离开我的局域网。
|
||
|
||
## 为什么这件事重要
|
||
|
||
记忆层改变的是一个助手真正能为企业做的事:
|
||
|
||
- **不再重复回答同样的问题。** 记住客户获批的试用、他买的产品、上次的售后问题——下一段对话从上一次结束的地方继续。
|
||
- **让「个性化」成真。** 一个记得客户偏好和历史记录的机器人,就是一个人。这不是提示词糖衣;这是一份存储的、可检索的记录。
|
||
- **把数据掌控权留在自己手里。** 我对托管式记忆服务不满的每一点,自托管都解决了——事实存在我自己的 PostgreSQL 里、我自己的 NAS 上、我自己网络的后面。
|
||
|
||
对任何跑 AI 助手(售后机器人、研究助手、个人自动化)的人来说,问题不是助手**要不要**记住——而是这份记忆是一份私有资产,还是第三方的数据。
|
||
|
||
## mem0 做了什么
|
||
|
||
Mem0 是给 LLM 应用用的「开箱即用的记忆」。你不用手搓嵌入表和相似度检索,它给一个小 API,把记忆需要的三件事都做了:
|
||
|
||
1. **加一条记忆** —— `POST /memories` 传一条事实或一段对话;它抽取、去重并存储(可选由 LLM 分类)。
|
||
2. **检索** —— `GET /search` 带一个 query,返回按语义相似度排序的相关事实。
|
||
3. **按用户隔离** —— 记忆归属 `user_id`,所以可以按客户、按项目、按会话分开,互不串扰。
|
||
|
||
「记忆」就是抽取出来的事实;「检索」就是向量相似度。哪怕你从没亲手碰过向量数据库,也能让助手有记忆。
|
||
|
||
## 技术栈
|
||
|
||
Synology DS1821+ 上用 Portainer compose 栈跑三个容器:
|
||
|
||
- **mem0 API** —— 记忆服务本身(本地自定义构建),监听 `20015` 端口。
|
||
- **LiteLLM** —— 真正做事实抽取的模型前面的 LLM 网关。不碰 mem0 配置就能换底层模型。
|
||
- **PostgreSQL 17 + pgvector** —— 数据库。`pgvector/pgvector` 把 Postgres 和向量扩展打包成一等公民,语义搜索和别的一切同库。
|
||
|
||
```text
|
||
┌──────────────┐ /search & /memories ┌──────────────────┐
|
||
│ AI agent / │ ──── X-Api-Key + JSON ───────▶ │ mem0 API :20015 │
|
||
│ Hermes / bot │ └────────┬─────────┘
|
||
└──────────────┘ │ pgvector
|
||
▼
|
||
PostgreSQL 17 + pgvector
|
||
┌──────────────┐ model calls (extract) ┌──────────────────┐
|
||
│ OpenAI etc. │ ◀───────── LiteLLM ──────────│ fact-classifier │
|
||
└──────────────┘ └──────────────────┘
|
||
```
|
||
|
||
一份有代表性的 compose 长这样:
|
||
|
||
```yaml
|
||
services:
|
||
mem0-postgres:
|
||
image: pgvector/pgvector:pg17
|
||
environment:
|
||
POSTGRES_USER: mem0
|
||
POSTGRES_PASSWORD: ${MEM0_DB_PASSWORD}
|
||
POSTGRES_DB: mem0
|
||
volumes:
|
||
- ./data/pg:/var/lib/postgresql/data
|
||
restart: unless-stopped
|
||
|
||
mem0-litellm:
|
||
image: ghcr.io/berriai/litellm:main-stable
|
||
command: ["--config", "/app/config.yaml"]
|
||
volumes:
|
||
- ./litellm-config.yaml:/app/config.yaml
|
||
restart: unless-stopped
|
||
|
||
mem0-api:
|
||
build: ./mem0-api
|
||
environment:
|
||
OPENAI_API_KEY: ${OPENAI_API_KEY}
|
||
OPENAI_API_BASE: http://mem0-litellm:4000/v1 # go through the gateway
|
||
MEM0_API_KEY: ${MEM0_API_KEY} # X-Api-Key for /search & /memories
|
||
POSTGRES_URL: postgresql://mem0:${MEM0_DB_PASSWORD}@mem0-postgres/mem0
|
||
ports:
|
||
- "20015:8000"
|
||
restart: unless-stopped
|
||
```
|
||
|
||
(我是从 mem0 仓库本地构建、把模型/事实抽取指向 LiteLLM;确切的镜像版本是我自己维护本地镜像的结果。真实 API key 我放在 compose 文件外面,走环境变量密文注入。)
|
||
|
||
## 使用
|
||
|
||
起起来之后,这个 API 小到意外。加一条事实(快速、逐字保存):
|
||
|
||
```bash
|
||
curl -X POST http://192.168.1.1:20015/memories \
|
||
-H "Content-Type: application/json" \
|
||
-H "X-Api-Key: $MEM0_API_KEY" \
|
||
-d '{
|
||
"user_id": "customer-2211",
|
||
"text": "Customer 2211 prefers email over WhatsApp for order updates."
|
||
}'
|
||
```
|
||
|
||
之后再取最相关的记忆:
|
||
|
||
```bash
|
||
curl -X POST http://192.168.1.1:20015/memories/search \
|
||
-H "Content-Type: application/json" \
|
||
-H "X-Api-Key: $MEM0_API_KEY" \
|
||
-d '{
|
||
"user_id": "customer-2211",
|
||
"query": "how should I reach this customer?",
|
||
"limit": 5
|
||
}'
|
||
```
|
||
|
||
然后把返回的事实塞进助手回答前的系统提示词(或上下文)。这就是全部循环:**存事实、召回相关的、在下一句回复里用上。**
|
||
|
||
### 让我花了一天时间的 `infer` 坑
|
||
|
||
- `POST /memories` 默认 **`infer=true`** 会跑 LLM 事实抽取器——分类、清洗每条记忆。聪明但**慢**,而且每次调用都要一次模型往返。
|
||
- 如果我只是想让助手**逐字快速地**记下某件事(客户说「请叫我 Andy」),我传 **`infer=false`**——不经过 LLM,近乎瞬时存储。
|
||
|
||
我栈上的路由是 `/search` 和 `/memories`,**没有 `/v1` 前缀**(早期一个自以为有 `/v1` 的包装器 404 了一阵子),认证是朴实的 `X-Api-Key` 头。都是小事,但都让我费过时间。
|
||
|
||
## 如果重来我会怎么做
|
||
|
||
- **从第一天起对常规记录就用 `infer=false`。** 只对重要的事实跑 LLM 抽取;默认的推理模式让每一次写入都为了一句随手记付出的成本不值。
|
||
- **把 API key 当真正的机密。** 它会嵌进 agent 配置和 compose 环境变量里,所以我把它从 compose 文件中拿出来,用环境密文注入。
|
||
- **把数据库放在我信任的盘上。** Mem0 的下限就是你 Postgres 的下限。我把它跑在 NAS 受保护的卷上、带备份任务——因为一个会失忆的记忆层还不如没有。
|
||
|
||
## 结果
|
||
|
||
一层私有、自托管的记忆,用两个小 HTTP 调用就能访问。我的助手现在跨会话记得客户、偏好和决策——而且因为整个栈都在我自己网络后面的 PostgreSQL 里,这一切都没有离开我的掌控。
|
||
|
||
如果你跑的 AI 助手动不动就忘掉上下文,自托管 mem0 是最划算、最省事的升级之一——而且你能在不把记忆送进别人数据库的前提下做到。
|
||
|
||
---
|
||
|
||
## 想让你的生意也用上带记忆的 AI 吗?
|
||
|
||
我为企业构建并自托管 AI 助手、记忆栈、网站和基础设施。如果你想让助手真正**记住**你的客户——或者你想聊聊雇佣我——我很乐意帮上忙:
|
||
|
||
- 📱 **WhatsApp:** [+60 12-797 2969](https://wa.me/60127972969)
|
||
- 📧 **邮箱:** [[email protected]](mailto:[email protected])
|
||
- 🌐 **网站:** [hoelee.com](https://hoelee.com)
|
||
````
|
||
|
||
### 🇬🇧 英文版原文 (English Markdown Primary)
|
||
````markdown
|
||
---
|
||
title: "How I Self-Hosted a Mem0 Memory Stack (So My AI Agent Remembers)"
|
||
description: "A private, self-hosted memory layer for AI agents — mem0 API + LiteLLM + PostgreSQL with pgvector on a Synology NAS. Semantic memory under your control, not a third party's."
|
||
pubDate: 2026-09-16
|
||
category: case-studies
|
||
tags: [mem0, docker, postgres, pgvector, litellm, ai, sharing]
|
||
ogImage: /og/self-hosting-mem0-memory-stack.jpg
|
||
banner: /banners/self-hosting-mem0-memory-stack.jpg
|
||
---
|
||
|
||
An AI agent that forgets everything between conversations is a tool you have
|
||
to reintroduce yourself to every session. My AI assistant (the one that runs
|
||
this very blog's workflow) used to start each chat from zero — until I gave it
|
||
a **memory layer**: a self-hosted [mem0](https://mem0.ai) stack that stores
|
||
facts it learns, retrieves them semantically, and survives across sessions.
|
||
|
||
This is the story of how I self-hosted it on my Synology NAS — private, fully
|
||
under my control, no data leaving my LAN.
|
||
|
||
## Why this matters
|
||
|
||
A memory layer changes what an agent can actually *do* for a business:
|
||
|
||
- **It stops re-answering the same questions.** Remember a customer's granted
|
||
trial, their product, their last support issue — and the next conversation
|
||
picks up where the last one ended.
|
||
- **It makes "personalization" real.** A bot that recalls your customer's
|
||
preferences and history is a bot that feels like a person. That's not
|
||
prompt-sugar; it's a stored, searchable record.
|
||
- **It keeps control of your data.** Every "memory" I dislike about hosted
|
||
memory services is solved by running the stack yourself — the facts live
|
||
in my own PostgreSQL, on my own NAS, behind my own network.
|
||
|
||
For anyone running AI agents (support bots, research assistants, personal
|
||
automation) the question isn't *should* the agent remember — it's whether the
|
||
memory is a private asset or a third party's.
|
||
|
||
## What mem0 does
|
||
|
||
Mem0 is "memory in a box" for LLM apps. Instead of you hand-rolling an
|
||
embeddings table and a similarity search, it gives you a small API that does
|
||
the three things memory needs:
|
||
|
||
1. **Add a memory** — `POST /memories` with a fact or a conversation; it
|
||
extracts, dedupes, and stores it (optionally classified by an LLM).
|
||
2. **Search** — `GET /search` with a query returns the most relevant stored
|
||
facts, ranked by semantic similarity.
|
||
3. **User scoping** — memories belong to a `user_id`, so you can keep memory
|
||
per customer, per project, or per conversation without cross-talk.
|
||
|
||
The "memory" is the extracted fact. The "retrieval" is vector similarity. You
|
||
get the agent even if you never touch a vector database yourself.
|
||
|
||
## The stack
|
||
|
||
Three containers on my Synology DS1821+, as a Portainer compose stack:
|
||
|
||
- **mem0 API** — the memory service itself (custom local build), listening
|
||
on port `20015`.
|
||
- **LiteLLM** — the LLM gateway in front of whatever model does the fact
|
||
extraction. I can swap the underlying model without touching mem0's config.
|
||
- **PostgreSQL 17 + pgvector** — the database. `pgvector/pgvector` bundles
|
||
Postgres with the vector extension as a first-class citizen, so semantic
|
||
search lives in the same DB as everything else.
|
||
|
||
```text
|
||
┌──────────────┐ /search & /memories ┌──────────────────┐
|
||
│ AI agent / │ ──── X-Api-Key + JSON ───────▶ │ mem0 API :20015 │
|
||
│ Hermes / bot │ └────────┬─────────┘
|
||
└──────────────┘ │ pgvector
|
||
▼
|
||
PostgreSQL 17 + pgvector
|
||
┌──────────────┐ model calls (extract) ┌──────────────────┐
|
||
│ OpenAI etc. │ ◀───────── LiteLLM ──────────│ fact-classifier │
|
||
└──────────────┘ └──────────────────┘
|
||
```
|
||
|
||
A representative compose looks like this:
|
||
|
||
```yaml
|
||
services:
|
||
mem0-postgres:
|
||
image: pgvector/pgvector:pg17
|
||
environment:
|
||
POSTGRES_USER: mem0
|
||
POSTGRES_PASSWORD: ${MEM0_DB_PASSWORD}
|
||
POSTGRES_DB: mem0
|
||
volumes:
|
||
- ./data/pg:/var/lib/postgresql/data
|
||
restart: unless-stopped
|
||
|
||
mem0-litellm:
|
||
image: ghcr.io/berriai/litellm:main-stable
|
||
command: ["--config", "/app/config.yaml"]
|
||
volumes:
|
||
- ./litellm-config.yaml:/app/config.yaml
|
||
restart: unless-stopped
|
||
|
||
mem0-api:
|
||
build: ./mem0-api
|
||
environment:
|
||
OPENAI_API_KEY: ${OPENAI_API_KEY}
|
||
OPENAI_API_BASE: http://mem0-litellm:4000/v1 # go through the gateway
|
||
MEM0_API_KEY: ${MEM0_API_KEY} # X-Api-Key for /search & /memories
|
||
POSTGRES_URL: postgresql://mem0:${MEM0_DB_PASSWORD}@mem0-postgres/mem0
|
||
ports:
|
||
- "20015:8000"
|
||
restart: unless-stopped
|
||
```
|
||
|
||
(Mine is built from the mem0 repo with the model/fact-extraction directed
|
||
through LiteLLM; the exact image tag is me maintaining a local build, and I
|
||
keep the real API key out of the compose file — it's an env secret.)
|
||
|
||
## Using it
|
||
|
||
Once it's up, the API is refreshingly small. Add a fact (fast, verbatim):
|
||
|
||
```bash
|
||
curl -X POST http://192.168.1.1:20015/memories \
|
||
-H "Content-Type: application/json" \
|
||
-H "X-Api-Key: $MEM0_API_KEY" \
|
||
-d '{
|
||
"user_id": "customer-2211",
|
||
"text": "Customer 2211 prefers email over WhatsApp for order updates."
|
||
}'
|
||
```
|
||
|
||
Retrieve the most relevant memories later:
|
||
|
||
```bash
|
||
curl -X POST http://192.168.1.1:20015/memories/search \
|
||
-H "Content-Type: application/json" \
|
||
-H "X-Api-Key: $MEM0_API_KEY" \
|
||
-d '{
|
||
"user_id": "customer-2211",
|
||
"query": "how should I reach this customer?",
|
||
"limit": 5
|
||
}'
|
||
```
|
||
|
||
Then inject the returned facts into the agent's system prompt (or context)
|
||
before it answers. That's the whole loop: **store facts, retrieve what's
|
||
relevant, use it in the next reply.**
|
||
|
||
### The `infer` gotcha that cost me a day
|
||
|
||
- `POST /memories` with the **default `infer=true`** runs the LLM fact
|
||
extractor — it classifies and cleans each memory. That's smart but **slow**,
|
||
and every call costs a model round-trip.
|
||
- If I just want the agent to note something verbatim and fast (user said
|
||
"please call me Andy"), I pass **`infer=false`** — no LLM hop, near-instant
|
||
storage.
|
||
|
||
The route of my stack is `/search` and `/memories` **without a `/v1` prefix**
|
||
(an early wrapper that assumed `/v1` 404'd for a while), and auth is a plain
|
||
`X-Api-Key` header. Small details, but they cost me time to discover.
|
||
|
||
## What I'd do differently
|
||
|
||
- **Set `infer=false` for routine logging from day one.** Only run the LLM
|
||
extractor on the facts that matter; the default inference mode makes every
|
||
write pricey for no benefit on throwaway notes.
|
||
- **Treat the API key as a real secret.** It gets embedded in agent configs
|
||
and compose envs, so I keep it out of the compose file and inject it via
|
||
environment secrets.
|
||
- **Put the DB on a disk I trust.** Mem0 is only as durable as its Postgres.
|
||
I run it on my NAS's protected volumes, with a backup job — because a
|
||
memory layer that forgets is worse than none.
|
||
|
||
## The result
|
||
|
||
A private, self-hosted memory layer answered by two small HTTP calls. My
|
||
agent now remembers customers, preferences, and decisions across sessions —
|
||
and because the stack sits in my own PostgreSQL behind my own network, none
|
||
of that leaves my control.
|
||
|
||
If you run AI agents that keep forgetting their context, self-hosting mem0
|
||
is one of the highest-value, lowest-friction upgrades you can make — and you
|
||
can do it without sending your memory to someone else's database.
|
||
|
||
---
|
||
|
||
## Want a memory-enabled AI setup for your business?
|
||
|
||
I build and self-host AI agents, memory stacks, websites, and infrastructure
|
||
for businesses. If you'd like your assistant to actually *remember* your
|
||
customers — or you want to talk about hiring me — I'd love to help:
|
||
|
||
- 📱 **WhatsApp:** [+60 12-797 2969](https://wa.me/60127972969)
|
||
- 📧 **Email:** [[email protected]](mailto:[email protected])
|
||
- 🌐 **Website:** [hoelee.com](https://hoelee.com)
|
||
````
|
||
|
||
---
|
||
|
||
## 文章 09 / 10:把 AI 修图工具做成 WordPress 插件:22 个版本换来的经验
|
||
- **Slug**: `shipping-an-ai-photo-editor-as-a-wordpress-plugin`
|
||
- **英文标题**: Shipping an AI Photo Editor as a WordPress Plugin: 22 Versions of Hard Lessons
|
||
- **分类**: `case-studies` | **发布日期**: 2026-09-18
|
||
- **线上地址**: https://blog.hoelee.com/posts/shipping-an-ai-photo-editor-as-a-wordpress-plugin/ (EN) | https://blog.hoelee.com/posts/zh/shipping-an-ai-photo-editor-as-a-wordpress-plugin/ (ZH)
|
||
- **本篇审核状态**: ⏳ 待审核 (Pending)
|
||
|
||
### ✍️ 顾问审阅意见区 (Review Feedback)
|
||
```text
|
||
【审阅结论】:[ ] 通过 [ ] 需微调 [ ] 需重构
|
||
【事实与数字核对】:
|
||
【人设与用词卫生】:
|
||
【CRO与转化建议】:
|
||
```
|
||
|
||
### 🇨🇳 中文版原文 (Chinese Markdown Twin)
|
||
````markdown
|
||
---
|
||
title: "把 AI 修图工具做成 WordPress 插件:22 个版本换来的经验"
|
||
description: "从单个 HTML 文件到一个真正上线的 WordPress 插件:fal.ai 异步队列、绝不能静默失败的水印、可选的名单元件,以及五个只有在真实环境里才会出现的 bug。"
|
||
pubDate: 2026-09-18
|
||
category: case-studies
|
||
blueprint: sme-digital-suite
|
||
blueprintLayer: L1-high-conversion-web
|
||
tags: [wordpress, php, fal-ai, docker, ai-image, javascript]
|
||
ogImage: /og/zh-shipping-an-ai-photo-editor-as-a-wordpress-plugin.jpg
|
||
banner: /banners/shipping-an-ai-photo-editor-as-a-wordpress-plugin.jpg
|
||
draft: false
|
||
---
|
||
|
||
几周前我[写过那个概念验证](/posts/zh/ai-furniture-compositing-with-flux-kontext/):一个
|
||
`index.html`、没有后端,两张家具照片进去,一张布置好的房间场景出来。它回答了
|
||
它本该回答的问题——*能不能保住真实的产品,只把周围的房间生成出来?*——同时留下
|
||
了一个显而易见的问题。
|
||
|
||
那篇 PoC 的结尾写着「*在决定做成完整的 WordPress 插件之前*」。这篇文章讲的就是
|
||
那个插件。它从 `0.0.1` 走到 `0.0.22`,58 个 commit,而其中几乎没有任何工作是 AI 那部分。
|
||
|
||
## 为什么这件事值得关心(写给老板,不是写给开发者)
|
||
|
||
PoC 的局限在于它活在一个 HTML 文件里,API key 就写在源码里。作为发给客户看的演示,
|
||
这没问题。但一家家具店要把这东西放到自己网站上,就不行了:
|
||
|
||
- **API key 不能出现在浏览器里。** 任何人 view-source 就能看到,然后把你的 fal.ai
|
||
额度刷光。它必须放在服务端,由一个管理员控制的设置页面来管。
|
||
- **没人想盯着生成过程。** 访客上传、等待、拿到图。如果中途挂了,店主根本不该知道。
|
||
- **顾客的照片不能泄露。** 匿名访客的原图绝不能进公开的媒体库;生成结果除非
|
||
*那位访客本人*同意分享,否则也不能公开。
|
||
- **输出必须带水印。** 否则你就是在给整个互联网提供免费 AI 修图服务。
|
||
- **店主需要拿到线索。** 一个只会产出一张漂亮图片、拿不到联系方式的 AI 工具是个玩具。
|
||
接上表单和 webhook,它就是家具生意的线索管道。
|
||
|
||
上面这五条都是**产品**需求,而每一条都比那次 AI 调用本身花的代码更多。
|
||
|
||
## 架构:真正让它跑起来的无聊部分
|
||
|
||
这是一个正常的 WordPress 插件——PHP 前缀 `hre_`、命名空间 `HRE`、激活时用
|
||
`dbDelta()` 建自定义表、自带 autoloader、运行时不依赖 Composer。有意思的决策在别处。
|
||
|
||
### 生成永远是异步的
|
||
|
||
fal.ai 的任务要 15–20 秒。PHP-FPM 的请求超时、`max_execution_time`、以及没耐心的
|
||
访客,让同步生成注定失败。所以流程是「入队 + 轮询」:
|
||
|
||
```
|
||
访客上传 → POST /uploads → 归一化 → 启动视觉分析
|
||
访客选择 → GET /prompts/{cat} → 每个风格的提示词
|
||
访客确认 → POST /jobs → fal 入队(返回 uuid)
|
||
浏览器轮询 → GET /jobs/{uuid} → status: queued | processing | done
|
||
```
|
||
|
||
访客永远不等服务商。任务行携带 fal 的请求 id,轮询要么拿到完成的结果,要么显示
|
||
真实的进度。前端是跑在 session cookie 上的小型状态机,所以中途刷新页面会回到
|
||
访客原来所在的位置。
|
||
|
||
### 归属权靠 session cookie,不靠 URL 里的 ID
|
||
|
||
匿名访客没有账号,这让授权很容易做错。我最终定下的规则是:
|
||
**每一次读取都通过调用者自己的 session hash 来解析**,绝不接受客户端传来的 ID。
|
||
|
||
- `GET /preview` 只输出调用者**自己**归一化后的上传图。它根本没有路径或 URL 参数
|
||
——别人请求它只会得到 404,因为那个 session 里没有文件。这也让私有存储路径
|
||
不会出现在任何 JSON 响应里。
|
||
- `GET /jobs/{uuid}` 是按 *session hash + uuid* 查任务的。从别的浏览器猜一个 UUID
|
||
什么也拿不到。
|
||
|
||
就这一个决策,消掉了「我改了 URL 里的 id 就看到了别人的照片」这一整类 bug。
|
||
|
||
### 水印是硬需求,所以回退逻辑绝不能静默
|
||
|
||
这个 bug 教给我的最多。水印那一步做的是 GD `imagecopyresampled` 合成。如果它失败,
|
||
一个很诱人的「有韧性」的写法是:
|
||
|
||
```php
|
||
// 别这么写
|
||
if ( ! $watermarked ) {
|
||
rename( $stage, $final ); // 直接把没水印的文件发出去
|
||
}
|
||
```
|
||
|
||
我当初就是这么写的。它完全静默、没有日志,插件会心安理得地输出没有水印的结果,
|
||
而后台还显示「水印:已开启」。店主几周后才发现,是因为看到了一张没水印的图。
|
||
|
||
修法分三部分:
|
||
|
||
1. **记录根因,而不是最近的那个症状。** `apply()` 返回的是
|
||
`hre_no_watermark_source`——一个下游错误。真正的原因是水印来源的解析链
|
||
(`site_logo` → `get_theme_mod('custom_logo')`)根本没解析到 logo。我加了一个
|
||
`block_reason()` 诊断,重新走一遍解析链,并针对每个失败分支返回**具体**信息。
|
||
2. **在后台暴露出来。** 一条常驻的 `notice-warning` 提示:水印已开启但不会被应用,
|
||
并附上具体原因。不需要去翻日志。
|
||
3. **让失败在测试时就看得见。** 一个独立探针把已知水印合成到已知底图上,并采样
|
||
预期水印矩形内的一个像素——这证明了变换路径本身是好的,从而把「功能坏了」和
|
||
「功能没配好」区分开。
|
||
|
||
**我现在遵守的规则:** 当某个「尽力而为」的分支掩盖了一个不可协商的变换时,它必须
|
||
记录具体原因**并且**在后台 UI 里告警。一个悄悄让必需功能降级的回退不是韧性——那是
|
||
一个有礼貌的 bug。
|
||
|
||
### 名单元件:默认关闭,开启后异步
|
||
|
||
名单元件是一个总开关。关闭时插件什么都不收集,向导的行为和以前完全一样。开启时,
|
||
管理员配置的字段会在生成之前变成必填,存入自定义表,并转发到 webhook。
|
||
|
||
两个值得照抄的决策:
|
||
|
||
- **字段列表由管理员定义、完全动态**——`{key, label, type, required, placeholder,
|
||
options[]}`——所以前端表单是照着配置把自己渲染出来的。默认的五项(姓名、电话、
|
||
邮箱、留言、同意)只是起点,店主可以整个替换。
|
||
- **Webhook 投递是排程的,绝不内联执行。** 访客不该为别人的接口等待:
|
||
|
||
```php
|
||
wp_schedule_single_event( time() + 5, 'hre_lead_webhook', array( $lead_id ) );
|
||
```
|
||
|
||
投递失败后按线性退避重试三次,然后标记为 `failed`。后台列表会显示状态徽章
|
||
(pending / retrying / delivered / failed)和尝试次数——这一点很重要——插件的数据
|
||
保留规则会保留**已投递**的线索,但按正常周期清理未投递的,因为一条没送出去的线索
|
||
只是躺在你数据库里的个人隐私数据。
|
||
|
||
### 服务商的急停开关必须在服务端强制执行
|
||
|
||
管理员可以停用图像服务商,并设置一段代替「生成」按钮显示给访客的文案。把复选框
|
||
变灰只是 UX;真正的强制发生在创建任务接口的开头:
|
||
|
||
```php
|
||
if ( ! (bool) Settings::get( 'fal_provided' ) ) {
|
||
return $this->error_response( 'hre_provider_disabled', $msg, 503 );
|
||
}
|
||
```
|
||
|
||
名单元件那道闸同理。浏览器端的闸是 UX,服务端的闸才是产品。
|
||
|
||
## 只有在真实安装里才会冒出来的五个 bug
|
||
|
||
这是所有「怎么做 AI 插件」的文章都不会写的一段,而 58 个 commit 里大部分都花在这。
|
||
|
||
### 1. 把后台 REST 路由注册在 `is_admin()` 里,会静默 404
|
||
|
||
只在 `is_admin()` 为真时注册后台路由,看起来是对的,实际上完全坏了:
|
||
**REST 请求里 `is_admin() === false`**,所以路由从未被注册,每次调用都返回
|
||
`404 "No route was found matching the URL and request method"`——这读起来就像是
|
||
URL 打错了,完全不像注册 bug。要在插件启动时就注册;真正的访问控制是
|
||
`permission_callback`(权限 + nonce)。
|
||
|
||
### 2. `rest_url()` 结尾没有斜杠
|
||
|
||
最近耗掉我一个下午的就是这个。`rest_url()` 返回的是
|
||
`https://example.com/wp-json/my-plugin/v1/`——结尾的斜杠属于**命名空间**,下一段
|
||
路径必须自己带一个斜杠。不带的话:
|
||
|
||
```js
|
||
const rest = window.hreAdmin.rest; // ".../wp-json/hoelee-ai-photo-remix/v1"
|
||
fetch( rest + 'admin/photos/' + id ) // ❌ ".../v1admin/photos/123"
|
||
fetch( rest + '/admin/photos/' + id ) // ✅
|
||
```
|
||
|
||
`.../v1admin/photos/123` 是一个 404,而且浏览器控制台里没有任何报错,于是 `catch`
|
||
分支触发,界面弹出笼统的「*Something went wrong.*」。它已经悄悄弄坏了**四个**接口
|
||
——照片分页、照片删除、webhook 测试按钮、线索重发。修法是在每个调用点加一个字符;
|
||
诊断却花了长得多的时间,因为这个失败模式和服务器出错完全无法区分。用两条 curl 就能
|
||
证明:正确的拼接返回 `403`(路由存在、缺 nonce),坏的那个返回 `404`。
|
||
|
||
### 3. 一个后台设置表单能抹掉另一个标签页的设置
|
||
|
||
每个后台标签页只提交自己的字段,但保存处理函数会跑完**整个**设置表。一个没被提交
|
||
的复选框,和一个被取消勾选的复选框长得一模一样,所以保存「限制」页会静默地把
|
||
「默认允许分享」写成 `false`,而保存那一页又会把整个名单元件配置清空。修法在
|
||
清洗器里,不在表单里——要区分「这次提交里没有这个键」和「有这个键但是空值」:
|
||
|
||
```php
|
||
// 本页提交了 → 用新值(清空就是清空)
|
||
// 本页没有提交 → 保留当前值
|
||
if ( array_key_exists( $key, $raw ) ) {
|
||
$clean[ $key ] = sanitize( $raw[ $key ] );
|
||
}
|
||
```
|
||
|
||
我为这件事补了一个回归测试(写入配置 → 保存另一个标签页的子集 → 断言原配置还在)。
|
||
这类 bug 只有在你有了两个标签页之后才会存在,所以它才会被发出去。
|
||
|
||
### 4. 二进制接口不能走 JSON 解析的 fetch 助手
|
||
|
||
结果下载是一个 JPEG 流。共用的 `api()` 助手对每个响都做 `res.json()`,碰到图片字节
|
||
就抛异常——而一个吞异常的 `.catch(function(){})` 把错误吃掉了,于是症状是
|
||
*「结果一直不出现」*,控制台里什么都没有。二进制接口需要自己的原始 fetch 助手:
|
||
检查 `res.ok`、只在出错时解析 JSON、成功时返回 `res.blob()`。
|
||
|
||
### 5. 在缩放之前触发的尺寸上限,等于废掉了缩放
|
||
|
||
插件会把上传图缩到工作尺寸(1920×1080 边界)。我把防解压炸弹的限制设得太低——
|
||
1 MB / 1 MP——结果每一张正常的手机照片都在**被缩放之前**就被拒了。访客看到预览刚
|
||
出现就立刻取消选中,被反馈成「缩放功能坏了」。
|
||
|
||
真正的教训是 UX,不是数字:客户端必须在**显示本地预览之前**就拒掉超限文件。
|
||
一闪就没,读起来就是 bug,哪怕底下那句提示其实是对的。现在上限是 15 MB / 50 MP,
|
||
高到正常照片一定能通过并被归一化。
|
||
|
||
## 如果重来一次我会怎么做
|
||
|
||
- **产品依赖的东西,先写失败路径。** 水印那个 bug 之所以存在,是因为我写了成功路径,
|
||
然后把失败路径藏了起来。现在我先把「这条线断了,店主会看到什么」写完,再宣告
|
||
功能完成。
|
||
- **第一天就拿真实站点测 REST 拼接。** 两条 curl(`.../v1/admin/x` → 403 对比
|
||
`.../v1admin/x` → 404)本来能在第一周就抓出四个坏接口,而不是拖到第四周。我已经
|
||
把它写进项目的 `AGENTS.md`,让它不会再犯。
|
||
- **别去猜服务商的 API 形状。** 我在 `fal.ai/api/me`(根本不存在的接口)上浪费了
|
||
时间,之后才发现正确的 key 校验是往队列接口发一个带鉴权的 `POST {}`:`401` 表示
|
||
被拒,其他都说明 key 没问题。先读真实 schema,再写客户端。
|
||
- **前端就保持两个 shortcode。** 我曾经很想把向导拆成五个 shortcode 和五个页面构建器
|
||
组件。保持成「一个应用 + 一个画廊」意味着每次 UI 迭代都是单文件改动,而正是这个
|
||
迭代速度让 22 个版本得以发出去。
|
||
|
||
## 结果
|
||
|
||
一个具备产品形态的 WordPress 插件:**`0.0.22`,共 22 次发布**,10 张自定义数据表、
|
||
异步 fal.ai 队列、服务端密钥管理、带重试 webhook 的动态名单元件、区分分享状态的
|
||
照片归档,以及一个 10 个标签页、不用碰代码就能改完所有配置的后台。
|
||
|
||
这就是演示和产品之间的区别。而我最在意的那个数字是:**58 个 commit 里,大概只有四个
|
||
和 AI 模型有关。** 其余全是那些不体面的工作,却决定了客户能不能在没有我的情况下
|
||
把这东西跑起来:校验、数据保留、权限、失败的可见性,以及一个说真话的后台页面。
|
||
|
||
---
|
||
|
||
## 想给你的生意也做一套?
|
||
|
||
我为马来西亚的中小企业做 WordPress 插件、AI 图像流水线和自托管基础设施——而且是
|
||
做成你真的能跑起来的产品,不是要你天天伺候的演示。如果你想要 AI 产品图、一套线索
|
||
收集管道,或者为你的业务定制插件,欢迎直接找我:
|
||
|
||
- 📱 **WhatsApp:** [+60 12-797 2969](https://wa.me/60127972969)
|
||
- 📧 **邮箱:** [[email protected]](mailto:[email protected]?subject=WordPress%20AI%20plugin%20project)
|
||
- 🌐 **网站:** [hoelee.com](https://hoelee.com)
|
||
````
|
||
|
||
### 🇬🇧 英文版原文 (English Markdown Primary)
|
||
````markdown
|
||
---
|
||
title: "Shipping an AI Photo Editor as a WordPress Plugin: 22 Versions of Hard Lessons"
|
||
description: "From a single HTML file to a shipped WordPress plugin: the fal.ai async queue, a watermark that must never silently fail, optional lead capture, and five bugs that only appeared in production."
|
||
pubDate: 2026-09-18
|
||
category: case-studies
|
||
blueprint: sme-digital-suite
|
||
blueprintLayer: L1-high-conversion-web
|
||
tags: [wordpress, php, fal-ai, docker, ai-image, javascript]
|
||
ogImage: /og/shipping-an-ai-photo-editor-as-a-wordpress-plugin.jpg
|
||
banner: /banners/shipping-an-ai-photo-editor-as-a-wordpress-plugin.jpg
|
||
draft: false
|
||
---
|
||
|
||
A few weeks ago I [wrote about the proof of concept](/posts/ai-furniture-compositing-with-flux-kontext/): one
|
||
`index.html`, no backend, two furniture photos in, a staged room scene out. It
|
||
answered the question it was built to answer — *can you keep the real product and
|
||
only generate the room around it?* — and it left one obvious question open.
|
||
|
||
That PoC ended with the words *"before committing to the full WordPress plugin."*
|
||
This post is about the plugin. It went from version `0.0.1` to `0.0.22` across 58
|
||
commits, and almost none of that work was the AI part.
|
||
|
||
## Why it matters (for a business owner, not a developer)
|
||
|
||
The PoC's limitation was that it lived in a single HTML file with the API key in
|
||
the source. That's fine for a demo you email a client. It is not fine for
|
||
something a furniture shop puts on their own website, where:
|
||
|
||
- **The API key cannot be in the browser.** Anyone can view-source and drain your
|
||
fal.ai credit. It has to live server-side, behind a settings screen an admin
|
||
controls.
|
||
- **Nobody wants to babysit a generation.** The visitor uploads, waits, gets a
|
||
picture. If the process dies halfway, the shop owner should never hear about it.
|
||
- **Photos of customers must not leak.** An anonymous visitor's source photo must
|
||
never end up in the public Media Library, and a result must never be public
|
||
unless *that visitor* opted in to sharing it.
|
||
- **Output needs a watermark.** Otherwise you're running a free AI photo service
|
||
for the entire internet.
|
||
- **The owner needs to capture the lead.** An AI tool that produces a pretty
|
||
picture and no contact details is a toy. Attached to a form + webhook, it's a
|
||
lead pipeline for a furniture business.
|
||
|
||
Every one of those five points is a *product* requirement, and every one of them
|
||
cost more code than the AI call itself.
|
||
|
||
## Architecture: the boring parts that make it work
|
||
|
||
The plugin is a normal WordPress plugin — PHP prefix `hre_`, namespace `HRE`,
|
||
custom tables created with `dbDelta()` on activation, an autoloader, no Composer
|
||
runtime dependency. The interesting decisions are elsewhere.
|
||
|
||
### Generation is asynchronous, always
|
||
|
||
fal.ai jobs take 15–20 seconds. PHP-FPM request timeouts, `max_execution_time`,
|
||
and impatient visitors make synchronous generation a losing bet. So the flow is a
|
||
queue-and-poll:
|
||
|
||
```
|
||
visitor uploads → POST /uploads → normalize → start vision analysis
|
||
visitor picks → GET /prompts/{cat} → per-style prompts
|
||
visitor confirms → POST /jobs → fal queue submit (returns uuid)
|
||
browser polls → GET /jobs/{uuid} → status: queued | processing | done
|
||
```
|
||
|
||
The visitor never waits on a provider. The job row carries the fal request id, and
|
||
a poll either finds a finished result or shows genuine progress. The front end is
|
||
a small state machine over a session cookie, so a mid-wizard refresh restores
|
||
where the visitor was.
|
||
|
||
### Ownership is the session cookie, not an ID in the URL
|
||
|
||
Anonymous visitors have no accounts, which makes authorization easy to get wrong.
|
||
The rule I settled on: **every read resolves through the caller's own session
|
||
hash**, never through an ID accepted from the client.
|
||
|
||
- `GET /preview` streams the caller's *own* normalized upload. There is no path or
|
||
URL parameter at all — a stranger requesting it gets a 404 because their session
|
||
has no file. This also keeps private storage paths out of every JSON payload.
|
||
- `GET /jobs/{uuid}` looks the job up *by session hash + uuid*. Guessing a UUID
|
||
from another browser returns nothing.
|
||
|
||
That's one decision that removes an entire class of "I changed the id in the URL
|
||
and saw someone else's photo" bugs.
|
||
|
||
### The watermark is a hard requirement, so a fallback must never be silent
|
||
|
||
This is the bug that taught me the most. The watermark step does a GD
|
||
`imagecopyresampled` composite. If it ever fails, the tempting "resilient" move is:
|
||
|
||
```php
|
||
// DON'T do this
|
||
if ( ! $watermarked ) {
|
||
rename( $stage, $final ); // ship the un-watermarked file
|
||
}
|
||
```
|
||
|
||
I did exactly that. It's silent, it has no log line, and it means the plugin
|
||
happily serves un-watermarked results while the admin screen says "watermark: on."
|
||
The owner found out weeks later by noticing a photo without a watermark.
|
||
|
||
The fix was three parts:
|
||
|
||
1. **Log the root cause, not the nearest symptom.** `apply()` returned
|
||
`hre_no_watermark_source` — a downstream error. The real cause was that the
|
||
watermark source resolution chain (`site_logo` → `get_theme_mod('custom_logo')`)
|
||
had no logo to resolve. I added a `block_reason()` diagnostic that re-walks the
|
||
chain and returns a *specific* message per failure branch.
|
||
2. **Surface it in the admin.** A persistent `notice-warning` says the watermark
|
||
is enabled but won't be applied, plus the concrete reason. No log-reading
|
||
required.
|
||
3. **Make the failure visible to me in testing.** A standalone probe composites a
|
||
known watermark onto a known base and samples a pixel inside the expected
|
||
watermark rectangle — proving the transform path itself works, which separates
|
||
"the feature is broken" from "the feature is unconfigured."
|
||
|
||
**Rule I now follow:** when a best-effort branch masks a non-negotiable transform,
|
||
it must log the concrete reason *and* warn in the admin UI. A silent fallback that
|
||
degrades a required feature is not resilience — it's a bug with good manners.
|
||
|
||
### Lead capture: off by default, asynchronous when on
|
||
|
||
Lead capture is a master toggle. Off, the plugin collects nothing and the wizard
|
||
behaves exactly as before. On, the visitor's configured fields are required before
|
||
generation, stored in a custom table, and forwarded to a webhook.
|
||
|
||
Two decisions worth copying:
|
||
|
||
- **The field list is admin-defined and fully dynamic** — `{key, label, type,
|
||
required, placeholder, options[]}` — so the front form renders itself from
|
||
config. The defaults (name, phone, email, message, consent) are just a starting
|
||
point the owner can replace entirely.
|
||
- **Webhook delivery is scheduled, never inline.** The visitor must not wait on
|
||
someone else's endpoint:
|
||
|
||
```php
|
||
wp_schedule_single_event( time() + 5, 'hre_lead_webhook', array( $lead_id ) );
|
||
```
|
||
|
||
Delivery retries three times with linear backoff, then marks the record `failed`.
|
||
The admin list shows a status badge (pending / retrying / delivered / failed) plus
|
||
the attempt count, and — this matters — the plugin's data retention rule keeps
|
||
*delivered* leads but purges undelivered ones on the normal schedule, because an
|
||
undelivered lead is just PII sitting in your database.
|
||
|
||
### The provider kill switch has to be enforced server-side
|
||
|
||
The admin can disable the image provider and set a message that visitors see
|
||
instead of the generate button. Greying out the checkbox is UX; the enforcement is
|
||
a check at the top of the job-creation endpoint:
|
||
|
||
```php
|
||
if ( ! (bool) Settings::get( 'fal_provided' ) ) {
|
||
return $this->error_response( 'hre_provider_disabled', $msg, 503 );
|
||
}
|
||
```
|
||
|
||
Same for the lead gate. The browser gate is UX. The server gate is the product.
|
||
|
||
## The five bugs that only showed up in the real install
|
||
|
||
This is the part no article about "building an AI plugin" ever includes, and it's
|
||
where most of the 58 commits went.
|
||
|
||
### 1. Admin REST routes registered inside `is_admin()` silently 404
|
||
|
||
Registering admin routes only when `is_admin()` is true looks correct and is
|
||
completely broken: **REST requests report `is_admin() === false`**, so the routes
|
||
are never registered and every call returns `404 "No route was found matching the
|
||
URL and request method"` — which reads exactly like a URL typo, not a registration
|
||
bug. Register at plugin boot; the `permission_callback` (capability + nonce) is
|
||
what gates access.
|
||
|
||
### 2. `rest_url()` has no trailing slash
|
||
|
||
The one that cost me the most recent afternoon. `rest_url()` returns
|
||
`https://example.com/wp-json/my-plugin/v1/` — the trailing slash is on the
|
||
*namespace*, and the next path segment must start with its own slash. Concatenating
|
||
without one:
|
||
|
||
```js
|
||
const rest = window.hreAdmin.rest; // ".../wp-json/hoelee-ai-photo-remix/v1"
|
||
fetch( rest + 'admin/photos/' + id ) // ❌ ".../v1admin/photos/123"
|
||
fetch( rest + '/admin/photos/' + id ) // ✅
|
||
```
|
||
|
||
`.../v1admin/photos/123` is a 404 with no browser console error, so the
|
||
`catch` block fires and the UI shows the generic *"Something went wrong."* It had
|
||
quietly broken **four** endpoints — photo pagination, photo delete, the webhook
|
||
test button, and lead resend. The fix is one character per call site; the
|
||
diagnosis took far longer, because the failure mode is indistinguishable from a
|
||
server error. Prove it with two curls: the correct join returns `403` (route
|
||
exists, nonce missing), the broken one returns `404`.
|
||
|
||
### 3. A WordPress admin settings form can wipe a different tab's settings
|
||
|
||
Each admin tab posts only its own fields, but the save handler runs the *whole*
|
||
settings map. A checkbox that isn't submitted looks identical to a checkbox that
|
||
was unchecked, so saving the "limits" tab silently wrote `false` over the
|
||
"share by default" option, and saving that one cleared the entire lead-capture
|
||
configuration. The fix belongs in the sanitizer, not the forms — distinguish
|
||
"absent from this submission" from "present and empty":
|
||
|
||
```php
|
||
// present in this tab → use the new value (a cleared field clears)
|
||
// absent from this tab → keep the current value
|
||
if ( array_key_exists( $key, $raw ) ) {
|
||
$clean[ $key ] = sanitize( $raw[ $key ] );
|
||
}
|
||
```
|
||
|
||
I added a regression test for exactly this (seed config → save a different tab's
|
||
subset → assert the seed survived). It's the kind of bug that only exists once you
|
||
have two tabs, which is why it shipped.
|
||
|
||
### 4. A binary endpoint must not go through a JSON fetch helper
|
||
|
||
The result download is a JPEG stream. The shared `api()` helper did `res.json()`
|
||
on every response, which threw on image bytes — and a swallowing
|
||
`.catch(function(){})` ate the error, so the symptom was *"the result never shows
|
||
up"* with nothing in the console. Blob endpoints need their own raw fetch helper
|
||
that checks `res.ok`, parses JSON only on error, and returns `res.blob()` on
|
||
success.
|
||
|
||
### 5. A size limit that fires before the resize defeats the resize
|
||
|
||
The plugin downscales uploads to a working size (1920×1080 bounds). I had set the
|
||
decompression-bomb guard too low — 1 MB / 1 MP — which meant every legitimate
|
||
phone photo was rejected *before* it could be resized. Visitors saw the preview
|
||
appear and instantly de-select, reported as "the resize feature is broken."
|
||
|
||
The real lesson is UX, not numbers: the client must reject an over-limit file
|
||
*before* showing the local preview. Flash-then-disappear reads as a bug even when
|
||
the message underneath is correct. The caps now sit at 15 MB / 50 MP, high enough
|
||
that normal photos always pass and get normalized.
|
||
|
||
## What I'd do differently
|
||
|
||
- **Write the failure path first for anything the product depends on.** The
|
||
watermark bug existed because I wrote the happy path and then hid the unhappy
|
||
one. Now I write the "what does the owner see when this breaks" branch before
|
||
the feature is finished.
|
||
- **Test REST joins against the live site on day one.** A two-curl check
|
||
(`.../v1/admin/x` → 403 vs `.../v1admin/x` → 404) would have caught four broken
|
||
endpoints in week one instead of week four. I've added it to the project's
|
||
`AGENTS.md` so it can't recur.
|
||
- **Don't guess at a provider's API surface.** I lost time on `fal.ai/api/me`
|
||
(which doesn't exist) before discovering the right key check is an authenticated
|
||
`POST {}` to the queue endpoint: `401` means rejected, anything else means the
|
||
key is fine. Read the real schema, then write the client.
|
||
- **Keep the front end to two shortcodes.** I was tempted to split the wizard into
|
||
five shortcodes and five page-builder widgets. Keeping it as one app + one
|
||
gallery shortcode meant every UI iteration was a single-file change, and that
|
||
iteration speed is the reason 22 versions shipped.
|
||
|
||
## The result
|
||
|
||
A production-shaped WordPress plugin: **`0.0.22` across 22 releases**, with 10
|
||
custom database tables, an async fal.ai queue, server-side key handling, dynamic
|
||
lead capture with a retrying webhook, a role-aware photo archive, and everything
|
||
configurable from a 10-tab admin screen without touching code.
|
||
|
||
It is the difference between a demo and a product, and — the number I actually
|
||
care about — **58 commits, of which roughly four were about the AI model.** The
|
||
rest was the unglamorous work that decides whether a client can run the thing
|
||
without me: validation, retention, permissions, failure visibility, and an admin
|
||
screen that tells the truth.
|
||
|
||
---
|
||
|
||
## Want this for your business?
|
||
|
||
I build WordPress plugins, AI image pipelines, and self-hosted infrastructure for
|
||
Malaysian SMEs — and I ship them as products you can actually run, not demos you
|
||
have to babysit. If you want AI product photography, a lead-capture pipeline, or
|
||
a custom plugin for your business, I'd love to talk:
|
||
|
||
- 📱 **WhatsApp:** [+60 12-797 2969](https://wa.me/60127972969)
|
||
- 📧 **Email:** [[email protected]](mailto:[email protected]?subject=WordPress%20AI%20plugin%20project)
|
||
- 🌐 **Website:** [hoelee.com](https://hoelee.com)
|
||
````
|
||
|
||
---
|
||
|
||
## 文章 10 / 10:在多台机器之间同步一个会自我学习的 AI Agent
|
||
- **Slug**: `syncing-a-self-improving-ai-agent-across-machines`
|
||
- **英文标题**: Syncing a Self-Improving AI Agent Across Machines
|
||
- **分类**: `case-studies` | **发布日期**: 2026-02-18
|
||
- **线上地址**: https://blog.hoelee.com/posts/syncing-a-self-improving-ai-agent-across-machines/ (EN) | https://blog.hoelee.com/posts/zh/syncing-a-self-improving-ai-agent-across-machines/ (ZH)
|
||
- **本篇审核状态**: ⏳ 待审核 (Pending)
|
||
|
||
### ✍️ 顾问审阅意见区 (Review Feedback)
|
||
```text
|
||
【审阅结论】:[ ] 通过 [ ] 需微调 [ ] 需重构
|
||
【事实与数字核对】:
|
||
【人设与用词卫生】:
|
||
【CRO与转化建议】:
|
||
```
|
||
|
||
### 🇨🇳 中文版原文 (Chinese Markdown Twin)
|
||
````markdown
|
||
---
|
||
title: "在多台机器之间同步一个会自我学习的 AI Agent"
|
||
description: "如何用基于 git 的 profile distribution 在两台电脑之间同步 Hermes agent 的技能、配置和定时任务——以及为什么我选择手动同步而不是用 cron。"
|
||
pubDate: 2026-02-18
|
||
updatedDate: 2026-09-11
|
||
category: case-studies
|
||
blueprint: ai-agent-automation
|
||
blueprintLayer: L2-llm-gateway-agents
|
||
tags: [hermes, git, gitea, ai-agents, devops, sync]
|
||
ogImage: /og/zh-syncing-a-self-improving-ai-agent-across-machines.jpg
|
||
banner: /banners/syncing-a-self-improving-ai-agent-across-machines.jpg
|
||
---
|
||
|
||
我的 agent 会学习。每当我带它走一遍不平凡的工作流程——如何发布到 Gitea、如何排查一个时好时坏的 Docker 容器、如何写一条 Shopee 商品列表——它就会把过程存成一项 *skill*:一个下次遇到同类任务时自动加载的可复用流程。几个月下来,它累积了 172 项技能,横跨二十个分类。它们就是我的第二大脑。
|
||
|
||
问题在于:这个大脑只存在于一台机器上。当我换到另一台电脑工作时,agent 就变"笨"了——它不知道我在第一台机器上教过它什么。
|
||
|
||
这篇文章讲的是我如何让 agent 的知识跟着我在机器之间流动,为什么那个显而易见的做法会悄悄毁掉工作成果,以及最后发现最关键的那个决定。
|
||
|
||
## 为什么这很重要
|
||
|
||
如果你在运行任何会自我学习的 agent——Hermes、Claude Code、Codex、Cursor——你都会遇到一模一样的问题。agent 在本地累积知识,但这些知识不会跟着你走。你要么在每台机器上重新教它一遍(毫无意义),要么让两份副本逐渐漂移、直到互相矛盾(更糟)。
|
||
|
||
正确地解决它需要三件事,也正是任何工程师在同步*任意*状态时都关心的三件事:
|
||
|
||
- **一个共享的真相来源**——一份两台机器都能拉取的权威副本。
|
||
- **不静默丢数据**——同步绝不能覆盖你在另一台机器上做过的工作。
|
||
- **一个决策点**——当两台机器改动了同一处内容时,由*你*来做选择,而不是让工具替你决定。
|
||
|
||
把这三件事做对,你的 agent 在两台机器上就是同一个人。做错了,你就得花一个周末去重建一个被错误的 `--force` 抹掉的技能。
|
||
|
||
## 三种官方机制
|
||
|
||
Hermes 提供了三种迁移 agent 的方式,它们回答的是不同的问题:
|
||
|
||
| 需求 | 机制 | 命令 |
|
||
|---|---|---|
|
||
| 只要技能 | Skills Hub "tap"(一个 `SKILL.md` 文件夹的 git 仓库) | `hermes skills tap add` + `install` |
|
||
| 整个 agent、带版本、可拉取更新 | **Profile distribution**(git 仓库 + `distribution.yaml`) | `hermes profile install` / `update` |
|
||
| 一次性迁移 / 备份 | 导出文件(`.tar.gz`) | `hermes profile export` / `import` |
|
||
|
||
对于"同一 agent 在两台机器上",**profile distribution** 才是持久的答案。它把整个 agent——SOUL、配置、技能、定时任务——打包成一个 git 仓库,另一台机器用一条命令就能拉取更新。
|
||
|
||
我所有东西本来就用 Gitea(git.hoelee.com),所以在那里放一个 distribution 仓库是顺理成章的。没有新工具、没有新账号,也符合我每个项目都遵循的"Gitea 优先"惯例。
|
||
|
||
## 我差点踩进去的坑
|
||
|
||
distribution 安装器有一个安全特性,*听起来*像限制,却恰恰是救命的东西:**它拒绝安装到 `default` profile 里。** 你必须给它一个命名 profile。
|
||
|
||
这不是麻烦。第二台电脑本来就有自己的 agent 和项目相关的技能。如果我把它*覆盖*安装上去——或者用了会覆盖现有 profile 的 `--force`——我就会删掉那台机器本地的成果。`default` 拒绝机制就是那道护栏,逼着你在现有 agent *旁边*安装,然后再合并。
|
||
|
||
而这正是整个练习真正的教训:**合并才是产品本身。** 同步不是"复制文件",而是调和两个都以为自己是真相来源的 agent。
|
||
|
||
## 那个差点让我翻车的目录事实
|
||
|
||
这里是微妙的部分,也是那种"看起来没事、直到出事"的坑。
|
||
|
||
distribution 仓库里放的是技能树的**副本**——它不是*活跃目录*。活跃技能在 `~/AppData/Local/hermes/skills/`(agent 真正写入的地方);仓库副本只是我推送的一份快照。它们是两棵会漂移的、互相独立的树。
|
||
|
||
所以一次同步实际上涉及**三方**,而不是两方:
|
||
|
||
```
|
||
活跃技能目录 ←→ 仓库副本(D:\dev\hoelee-agent-dist\skills) ←→ Gitea 远端
|
||
```
|
||
|
||
我在上次推送之后新建的一个技能,*只*存在于活跃目录里。如果我假设仓库副本是权威、并"从它开始同步",就会静默删掉那个技能。所以每次同步前我做的第一件事,就是比对两棵树:
|
||
|
||
```bash
|
||
diff -rq ~/AppData/Local/hermes/skills D:/dev/hoelee-agent-dist/skills
|
||
```
|
||
|
||
漂移是*正常的*,不是错误。整套纪律在于搞清楚三方里谁领先,然后有意识地调和。
|
||
|
||
## 为什么我手动同步,而不是用 cron
|
||
|
||
这是最关键的决定,而它归结为冲突策略。我想要双向同步——两台机器都会编辑技能——而当两边编辑了*同一个*技能时,我想**两边都保留、由我自己来挑**,而不是让工具静默丢掉其中一个。
|
||
|
||
这种策略本质上是交互式的。一个自动拉取的 cron 要么覆盖成果,要么在我没盯着的时候触发。所以我让触发变成手动:我说一句*"同步技能"*,agent 就去执行,并在**任何冲突时停下来问我**。这不是偷懒——而是合并的决定权在我手里,自动化做不了这个决定。
|
||
|
||
我记录下来的(也是现在真正在跑的)流程是:
|
||
|
||
```bash
|
||
# 1. 把远端拉进仓库副本,只快进——绝不 force
|
||
cd D:\dev\hoelee-agent-dist && git pull --ff-only origin main
|
||
|
||
# 2. 调和活跃目录 ↔ 仓库副本
|
||
diff -rq ~/AppData/Local/hermes/skills D:/dev/hoelee-agent-dist/skills
|
||
|
||
# 3. 只暂存真正的技能内容(绝不包含 curator 垃圾)
|
||
# 4. 提交 + 推送,然后验证远端确实有了
|
||
git ls-remote origin main # 必须等于本地 HEAD
|
||
```
|
||
|
||
如果拉取被拒绝,或者 diff 显示同一个技能在两边都被改过,我就停下来做决定。绝不 `--force`,绝不 reset。
|
||
|
||
## 那坨悄悄撑大仓库的垃圾
|
||
|
||
第一次打包时的一个具体数字:我的技能目录有 **57 MB**,但真正的技能内容只有 **~8 MB**。剩下的是 agent 的 curator 不断写入的运行时状态——一个 40 MB 的 hub 索引缓存、curator 备份、使用统计、一份账本。
|
||
|
||
这些都不该进共享仓库。它们每天都在变、是机器本地的、而且会让每次同步都变成一团糟。一个 `.gitignore` 就能把它们剥掉:
|
||
|
||
```gitignore
|
||
# skill 运行时垃圾——绝不入库
|
||
skills/.hub/
|
||
skills/.curator_backups/
|
||
skills/.curator_ledger.jsonl
|
||
skills/.usage.json
|
||
skills/.bundled_manifest
|
||
```
|
||
|
||
当你打包一个会自我学习的 agent 时,会发现它不只是文件——是文件*加上*一层必须挡在外面的簿记。跟给 `node_modules` 写 `.gitignore` 是同一个道理,只不过对象是你自己的记忆。
|
||
|
||
## 我会做得不一样的地方
|
||
|
||
- **先想清楚触发方式,再选机制。** 我花了不少功夫纠结 distribution 还是 export,却还没回答"我要手动还是自动"——而这个答案反过来会*改变*机制。如果我一开始就知道要的是手动的、冲突感知的同步,第一天就会照这个方式去设计脚本。
|
||
- **把"副本 vs 活跃目录"的区分当作一条有名字的不变量。** 我是靠 diff 才发现的;它本该从第一次 `cp -r` 起就写进我的笔记里。
|
||
- **提前决定每台机器的 `user_id`。** 技能走 git 同步,但情节记忆(mem0)是另一个后端——两台机器要么共享一个记忆桶、要么各留各的,这是一个应该早点明确的单行配置选择。
|
||
|
||
## 结果
|
||
|
||
现在我有一个 git 仓库——`git.hoelee.com/hoelee/hoelee-agent-dist`——装着 172 项技能、我的配置、SOUL 和定时任务。另一台机器把它装进一个命名 profile,再把自己本地的技能合并进去,我们靠一个"每次冲突都问我"的手动触发器保持同步。第一次真正的同步推送了一个只存在于活跃机器上的技能,验证它落地了(两边都是 `edbf7ac`),并且没有动任何现有的技能。
|
||
|
||
给任何想同步 agent 的人的一句实在话:*文件*是简单的——git 干了大部分重活。难的是那些护栏:那个你绝不能跑的 `--force`,那个你绝不能误当成真相来源的副本,还有那个你绝不能让工具替你静默解决的冲突。
|
||
|
||
---
|
||
|
||
## 想为自己的 agent 搭建这套东西吗?
|
||
|
||
我为企业和个人搭建自托管的 AI 基础设施——agent、bot、自动化。如果你正在跨机器运行 agent(或想开始),或者需要自托管工具方面的帮助,我很乐意聊聊:
|
||
|
||
- 📱 **WhatsApp:** [+60 12-797 2969](https://wa.me/60127972969)
|
||
- 📧 **Email:** [[email protected]](mailto:[email protected]?subject=Agent%20sync%20setup)
|
||
- 🌐 **Website:** [hoelee.com](https://hoelee.com)
|
||
````
|
||
|
||
### 🇬🇧 英文版原文 (English Markdown Primary)
|
||
````markdown
|
||
---
|
||
title: "Syncing a Self-Improving AI Agent Across Machines"
|
||
description: "How I sync my Hermes agent's skills, config, and cron jobs between two PCs with a git-backed profile distribution — and why I sync manually instead of on a cron."
|
||
pubDate: 2026-02-18
|
||
updatedDate: 2026-09-11
|
||
category: case-studies
|
||
blueprint: ai-agent-automation
|
||
blueprintLayer: L2-llm-gateway-agents
|
||
tags: [hermes, git, gitea, ai-agents, devops, sync]
|
||
ogImage: /og/syncing-a-self-improving-ai-agent-across-machines.jpg
|
||
banner: /banners/syncing-a-self-improving-ai-agent-across-machines.jpg
|
||
---
|
||
|
||
My agent learns. Every time I walk it through a non-trivial workflow — how to
|
||
publish to Gitea, how to troubleshoot a flaky Docker container, how to write a
|
||
Shopee listing — it saves that as a *skill*: a reusable procedure it loads the
|
||
next time the task comes up. Over a few months that grew to 172 skills across
|
||
twenty categories. They're my second brain.
|
||
|
||
The problem: that brain lives on one machine. When I sit down at my other PC,
|
||
the agent is *dumber* — it doesn't know what I taught it on the first one.
|
||
|
||
This is the story of how I made the agent's knowledge follow me between
|
||
machines, why the obvious approach would have silently destroyed work, and the
|
||
one decision that turned out to matter most.
|
||
|
||
## Why this matters
|
||
|
||
If you run any self-improving agent — Hermes, Claude Code, Codex, Cursor — you
|
||
have this exact problem. The agent accumulates knowledge locally, and none of it
|
||
moves. You either re-teach it on every machine (pointless) or you let the two
|
||
copies drift until they contradict each other (worse).
|
||
|
||
Solving it properly means three things, and they're the same three things any
|
||
engineer cares about when syncing *any* state:
|
||
|
||
- **A shared source of truth** — one canonical copy both machines pull from.
|
||
- **No silent data loss** — a sync that can't clobber work you did on the other
|
||
machine.
|
||
- **A decision point** — when two machines changed the same thing, *you* pick,
|
||
not the tool.
|
||
|
||
Get those three right and your agent is genuinely the same person on both
|
||
machines. Get them wrong and you spend a weekend reconstructing a skill a bad
|
||
`--force` wiped out.
|
||
|
||
## The three official mechanisms
|
||
|
||
Hermes ships three ways to move an agent, and they answer different questions:
|
||
|
||
| Need | Mechanism | Command |
|
||
|---|---|---|
|
||
| Just skills | Skills Hub "tap" (a git repo of `SKILL.md` folders) | `hermes skills tap add` + `install` |
|
||
| Whole agent, versioned, pullable | **Profile distribution** (git repo + `distribution.yaml`) | `hermes profile install` / `update` |
|
||
| One-off move / backup | Export file (`.tar.gz`) | `hermes profile export` / `import` |
|
||
|
||
For "same agent on two machines," the **profile distribution** is the durable
|
||
answer. It packages the whole agent — SOUL, config, skills, cron — as a git
|
||
repo, and the other machine pulls updates with one command.
|
||
|
||
I already run Gitea (git.hoelee.com) for everything else, so a distribution
|
||
repo there was the natural fit. No new tooling, no new accounts, and it plays
|
||
by the same Gitea-first convention I use for every project.
|
||
|
||
## The trap I almost walked into
|
||
|
||
The distribution installer has a safety property that *sounds* like a
|
||
limitation but is exactly what saves you: **it refuses to install into the
|
||
`default` profile.** You must give it a named profile.
|
||
|
||
That's not an annoyance. The second PC already had its own agent with
|
||
project-specific skills. If I'd installed the distribution *over* it — or used
|
||
`--force`, which overwrites an existing profile — I'd have deleted that
|
||
machine's local work. The `default`-refusal is the guardrail that forces you to
|
||
install *alongside* the existing agent, then merge.
|
||
|
||
Which is the real lesson of this whole exercise: **the merge is the product.**
|
||
The sync isn't "copy files." It's reconciling two agents that both think
|
||
they're the source of truth.
|
||
|
||
## The layout fact that would have clobbered me
|
||
|
||
Here's the subtle part, and it's the kind of thing that looks fine until it
|
||
isn't.
|
||
|
||
The distribution repo holds a **copy** of the skills tree — it is *not* the
|
||
live directory. The live skills live in `~/AppData/Local/hermes/skills/` (where
|
||
the agent actually writes); the repo copy is a snapshot I push. They are two
|
||
separate trees that drift.
|
||
|
||
So a sync actually has **three parties**, not two:
|
||
|
||
```
|
||
live skills dir ←→ repo copy (D:\dev\hoelee-agent-dist\skills) ←→ Gitea remote
|
||
```
|
||
|
||
A skill I create after the last push exists *only* in the live dir. If I'd
|
||
assumed the repo copy was authoritative and "synced" from it, I'd have
|
||
silently deleted that skill. The first thing I do before any sync is diff the
|
||
two trees:
|
||
|
||
```bash
|
||
diff -rq ~/AppData/Local/hermes/skills D:/dev/hoelee-agent-dist/skills
|
||
```
|
||
|
||
Divergence is *normal*, not an error. The whole discipline is knowing which of
|
||
the three parties is ahead and reconciling deliberately.
|
||
|
||
## Why I sync manually, not on a cron
|
||
|
||
This was the decision that mattered most, and it came down to the conflict
|
||
policy. I want two-way sync — both machines edit skills — and when both edit
|
||
the *same* skill, I want to **keep both and pick myself**, not have a tool
|
||
silently drop one.
|
||
|
||
That policy is inherently interactive. A cron job that auto-pulls either
|
||
overwrites work or fires when I'm not looking. So I made the trigger manual: I
|
||
say *"sync skills"*, the agent runs it, and it **stops and asks me on any
|
||
conflict**. It's not laziness — it's that the merge decision is mine to make,
|
||
and automation can't make it for me.
|
||
|
||
The flow I documented (and now run) is:
|
||
|
||
```bash
|
||
# 1. Pull remote into the repo copy, fast-forward only — never force
|
||
cd D:\dev\hoelee-agent-dist && git pull --ff-only origin main
|
||
|
||
# 2. Reconcile live dir ↔ repo copy
|
||
diff -rq ~/AppData/Local/hermes/skills D:/dev/hoelee-agent-dist/skills
|
||
|
||
# 3. Stage only real skill content (never the curator junk)
|
||
# 4. Commit + push, then verify the remote actually has it
|
||
git ls-remote origin main # must match local HEAD
|
||
```
|
||
|
||
If the pull refuses, or a diff shows the same skill changed on both sides, I
|
||
stop and decide. Never `--force`, never a reset.
|
||
|
||
## The junk that was silently bloating the repo
|
||
|
||
One concrete number from the first packaging: my skills directory was **57 MB**,
|
||
but only **~8 MB** was actual skill content. The rest was runtime state the
|
||
agent's curator writes constantly — a 40 MB hub index cache, curator backups,
|
||
usage tracking, a ledger.
|
||
|
||
None of that belongs in a shared repo. It changes daily, it's machine-local,
|
||
and it would have made every sync a noisy mess. A `.gitignore` strips it:
|
||
|
||
```gitignore
|
||
# skill runtime junk — never ship
|
||
skills/.hub/
|
||
skills/.curator_backups/
|
||
skills/.curator_ledger.jsonl
|
||
skills/.usage.json
|
||
skills/.bundled_manifest
|
||
```
|
||
|
||
The moment you package a self-improving agent, you discover it's not just
|
||
files — it's files *plus* a layer of bookkeeping you have to keep out. Same
|
||
lesson as a `.gitignore` for `node_modules`, but for your own memory.
|
||
|
||
## What I'd do differently
|
||
|
||
- **Think about the trigger before the mechanism.** I spent effort deciding
|
||
distribution-vs-export before I'd answered "do I want this manual or
|
||
automated?" — and the answer to that question *changed* the mechanism. If I'd
|
||
known I wanted manual, conflict-aware sync from the start, I'd have designed
|
||
the script that way on day one.
|
||
- **Treat the copy-vs-live distinction as a named invariant.** I discovered it
|
||
by diffing; it should have been a line in my notes from the first `cp -r`.
|
||
- **Decide per-machine `user_id` up front** for memory. Skills sync via git,
|
||
but episodic memory (mem0) is a separate backend — two machines either share
|
||
one memory bucket or keep separate ones, and that's a one-line config choice
|
||
I should have made explicit earlier.
|
||
|
||
## The result
|
||
|
||
I now have one git repo — `git.hoelee.com/hoelee/hoelee-agent-dist` — holding
|
||
172 skills, my config, SOUL, and cron jobs. The other machine installs it into
|
||
a named profile, merges its own skills in, and we stay in sync with a manual
|
||
trigger that asks me on every conflict. The first real sync pushed a
|
||
skill that existed only on the live machine, verified it landed (`edbf7ac` on
|
||
both ends), and left every existing skill untouched.
|
||
|
||
The honest takeaway for anyone syncing an agent: the *files* are easy — git
|
||
does the heavy lifting. The hard parts are the guardrails: the `--force` you
|
||
must never run, the copy you must never mistake for the source of truth, and
|
||
the conflict you must never let a tool resolve silently.
|
||
|
||
---
|
||
|
||
## Want this for your own agent setup?
|
||
|
||
I build self-hosted AI infrastructure — agents, bots, and automation — for
|
||
businesses and individuals. If you're running an agent across machines (or want
|
||
to start), or need a hand with self-hosted tooling, I'd love to talk:
|
||
|
||
- 📱 **WhatsApp:** [+60 12-797 2969](https://wa.me/60127972969)
|
||
- 📧 **Email:** [[email protected]](mailto:[email protected]?subject=Agent%20sync%20setup)
|
||
- 🌐 **Website:** [hoelee.com](https://hoelee.com)
|
||
````
|
||
|
||
---
|
||
|