Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

feat(plugins): 需求箱页面多一块「提交同步」,一眼看见哪些提交没发版、现网跟没跟上

Adelied503fd703731
diff --git a/plugins/requirements-box/README.md b/plugins/requirements-box/README.md
index 06586d27..b269e3cf 100644
--- a/plugins/requirements-box/README.md
+++ b/plugins/requirements-box/README.md
@@ -21,7 +21,7 @@ every <period> the agent wakes, reads the list, marks each item doing, and works
| Piece | What it is |
| --- | --- |
| `kit/requirements.mjs` | The whole service: a JSON store with atomic writes, the keyed API (list/create/read/patch, the patrol cadence, and the do-it-now trigger), and it serves the page. Node standard library only — no build step, no dependency tree. |
-| `kit/requirements.html` | The page: file a request, edit or withdraw one, select several and act in bulk, schedule an item, pause the patrol or change its cadence, and a "do it now" button. |
+| `kit/requirements.html` | The page: file a request, edit or withdraw one, select several and act in bulk, schedule an item, pause the patrol or change its cadence, see which commits are not released or not on the live server yet, and a "do it now" button. |
| `kit/serve.mjs` | A standalone server for the box alone, so it can run on its own port without touching anything else already on the machine. |
| `kit/patrol.md` | The protocol the scheduled round follows: take work, mark it doing before touching it, triage, gate, ship, mail, archive — and the red lines. |
| `kit/install.mjs` | Lays the files down, generates the key, writes `box.config.json`, writes the schedule, and prints the two commands left to run. |
@@ -34,6 +34,12 @@ every <period> the agent wakes, reads the list, marks each item doing, and works
and the whole state is a file you can read.
- **The schedule is a file, not a black box.** The round is a `.toml` the platform re-reads; the cadence, the
on/off switch and the "do it now" button all write that one file.
+- **You can see what is not out yet.** The page carries a "commit sync" card: the commits after the last
+ release tag, what the live server is actually running (asked of its own `/api/version`, not read off disk),
+ whether an update is installed but not restarted yet, and the released commits the running server has not
+ picked up. All four come from `box.config.json` (`repoDir` / `serverUrl` / `serverTokenFile` / `installDir`),
+ which the installer works out for you; anything it cannot work out is reported as "not configured" rather
+ than guessed. The token file stays in this process and never reaches the browser.
- **Doing it now is one click.** Waiting for the next tick is the common complaint, so the page can start a
session immediately, and can do it for just the items the user selected.
diff --git a/plugins/requirements-box/plugin.json b/plugins/requirements-box/plugin.json
index 764c3a78..8f917b8c 100644
--- a/plugins/requirements-box/plugin.json
+++ b/plugins/requirements-box/plugin.json
@@ -3,7 +3,7 @@
"description_zh": "立起一个需求箱:一页受口令保护的表单让用户提需求,一个定时任务按节奏叫 Agent 来做,每轮一封邮件汇报。服务是一个零依赖的 Node 文件(JSON 存储、带口令的 GET/POST/PATCH 接口、它自己那一页、按条目排期、批量勾选,以及一个立刻开会话开工的按钮),巡台协议是一份 Markdown,安装脚本把两者摆好并登记定时任务。",
"short_description": "A keyed request page plus a scheduled patrol that works through it.",
"short_description_zh": "一页收需求的表单 + 定时巡台去做 + 每轮邮件汇报。",
- "version": "2026.10.07.1",
+ "version": "2026.10.15.1",
"category": "office-productivity",
"preinstall": false
}
diff --git a/plugins/requirements-box/skills/requirements-box/SKILL.md b/plugins/requirements-box/skills/requirements-box/SKILL.md
index 4b95f77c..66338159 100644
--- a/plugins/requirements-box/skills/requirements-box/SKILL.md
+++ b/plugins/requirements-box/skills/requirements-box/SKILL.md
@@ -57,10 +57,28 @@ install 会:把服务拷到 `--dir`、生成口令(`data/key.txt`,0600)
| GET / PATCH | `/api/requirements/<id>` | 读一条、改(`title`/`detail`/`priority`/`not_before`/`status`/`result`/`archive`) |
| GET / PATCH | `/api/requirements/patrol` | 看/改巡台节奏(`period`、`daily_at`、`enabled`) |
| GET / POST | `/api/requirements/run` | 看上次手动触发;POST 立刻开一个会话开工(60 秒冷却) |
+| GET | `/api/requirements/sync` | 提交同步:最后一个发布标签之后的提交、现网在跑什么、现网还差哪些提交(30 秒缓存,`?fresh=1` 跳过) |
状态:`new` / `doing` / `done` / `blocked` / `rejected` / `withdrawn`;归档是 `archive: true`,
归档之后接口不再让改。
+### 页面上「提交同步」那块
+
+它写三件**看不见就容易忘**的事(用户 2026-10-15 的口径):**未发版**的提交、**现网没跟上**的提交
+(已经发出去、而正在跑的那个服务还没换上的)、以及**装了没重启**(磁盘上的版本比正在跑的进程新)。
+只看会进构建的提交 —— 发布正文、记账这类只动 markdown 的不算「没同步」,否则每次发完版都在喊狼来了。
+
+出处全在 `box.config.json`(`install.mjs` 会尽量推出来,推不出来就留空,页面上如实写「没配」):
+
+| 键 | 是什么 | install 的默认 |
+| --- | --- | --- |
+| `repoDir` | 看哪个仓库的提交 | `--workspace` |
+| `serverUrl` | 现网服务地址(问它自己的 `/api/version`) | 数据根 `server.lock` 里的端口 |
+| `serverTokenFile` | 现网那个接口要的本机口令文件 | `<数据根>/api-token` |
+| `installDir` | 磁盘上装在哪,用来比出「装了没重启」 | 数据根的上一级 |
+
+口令只在本进程里读,**绝不下发给浏览器**。
+
## 三、巡台那一轮怎么跑
**准则在 `kit/patrol.md`**,装完之后它就是用户机器上的那份(改流程改它,不要改定时任务里的 prompt)。
diff --git a/plugins/requirements-box/skills/requirements-box/kit/box.config.example.json b/plugins/requirements-box/skills/requirements-box/kit/box.config.example.json
index 698d0146..826850f8 100644
--- a/plugins/requirements-box/skills/requirements-box/kit/box.config.example.json
+++ b/plugins/requirements-box/skills/requirements-box/kit/box.config.example.json
@@ -4,5 +4,9 @@
"penguinBin": "/root/.adelie/data/bin/penguin",
"project": "self_evolution",
"agent": "default_agent",
- "workspace": "/root/adelie-fork"
+ "workspace": "/root/adelie-fork",
+ "repoDir": "/root/adelie-fork",
+ "serverUrl": "http://127.0.0.1:7364",
+ "serverTokenFile": "/root/.adelie/data/api-token",
+ "installDir": "/root/.adelie"
}
diff --git a/plugins/requirements-box/skills/requirements-box/kit/install.mjs b/plugins/requirements-box/skills/requirements-box/kit/install.mjs
index 0731cbe5..970bfce4 100644
--- a/plugins/requirements-box/skills/requirements-box/kit/install.mjs
+++ b/plugins/requirements-box/skills/requirements-box/kit/install.mjs
@@ -12,6 +12,7 @@
* --data-root ~/.adelie/data --project default_project --print-only
*
* 选项都有默认值:--dir 必给,其余不给就按上面那些推断(推断结果会原样打印出来核对)。
+ * --repo-dir / --server-url 只影响页面上「提交同步」那块(看哪些提交没发版、现网跟没跟上)。
*/
import { execFileSync } from "node:child_process";
import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
@@ -80,6 +81,24 @@ const DATA_DIR = resolve(String(flags["data-dir"] ?? join(DIR, "data")));
const PENGUIN_BIN = String(flags["penguin-bin"] ?? process.env.PENGUIN_BIN ?? "penguin");
const PRINT_ONLY = flags["print-only"] === true;
+/** 现网在跑的话,数据根那份 server.lock 里记着它的端口;服务没起来就返回空串。 */
+function liveServerUrl() {
+ try {
+ const lock = JSON.parse(readFileSync(join(DATA_ROOT, "server.lock"), "utf8"));
+ return lock && lock.port ? `http://127.0.0.1:${lock.port}` : "";
+ } catch {
+ return "";
+ }
+}
+
+// 页面上「提交同步」那块要的四个出处。能推的都推出来:仓库默认就是巡台改代码的那个工作区;
+// 现网地址从 server.lock 读,读不到就留空 —— 页面上如实说「没配」,比显示一个猜的地址强;
+// 现网口令与安装目录都长在数据根旁边。
+const REPO_DIR = resolve(String(flags["repo-dir"] ?? WORKSPACE));
+const INSTALL_DIR = resolve(String(flags["install-dir"] ?? dirname(DATA_ROOT)));
+const SERVER_TOKEN_FILE = join(DATA_ROOT, "api-token");
+const SERVER_URL = String(flags["server-url"] ?? process.env.ADELIE_SERVER_URL ?? liveServerUrl());
+
if (!PERIOD.match(/^\d+[mhd]$/)) die(`--period 要是 30m / 2h / 7d 这样的写法,收到的是 ${PERIOD}`);
// 巡台会话在这个目录里干活:它不存在的话,spawn 会在点「现在就做」的那一刻才报 ENOENT,
// 那种错没人看得懂 —— 摆的时候就拦住。
@@ -112,6 +131,10 @@ const config = {
project: PROJECT,
agent: AGENT,
workspace: WORKSPACE,
+ repoDir: REPO_DIR,
+ serverUrl: SERVER_URL,
+ serverTokenFile: SERVER_TOKEN_FILE,
+ installDir: INSTALL_DIR,
};
if (!PRINT_ONLY)
writeFileSync(join(DIR, "box.config.json"), `${JSON.stringify(config, null, 2)}\n`);
@@ -154,6 +177,7 @@ console.log(`装到 ${DIR}${PRINT_ONLY ? "(--print-only:什么都没
配置 ${join(DIR, "box.config.json")}
定时任务 ${SCHEDULE_TOML}(每 ${PERIOD})
工作目录 ${WORKSPACE}
+提交同步 ${REPO_DIR}${SERVER_URL ? ` · 现网 ${SERVER_URL}` : " · 现网地址没配上(页面上那块会说「没配」)"}
核对 ${verified}
接下来两步:
diff --git a/plugins/requirements-box/skills/requirements-box/kit/requirements.html b/plugins/requirements-box/skills/requirements-box/kit/requirements.html
index f1d4e883..8495a317 100644
--- a/plugins/requirements-box/skills/requirements-box/kit/requirements.html
+++ b/plugins/requirements-box/skills/requirements-box/kit/requirements.html
@@ -460,6 +460,56 @@
white-space: nowrap;
border: 0;
}
+ .sync-line {
+ font-size: 13px;
+ color: var(--fg-muted);
+ margin: 0 0 4px;
+ }
+ .sync-line b {
+ color: var(--fg);
+ font-weight: 500;
+ }
+ .sync-line .warn {
+ color: #b45309;
+ }
+ .dark .sync-line .warn {
+ color: #fcd34d;
+ }
+ .sync-list {
+ list-style: none;
+ margin: 6px 0 0;
+ padding: 0;
+ }
+ .sync-list li {
+ display: flex;
+ gap: 8px;
+ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
+ font-size: 12px;
+ color: var(--fg-muted);
+ padding: 2px 0;
+ }
+ .sync-list li .h {
+ flex: none;
+ color: var(--fg-faint);
+ }
+ .sync-list li .s {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .sync-list li.doc {
+ opacity: 0.65;
+ }
+ .chip.attention {
+ border-color: #fde68a;
+ background: #fffbeb;
+ color: #b45309;
+ }
+ .dark .chip.attention {
+ background: rgb(245 158 11 / 0.12);
+ border-color: rgb(245 158 11 / 0.3);
+ color: #fcd34d;
+ }
@media (min-width: 640px) {
.grid-2 {
display: grid;
@@ -562,6 +612,20 @@
</form>
</section>
+ <section id="sync" class="card" hidden>
+ <div class="row" style="margin-bottom: 8px">
+ <h2 style="font-size: 15px; font-weight: 600; margin: 0">提交同步</h2>
+ <span class="chip" id="sync-release" hidden></span>
+ <span class="chip" id="sync-unreleased" hidden></span>
+ <span class="chip" id="sync-behind" hidden></span>
+ <span class="grow"></span>
+ <span class="muted" id="sync-at"></span>
+ </div>
+ <p class="sync-line" id="sync-server">—</p>
+ <p class="sync-line" id="sync-repo">—</p>
+ <div id="sync-lists"></div>
+ </section>
+
<section id="patrol" class="card" hidden>
<div class="row" style="margin-bottom: 4px">
<h2 style="font-size: 15px; font-weight: 600; margin: 0">巡台节奏</h2>
@@ -673,6 +737,14 @@
statusLine: document.getElementById("status-line"),
live: document.getElementById("live"),
cadence: document.getElementById("cadence"),
+ sync: document.getElementById("sync"),
+ syncRelease: document.getElementById("sync-release"),
+ syncUnreleased: document.getElementById("sync-unreleased"),
+ syncBehind: document.getElementById("sync-behind"),
+ syncAt: document.getElementById("sync-at"),
+ syncServer: document.getElementById("sync-server"),
+ syncRepo: document.getElementById("sync-repo"),
+ syncLists: document.getElementById("sync-lists"),
latestVersion: document.getElementById("latest-version"),
patrol: document.getElementById("patrol"),
patrolState: document.getElementById("patrol-state"),
@@ -1282,6 +1354,170 @@
els.live.appendChild(document.createTextNode(text));
}
+ /**
+ * 「没发版的提交」「服务器没同步的提交」写在这一块(用户 2026-10-15 的口径)。
+ * 数全在服务端算好(那边读得到仓库的 git、也问得到现网在跑什么),这里只管画成人扫一眼
+ * 就懂的样子:两个数字当徽章,明细折在下面,没东西可看时一行带过。
+ */
+ function paintSync(sync) {
+ if (!sync || sync.configured === false) {
+ els.sync.hidden = true;
+ return;
+ }
+ els.sync.hidden = false;
+
+ var release = sync.release || {};
+ els.syncRelease.hidden = !release.tag;
+ els.syncRelease.textContent = release.tag ? "已发布 " + release.tag : "";
+
+ var unreleased = (sync.unreleased && sync.unreleased.count) || 0;
+ els.syncUnreleased.hidden = unreleased === 0;
+ els.syncUnreleased.textContent = "未发版 " + unreleased + " 条";
+ els.syncUnreleased.className = unreleased > 0 ? "chip attention" : "chip";
+
+ var behind = (sync.behind && sync.behind.count) || 0;
+ els.syncBehind.hidden = behind === 0;
+ els.syncBehind.textContent = "现网没跟上 " + behind + " 条";
+ els.syncBehind.className = behind > 0 ? "chip attention" : "chip";
+
+ els.syncAt.textContent = sync.at ? fmt(sync.at) + " 查的" : "";
+
+ // 配了却读不动(仓库不是仓库、git 不在……):把原因写在明面上,别让这块悄悄消失
+ if (sync.error) {
+ els.syncServer.textContent = "这块没算全:" + sync.error;
+ paintSyncRepo(sync.repo);
+ els.syncLists.textContent = "";
+ return;
+ }
+
+ paintSyncServer(sync.server);
+ paintSyncRepo(sync.repo);
+ paintSyncLists(sync);
+ }
+
+ function paintSyncServer(server) {
+ els.syncServer.textContent = "";
+ if (!server || !server.configured) {
+ els.syncServer.textContent =
+ "没配现网地址:在 box.config.json 里写 serverUrl,才看得出服务器同步没同步";
+ return;
+ }
+ if (!server.ok) {
+ els.syncServer.textContent = "现网读不到:" + (server.note || "原因不明");
+ return;
+ }
+ els.syncServer.appendChild(document.createTextNode("现网正跑 "));
+ var version = document.createElement("b");
+ version.textContent = server.version || "版本不明";
+ els.syncServer.appendChild(version);
+ if (server.short)
+ els.syncServer.appendChild(document.createTextNode("(" + server.short + ")"));
+ if (server.buildDate)
+ els.syncServer.appendChild(document.createTextNode(" · " + server.buildDate + " 构建"));
+ if (server.restartPending) {
+ var warn = document.createElement("span");
+ warn.className = "warn";
+ warn.textContent = " —— 磁盘上装的是 " + server.installedVersion + ",重启了才生效";
+ els.syncServer.appendChild(warn);
+ }
+ }
+
+ function paintSyncRepo(repo) {
+ els.syncRepo.textContent = "";
+ if (!repo) return;
+ var head = repo.head || {};
+ els.syncRepo.appendChild(
+ document.createTextNode("仓库 " + repo.branch + " 的最后一笔是 "),
+ );
+ var hash = document.createElement("b");
+ hash.textContent = head.short || "?";
+ els.syncRepo.appendChild(hash);
+ els.syncRepo.appendChild(
+ document.createTextNode(
+ " " + (head.subject || "") + (head.at ? "(" + fmt(head.at) + ")" : ""),
+ ),
+ );
+ if (repo.dirty)
+ els.syncRepo.appendChild(document.createTextNode(",工作区还有没提交的改动"));
+ }
+
+ function paintSyncLists(sync) {
+ els.syncLists.textContent = "";
+ var unreleased = sync.unreleased;
+ var behind = sync.behind;
+ var up = sync.unpushed;
+ if ((!unreleased || unreleased.count === 0) && (!behind || behind.count === 0)) {
+ var ok = document.createElement("p");
+ ok.className = "sync-line";
+ ok.textContent = "都同步了:没有未发版的提交,现网也在跑最新那个发布。";
+ els.syncLists.appendChild(ok);
+ return;
+ }
+ appendCommitBlock(
+ "未发版",
+ unreleased,
+ up && up.count > 0 ? "其中 " + up.count + " 条还没推到 " + up.upstream : "",
+ );
+ appendCommitBlock(
+ "现网没跟上",
+ behind,
+ behind && behind.docsOnly
+ ? "另外 " + behind.docsOnly + " 条只动了文档,不影响运行"
+ : "",
+ );
+ }
+
+ function appendCommitBlock(title, data, note) {
+ if (!data || data.count === 0) return;
+ var head = document.createElement("p");
+ head.className = "sync-line";
+ head.style.marginTop = "10px";
+ head.textContent = title + " " + data.count + " 条" + (note ? " —— " + note : "");
+ els.syncLists.appendChild(head);
+
+ var ul = document.createElement("ul");
+ ul.className = "sync-list";
+ data.commits.forEach(function (c) {
+ ul.appendChild(commitLi(c));
+ });
+ if (data.truncated) {
+ var more = document.createElement("li");
+ more.textContent = "…还有 " + (data.count - data.commits.length) + " 条没列出来";
+ ul.appendChild(more);
+ }
+ els.syncLists.appendChild(ul);
+ }
+
+ function commitLi(c) {
+ var li = document.createElement("li");
+ // 记账/发布正文这类提交标得淡一点:它们在列表里,但不代表有东西等着上服务器
+ if (/^docs[:(]/.test(c.subject || "")) li.className = "doc";
+ var hash = document.createElement("span");
+ hash.className = "h";
+ hash.textContent = c.short;
+ var subject = document.createElement("span");
+ subject.className = "s";
+ subject.textContent = c.subject + (c.at ? " · " + fmt(c.at) : "");
+ subject.title = c.subject;
+ li.appendChild(hash);
+ li.appendChild(subject);
+ return li;
+ }
+
+ function loadSync(fresh) {
+ if (!key) return Promise.resolve();
+ return api("/sync" + (fresh ? "?fresh=1" : ""))
+ .then(function (body) {
+ paintSync(body.sync);
+ })
+ .catch(function (err) {
+ // 这块算不出来要说出来 —— 它本来就是为了「看不见的东西」才加的
+ els.sync.hidden = false;
+ els.syncAt.textContent = "";
+ els.syncServer.textContent = "这块没算出来:" + err.message;
+ });
+ }
+
function load(opts) {
var quiet = opts && opts.quiet;
if (!quiet) {
@@ -1292,6 +1528,7 @@
els.list.appendChild(sk);
}
}
+ loadSync();
var filter = els.filter.value;
var query = filter === "archived" ? "?archived=1" : filter ? "?status=" + filter : "";
return api(query)
@@ -1403,6 +1640,7 @@
els.statusLine.textContent = "共 " + body.count + " 条 · 序号已发到 " + body.seq;
render(body.items);
loadPatrol();
+ loadSync(true);
})
.catch(function (err) {
showError("口令不对或者服务没起来:" + err.message);
@@ -1458,6 +1696,7 @@
});
loadPatrol();
loadVersion();
+ loadSync(true);
});
// 最新版本号:同源的发布清单(/downloads/index.json,发布那一轮写的)第一项就是最新的。
diff --git a/plugins/requirements-box/skills/requirements-box/kit/requirements.mjs b/plugins/requirements-box/skills/requirements-box/kit/requirements.mjs
index e3a4d29e..57cc9016 100644
--- a/plugins/requirements-box/skills/requirements-box/kit/requirements.mjs
+++ b/plugins/requirements-box/skills/requirements-box/kit/requirements.mjs
@@ -50,6 +50,12 @@ const PENGUIN_BIN = pick("PENGUIN_BIN", "penguinBin", "penguin");
const PATROL_PROJECT = pick("PATROL_PROJECT", "project", "");
const PATROL_AGENT = pick("PATROL_AGENT", "agent", "");
const PATROL_WORKSPACE = pick("PATROL_WORKSPACE", "workspace", process.cwd());
+// 提交同步那一块的三个出处(仓库在哪、现网服务在哪、现网的口令文件在哪)。都是本机才知道的
+// 事,所以照样走 box.config.json;没配就如实说「没配」,不猜一个路径 —— 猜出来的没人敢信。
+const REPO_DIR = pick("REPO_DIR", "repoDir", "");
+const SERVER_URL = pick("SERVER_URL", "serverUrl", "");
+const SERVER_TOKEN_FILE = pick("SERVER_TOKEN_FILE", "serverTokenFile", "");
+const INSTALL_DIR = pick("INSTALL_DIR", "installDir", "");
/** 状态的封闭集合。`new` 是刚提上来还没被看过的;`doing` 是这一轮正在做的。 */
const STATUSES = new Set(["new", "doing", "done", "blocked", "rejected", "withdrawn"]);
@@ -385,6 +391,265 @@ function spawnPatrol(ids, res) {
child.unref();
}
+// --- 提交同步 ---------------------------------------------------------------
+//
+// 用户 2026-10-15 的口径:「没发版 / 服务器没有同步的提交」写在页面上。三件事各有出处,合成
+// 一句话就没人看得懂,所以分开算:
+// · 未发版 —— 仓库 main 上、最后一个发布标签之后的提交(提交了,还没发 Release)
+// · 现网没跟上 —— 已经发出去、而正在跑的那个服务还没换上的提交(发版了,没更新现网)
+// · 装了没重启 —— 磁盘上的版本比正在跑的进程新(更新装好了,进程还挂着旧代码)
+//
+// 现网的版本问它自己(`/api/version`),不拿磁盘上那份冒充正在跑的东西:用户那天遇到的恰恰是
+// 「装好了没重启」,两者混起来正好把这个区别盖掉。那个接口要本机口令,口令从 SERVER_TOKEN_FILE
+// 读,只在本进程里用,绝不下发给浏览器。
+//
+// 几条 git 命令几十毫秒,可页面每 10 秒刷一次,所以缓存 30 秒;页面那个 ⟳ 带 fresh=1 跳过缓存。
+const SYNC_TTL_MS = 30 * 1000;
+const SYNC_COMMIT_LIMIT = 30;
+const SYNC_CMD_TIMEOUT_MS = 8000;
+// git 输出里的字段分隔符:提交标题里什么字符都可能有,只有 US(0x1f)不会出现。
+const FIELD = "\u001f";
+// 「现网没跟上」只算真的会进构建的提交:发布正文、记账这些只动 markdown 的提交从不进产物,
+// 把它们算进去,每次发完版页面都会喊「现网落后 1 条」,喊多了就没人看了。
+const DOC_PATHSPEC = ["--", ".", ":(exclude)*.md", ":(exclude)docs/**"];
+
+let syncCache = { at: 0, value: null };
+
+/** 跑一条命令,收它整份 stdout。非零退出把 stderr 第一行当错误抛出去,由调用方解释。 */
+function runCapture(bin, args, timeout = SYNC_CMD_TIMEOUT_MS) {
+ return new Promise((resolvePromise, reject) => {
+ let child;
+ try {
+ child = spawn(bin, args, { stdio: ["ignore", "pipe", "pipe"] });
+ } catch (err) {
+ reject(err);
+ return;
+ }
+ let out = "";
+ let err = "";
+ let settled = false;
+ const finish = (fn, value) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ fn(value);
+ };
+ const timer = setTimeout(() => {
+ try {
+ child.kill();
+ } catch {
+ /* 已经退了 */
+ }
+ finish(reject, new Error("跑得太久"));
+ }, timeout);
+ child.stdout?.on("data", (d) => {
+ out += String(d);
+ });
+ child.stderr?.on("data", (d) => {
+ err += String(d);
+ });
+ child.on("error", (e) => finish(reject, e));
+ child.on("exit", (code) => {
+ if (code === 0) finish(resolvePromise, out);
+ else finish(reject, new Error((err.trim() || `exit ${code}`).split("\n")[0]));
+ });
+ });
+}
+
+async function git(args) {
+ return runCapture("git", ["-C", REPO_DIR, ...args]);
+}
+
+/** 一行一条提交:短哈希 / 标题 / 提交时间 / 作者。 */
+function parseCommits(text) {
+ return String(text)
+ .split("\n")
+ .map((line) => line.trim())
+ .filter((line) => line !== "")
+ .map((line) => {
+ const [short, subject, at, author] = line.split(FIELD);
+ return { short, subject, at, author };
+ });
+}
+
+/** 一段提交范围:总条数 +(最多 SYNC_COMMIT_LIMIT 条)明细。范围再长也不把整页撑爆。 */
+async function rangeCommits(range, { shippedOnly = false } = {}) {
+ const paths = shippedOnly ? DOC_PATHSPEC : [];
+ const total = await countCommits(range);
+ const shown = shippedOnly ? await countCommits(range, paths) : total;
+ const listed = parseCommits(
+ await git([
+ "log",
+ `--max-count=${SYNC_COMMIT_LIMIT}`,
+ `--pretty=%h${FIELD}%s${FIELD}%cI${FIELD}%an`,
+ range,
+ ...paths,
+ ]),
+ );
+ return {
+ count: shown,
+ // 只是文档/记账的提交单独报个数:它们从来不进构建,混进「现网没跟上」就是狼来了
+ docsOnly: shippedOnly && total > shown ? total - shown : 0,
+ truncated: shown > listed.length,
+ commits: listed,
+ };
+}
+
+async function countCommits(range, paths = []) {
+ const args = ["rev-list", "--count", range, ...paths];
+ const value = Number((await git(args)).trim());
+ return Number.isFinite(value) ? value : 0;
+}
+
+/** 最后一个发布标签。按版本号排,不按时间 —— 补发一个旧版本不该把「最新」指回去。 */
+async function latestRelease() {
+ const tags = (await git(["tag", "--list", "v*", "--sort=-v:refname"]))
+ .split("\n")
+ .map((t) => t.trim())
+ .filter((t) => t !== "");
+ if (tags.length === 0) return null;
+ const tag = tags[0];
+ const hash = (await git(["rev-list", "-n", "1", tag])).trim();
+ return {
+ tag,
+ hash,
+ short: hash.slice(0, 8),
+ at: (await git(["log", "-1", "--pretty=%cI", tag])).trim(),
+ };
+}
+
+/** 现网正在跑的是哪个版本:问它自己的 /api/version,不认磁盘上那份。 */
+async function probeRunning() {
+ if (!SERVER_URL) return { configured: false };
+ const headers = {};
+ let token = "";
+ if (SERVER_TOKEN_FILE) {
+ try {
+ token = readFileSync(SERVER_TOKEN_FILE, "utf8").trim();
+ } catch {
+ token = "";
+ }
+ }
+ if (token) headers.authorization = `Bearer ${token}`;
+ const base = { configured: true, url: SERVER_URL };
+ try {
+ const res = await fetch(`${SERVER_URL}/api/version`, {
+ headers,
+ signal: AbortSignal.timeout(5000),
+ });
+ if (!res.ok) {
+ return {
+ ...base,
+ ok: false,
+ status: res.status,
+ note:
+ res.status === 401
+ ? "现网不认这个口令(SERVER_TOKEN_FILE 指向的那个文件)"
+ : `现网回 HTTP ${res.status}`,
+ };
+ }
+ const body = await res.json();
+ return {
+ ...base,
+ ok: true,
+ version: body.version ?? null,
+ commit: body.commit ?? null,
+ short: String(body.commit ?? "").slice(0, 8),
+ buildDate: body.buildDate ?? null,
+ };
+ } catch (err) {
+ return { ...base, ok: false, note: `没连上现网:${err.message}` };
+ }
+}
+
+/** 磁盘上装的是哪个版本 —— 和「正在跑的」不一样就说明装好了还没重启。 */
+function installedVersion() {
+ if (!INSTALL_DIR) return null;
+ try {
+ return (
+ JSON.parse(readFileSync(join(INSTALL_DIR, "lib", "package.json"), "utf8")).version ?? null
+ );
+ } catch {
+ return null;
+ }
+}
+
+async function computeSync() {
+ const out = {
+ at: new Date().toISOString(),
+ configured: true,
+ repoDir: REPO_DIR || null,
+ serverUrl: SERVER_URL || null,
+ };
+ if (!REPO_DIR) {
+ // 没配仓库 = 这台机器没打算要这一块,整块不显示;配了却读不动才是要报出来的错。
+ out.configured = false;
+ out.error =
+ "没配仓库:在 box.config.json 里写 repoDir(或设 REPO_DIR 环境变量),这块才算得出来";
+ return out;
+ }
+ try {
+ out.repo = {
+ branch: (await git(["rev-parse", "--abbrev-ref", "HEAD"])).trim() || "HEAD",
+ head:
+ parseCommits(await git(["log", "-1", `--pretty=%h${FIELD}%s${FIELD}%cI${FIELD}%an`]))[0] ??
+ null,
+ dirty: (await git(["status", "--porcelain"])).trim() !== "",
+ };
+ } catch (err) {
+ out.error = `读仓库失败:${err.message}`;
+ return out;
+ }
+
+ try {
+ out.release = await latestRelease();
+ } catch (err) {
+ out.error = `读发布标签失败:${err.message}`;
+ return out;
+ }
+ if (!out.release) out.error = "这个仓库里还没有发布标签,分不出「发过没发过」";
+
+ if (out.release) {
+ out.unreleased = await rangeCommits(`${out.release.tag}..HEAD`).catch(() => null);
+ }
+ try {
+ const upstream = (
+ await git(["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"])
+ ).trim();
+ if (upstream) out.unpushed = { upstream, ...(await rangeCommits(`${upstream}..HEAD`)) };
+ } catch {
+ /* 没配远端就不写这一项,别编一个出来 */
+ }
+
+ out.server = { ...(await probeRunning()), installedVersion: installedVersion() };
+ // 磁盘比现网新 = 装好了没重启
+ out.server.restartPending = !!(
+ out.server.ok &&
+ out.server.installedVersion &&
+ out.server.version &&
+ out.server.installedVersion !== out.server.version
+ );
+ // 已经发出去、而现网还没跑上的提交
+ if (out.server.ok && out.server.commit && out.release) {
+ try {
+ out.behind = await rangeCommits(`${out.server.commit}..${out.release.tag}`, {
+ shippedOnly: true,
+ });
+ } catch (err) {
+ out.behindNote = `现网跑的那个提交(${out.server.short || "未知"})对不上这个仓库的历史:${err.message}`;
+ }
+ }
+ return out;
+}
+
+async function syncSnapshot(fresh) {
+ const now = Date.now();
+ if (!fresh && syncCache.value && now - syncCache.at < SYNC_TTL_MS) return syncCache.value;
+ const value = await computeSync();
+ syncCache = { at: now, value };
+ return value;
+}
+
const PAGE_CSP = [
"default-src 'none'",
"style-src 'unsafe-inline'",
@@ -593,6 +858,18 @@ export function handleRequirements(req, res, rawUrl) {
return true;
}
+ // 提交同步:/api/requirements/sync(?fresh=1 跳过缓存)
+ if (tail === "sync") {
+ if (method !== "GET") {
+ json(res, 405, { ok: false, error: "只支持 GET" });
+ return true;
+ }
+ syncSnapshot(url.searchParams.get("fresh") === "1")
+ .then((sync) => json(res, 200, { ok: true, sync }))
+ .catch((err) => json(res, 500, { ok: false, error: `算不出来:${err.message}` }));
+ return true;
+ }
+
// 单条:/api/requirements/<id>
const id = tail.split("/")[0];
const state = load();