@sleep2agi/commhub-server 0.9.0-preview.246 → 0.9.0-preview.247

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,7 @@
1
+ {
2
+ "schema": 1,
3
+ "commit": "4f3402b92ec816455b9976a600d98f7ae415da6b",
4
+ "dirty": false,
5
+ "built_at": "2026-10-31T17:51:57.763Z",
6
+ "source": "ci"
7
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sleep2agi/commhub-server",
3
- "version": "0.9.0-preview.246",
3
+ "version": "0.9.0-preview.247",
4
4
  "description": "CommHub Server — AI Agent communication hub with MCP protocol, multi-network isolation, user auth, and MCP tools (17 collaboration-core + node/provider ops tools; authoritative list: docs-site/docs/api/mcp-tools.md).",
5
5
  "type": "module",
6
6
  "main": "src/index.ts",
@@ -9,12 +9,14 @@
9
9
  },
10
10
  "files": [
11
11
  "src",
12
- "bin"
12
+ "bin",
13
+ "build-info.json"
13
14
  ],
14
15
  "scripts": {
15
16
  "start": "COMMHUB_SERVER=1 bun run src/index.ts",
16
17
  "dev": "COMMHUB_SERVER=1 bun --watch run src/index.ts",
17
- "test": "bun run scripts/test-aggregate.ts"
18
+ "test": "bun run scripts/test-aggregate.ts",
19
+ "prepack": "node scripts/write-build-info.mjs"
18
20
  },
19
21
  "keywords": [
20
22
  "commhub",
@@ -0,0 +1,60 @@
1
+ // #3177 —— 构建期注入的构建标识:**读取三态**(present / absent / invalid)。
2
+ //
3
+ // 为什么这三态必须分开(这是本文件存在的理由):
4
+ // 部署形态(npm install 出来的 runtime)里没有 .git ⇒ 运行期 git rev-parse 拿不到东西 ⇒
5
+ // 生产 /health 的 build_identified 恒为 false(实测:部署 .246 之后仍为 false)。
6
+ // 于是「注入写坏了」与「还没注入」会读成同一个东西 —— 而后者是正常状态、前者是缺陷。
7
+ // ⇒ absent 是正常的;invalid 必须能被单独看见。
8
+ import { describe, expect, test } from "bun:test";
9
+ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
10
+ import { tmpdir } from "node:os";
11
+ import { join } from "node:path";
12
+ import { BUILD_INFO_FILE, readBuildInfo, validateBuildInfo } from "./build-info";
13
+
14
+ const SHA = "a".repeat(40);
15
+ const GOOD = { schema: 1, commit: SHA, dirty: false, built_at: "2026-10-31T17:00:00Z" };
16
+
17
+ function inTemp(fn: (dir: string) => void): void {
18
+ const dir = mkdtempSync(join(tmpdir(), "build-info-"));
19
+ try { fn(dir); } finally { rmSync(dir, { recursive: true, force: true }); }
20
+ }
21
+
22
+ describe("#3177 build-info 读取", () => {
23
+ test("absent:目录里没有文件 —— 这是**正常状态**(部署形态没注入),不是缺陷", () => {
24
+ inTemp((dir) => expect(readBuildInfo(dir)).toEqual({ kind: "absent" }));
25
+ });
26
+
27
+ test("present:格式正确就原样读出(含可选 source)", () => {
28
+ inTemp((dir) => {
29
+ writeFileSync(join(dir, BUILD_INFO_FILE), JSON.stringify({ ...GOOD, source: "release.yml" }));
30
+ expect(readBuildInfo(dir)).toEqual({ kind: "present", info: { ...GOOD, source: "release.yml" } });
31
+ });
32
+ });
33
+
34
+ test("invalid:文件在但形状不对 ⇒ 与 absent **分开报**", () => {
35
+ inTemp((dir) => {
36
+ writeFileSync(join(dir, BUILD_INFO_FILE), "{ not json");
37
+ expect(readBuildInfo(dir)).toEqual({ kind: "invalid", error: "invalid_json" });
38
+ writeFileSync(join(dir, BUILD_INFO_FILE), JSON.stringify({ ...GOOD, commit: "short" }));
39
+ expect(readBuildInfo(dir)).toEqual({ kind: "invalid", error: "invalid_shape" });
40
+ });
41
+ });
42
+
43
+ test("严格校验:这几个都不接受(每一个都是真实会写错的形态)", () => {
44
+ expect(validateBuildInfo(null)).toBeNull();
45
+ expect(validateBuildInfo([])).toBeNull();
46
+ expect(validateBuildInfo({ ...GOOD, schema: "1" })).toBeNull(); // 字符串 schema
47
+ expect(validateBuildInfo({ ...GOOD, commit: "A".repeat(40) })).toBeNull(); // 大写 hex
48
+ expect(validateBuildInfo({ ...GOOD, commit: "a".repeat(39) })).toBeNull();
49
+ expect(validateBuildInfo({ ...GOOD, dirty: "false" })).toBeNull(); // 字符串布尔
50
+ expect(validateBuildInfo({ ...GOOD, built_at: "2026-10-31 17:00:00" })).toBeNull(); // 非 ISO-Z
51
+ expect(validateBuildInfo({ ...GOOD, built_at: "yesterday" })).toBeNull();
52
+ expect(validateBuildInfo({ ...GOOD, source: 42 })).toBeNull();
53
+ });
54
+
55
+ test("脏树可以注入,但读数里必须看得见 dirty —— 否则「脏树构建」会被当成提交", () => {
56
+ const dirty = validateBuildInfo({ ...GOOD, dirty: true });
57
+ expect(dirty?.dirty).toBe(true);
58
+ expect(dirty?.commit).toBe(SHA);
59
+ });
60
+ });
@@ -0,0 +1,85 @@
1
+ /**
2
+ * 2026-10-31 —— **构建期注入的构建标识**(#3177)。
3
+ *
4
+ * 为什么需要它:`detectBootGitIdentity()` 是**运行期** `git rev-parse` 从 module_dir 向上找 `.git`。
5
+ * 而生产的部署形态是 `npm install --prefix ~/.commhub/runtime-…` 的产物 —— **没有 .git**。
6
+ * 实测(部署 .246 之后):`/health` 的 `build_identified = false`。
7
+ * ⇒ 同一版本号、不同字节,在生产上**无法分辨**;而 runtime 读 git 这条路在部署形态上不存在。
8
+ *
9
+ * 所以标识必须由**构建时**写下来,运行期只负责读,并且**读不到要能与「没有标识」区分**。
10
+ *
11
+ * 本模块只做读取与**严格校验**:形状不对就返回 null,绝不猜、绝不抛。
12
+ * 判据:一个坏掉的 build-info.json 与「没有这个文件」是两件事,
13
+ * 但两者都不能变成「看起来有标识」—— 所以校验失败一律 null,由调用方的 reason 去说明。
14
+ */
15
+ import { readFileSync } from "node:fs";
16
+ import { join } from "node:path";
17
+
18
+ export type BuildInfo = {
19
+ schema: 1;
20
+ /** 40 位小写十六进制;构建时的 HEAD。 */
21
+ commit: string;
22
+ /** 构建时工作树是否脏。脏的 commit 只能当「自称」用。 */
23
+ dirty: boolean;
24
+ /** 构建时刻(ISO 8601,UTC)。 */
25
+ built_at: string;
26
+ /** 可选:谁写的(例如 "release.yml")。仅用于人读。 */
27
+ source?: string;
28
+ };
29
+
30
+ export const BUILD_INFO_FILE = "build-info.json";
31
+
32
+ const SHA40 = /^[0-9a-f]{40}$/;
33
+
34
+ function isIsoUtc(s: unknown): s is string {
35
+ if (typeof s !== "string" || s.length < 20) return false;
36
+ const ms = Date.parse(s);
37
+ return Number.isFinite(ms) && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/.test(s);
38
+ }
39
+
40
+ /** 校验一份 build-info 载荷;形状不对返回 null(不抛)。 */
41
+ export function validateBuildInfo(raw: unknown): BuildInfo | null {
42
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
43
+ const o = raw as Record<string, unknown>;
44
+ if (o.schema !== 1) return null;
45
+ if (typeof o.commit !== "string" || !SHA40.test(o.commit)) return null;
46
+ if (typeof o.dirty !== "boolean") return null;
47
+ if (!isIsoUtc(o.built_at)) return null;
48
+ if (o.source !== undefined && typeof o.source !== "string") return null;
49
+ const out: BuildInfo = { schema: 1, commit: o.commit, dirty: o.dirty, built_at: o.built_at };
50
+ if (typeof o.source === "string") out.source = o.source;
51
+ return out;
52
+ }
53
+
54
+ /**
55
+ * 从某个目录读 build-info.json。
56
+ *
57
+ * 返回**两态**而不是一态:
58
+ * `{ kind: "present", info }` —— 读到且通过校验
59
+ * `{ kind: "absent" }` —— 文件不存在(部署形态没注入)
60
+ * `{ kind: "invalid", error }` —— 文件在但形状不对(这是**缺陷**,不是「没有」)
61
+ * 第三种必须与第二种分开:否则「注入写坏了」会读成「还没注入」,而后者是正常状态。
62
+ */
63
+ export type BuildInfoRead =
64
+ | { kind: "present"; info: BuildInfo }
65
+ | { kind: "absent" }
66
+ | { kind: "invalid"; error: string };
67
+
68
+ export function readBuildInfo(dir: string): BuildInfoRead {
69
+ const path = join(dir, BUILD_INFO_FILE);
70
+ let text: string;
71
+ try {
72
+ text = readFileSync(path, "utf8");
73
+ } catch (e: any) {
74
+ if (e && (e.code === "ENOENT" || e.code === "ENOTDIR")) return { kind: "absent" };
75
+ return { kind: "invalid", error: `unreadable:${e?.code ?? "unknown"}` };
76
+ }
77
+ let parsed: unknown;
78
+ try {
79
+ parsed = JSON.parse(text);
80
+ } catch {
81
+ return { kind: "invalid", error: "invalid_json" };
82
+ }
83
+ const info = validateBuildInfo(parsed);
84
+ return info ? { kind: "present", info } : { kind: "invalid", error: "invalid_shape" };
85
+ }
@@ -1021,15 +1021,24 @@ describe("#473 anonymous /health — watchdog contract intact, no topology leak"
1021
1021
  // 2026-10-31 —— **身份是从哪个根读的**(外部复核那条:release 读的是 cwd,不是可执行文件目录)。
1022
1022
  // 我们优先模块目录,只在拿不到时退回 cwd —— 但若没有字段说明是哪一支,
1023
1023
  // 「读到的是本包的身份」与「读到的是启动目录里另一个仓库」在载荷上完全同形。
1024
- test("git identity says which root it came from (module_dir vs cwd)", async () => {
1024
+ test("git identity says which root it came from (build_info vs module_dir vs cwd)", async () => {
1025
1025
  const b = await (await fetch(`${BASE}/health`, { headers: { Authorization: `Bearer ${adminToken}` } })).json() as any;
1026
- expect(["module_dir", "cwd"]).toContain(b.git_identity_root);
1026
+ // 2026-10-31 —— 加了第三支 `build_info`(#3177:生产 runtime 没有 .git,
1027
+ // 只有在**打包时**写进 build-info.json 才可能有标识)。
1028
+ expect(["build_info", "module_dir", "cwd"]).toContain(b.git_identity_root);
1027
1029
  // 从 cwd 读出来的身份,必须显式承认它不是制品身份
1028
1030
  if (b.git_identity_root === "cwd") {
1029
1031
  expect(b.build_identity_note === null || typeof b.build_identity_note === "string").toBe(true);
1030
1032
  }
1031
1033
  // 反向:有 commit 却说不出来源 ⇒ 这条断言不允许
1032
- if (b.git_commit) expect(["module_dir", "cwd"]).toContain(b.git_identity_root);
1034
+ if (b.git_commit) expect(["build_info", "module_dir", "cwd"]).toContain(b.git_identity_root);
1035
+ // 新支的存在意义:**注入存在 ⇒ 标识必须存在**。
1036
+ // 这一条让「注入了但读不到」变成红,而不是静默退回「没有标识」。
1037
+ if (b.git_identity_root === "build_info") {
1038
+ expect(b.build_identified).toBe(true);
1039
+ expect(b.git_commit).toMatch(/^[0-9a-f]{40}$/);
1040
+ expect(typeof b.git_dirty).toBe("boolean");
1041
+ }
1033
1042
  });
1034
1043
 
1035
1044
  // 2026-10-31 —— **每个 verdict 都要有仲裁字段**(外部复核那条:
@@ -111,8 +111,18 @@ test('actual Hub tool atomically saves encrypted Provider; metadata read and con
111
111
  const read = await human('daemon_provider_snapshot', { action: 'hub_read', id: 'hub', network_id: net }); expect(read.providers).toHaveLength(1);
112
112
  // 2026-10-31 —— **精确键集**(#3171):客户端「可选模型」这一面直接消费这两个投影,
113
113
  // 而多给一个键(尤其 secret_key_ref)在这条线上是最严重的那类改动。
114
- // 实际四键(我第一版漏了 network_id —— 断言当场纠正)。
115
- expect(Object.keys(read).sort()).toEqual(["network_id", "ok", "providers", "source"]);
114
+ //
115
+ // 2026-10-31 晚 —— 补齐到 7 键。原因是端点自己长出了三态自述(counts / source_table / state):
116
+ // 「providers 是空数组」与「全都禁用」在旧载荷里长得一模一样,读的人只能猜。
117
+ // 这条精确键集因此**当场变红**——而这正是它该做的事:让「多加一栏」必须是一次有意识的决定。
118
+ // 两个键的存在理由:state ∈ {configured, unconfigured, all_disabled}(空数组不是结论);
119
+ // source_table 说明读的是**哪张表**(本仓另有 MCP list_providers 读 providers 表,两者不同源)。
120
+ expect(Object.keys(read).sort()).toEqual([
121
+ "counts", "network_id", "ok", "providers", "source", "source_table", "state",
122
+ ]);
123
+ expect(["configured", "unconfigured", "all_disabled"]).toContain(read.state);
124
+ expect(read.source_table).toBe("hub_provider_configs");
125
+ expect(read.counts.providers).toBe(read.providers.length); // 计数与数组同源
116
126
  // provider 视图实际 12 键(我第一版写了 6 个,漏了 baseUrl/enabled/models/protocol/updated_at/verification)
117
127
  expect(Object.keys(result.provider).sort()).toEqual([
118
128
  "baseUrl", "compatible_runtimes", "credential_present", "enabled", "id", "label",
package/src/server.ts CHANGED
@@ -107,6 +107,7 @@ import { assertScheduledTaskBackendSupported, handleScheduledTaskRequest, startS
107
107
  import { startDueReminderTimer } from "./requirement-due-reminders.js";
108
108
  import { clearNodeFromRequirements, handleRequirementsRequest } from "./requirements.js";
109
109
  import { readHubProviders, putHubProvider, providerWriteStatus } from "./hub-provider-config.js";
110
+ import { readBuildInfo } from "./build-info.js";
110
111
  import { requestProviderApplication } from "./daemon-provider-snapshots.js";
111
112
  import { requestNodeSecrets, getScopedSecrets } from "./scoped-secrets.js";
112
113
  import { readEnvTransportLog } from "./env-transport-gate.js";
@@ -1460,7 +1461,12 @@ function detectBootGitIdentity(): {
1460
1461
  /** 只有 commit 非空时才有意义;commit 为空时必须是 null(**不是 false**)。 */
1461
1462
  dirty: boolean | null;
1462
1463
  /** commit 为空时说明**为什么**空 —— 没有它,「没有」与「读不到」同形。 */
1463
- reason: "not_a_git_checkout" | "git_unavailable" | "unexpected_rev_parse_output" | null;
1464
+ /**
1465
+ * 2026-10-31 —— #3177:`build_info_invalid` 与 `not_a_git_checkout` 必须分开。
1466
+ * 前者是**缺陷**(注入写坏了),后者是**部署形态的正常状态**(npm 包里没有 .git)。
1467
+ * 合成一个 reason,就等于把「写坏了」读成「本来就没有」。
1468
+ */
1469
+ reason: "not_a_git_checkout" | "git_unavailable" | "unexpected_rev_parse_output" | "build_info_invalid" | null;
1464
1470
  /**
1465
1471
  * 2026-10-31 —— **这个 commit 是从哪个根读出来的**(外部复核那条:
1466
1472
  * 「release 读的是 cwd 而不是可执行文件目录 ⇒ 它标识部署动作,不标识运行内容」)。
@@ -1470,11 +1476,25 @@ function detectBootGitIdentity(): {
1470
1476
  * 在载荷上完全同形 —— 后者会把一台跑着旧包的机器报成新提交。
1471
1477
  * ⇒ 加一格 root_kind 作仲裁;cwd 那一支必须能被看出来。
1472
1478
  */
1473
- root_kind: "module_dir" | "cwd";
1479
+ root_kind: "module_dir" | "cwd" | "build_info";
1474
1480
  } {
1475
1481
  const moduleDir = (import.meta as { dir?: string }).dir;
1476
1482
  const start = moduleDir ?? process.cwd();
1477
1483
  const rootKind: "module_dir" | "cwd" = moduleDir ? "module_dir" : "cwd";
1484
+ // 2026-10-31 —— #3177:**先读构建期注入**,再退回运行期 git。
1485
+ // 生产是 `npm install` 出来的 runtime(没有 .git),运行期这条路在那里根本不存在 ⇒
1486
+ // 只能由构建时写下 commit/dirty/built_at。读到了就以它为准(它是**制品的一部分**,
1487
+ // 比「启动目录恰好是个 git 仓库」更能代表跑的是什么字节)。
1488
+ // 包内布局是 `bin/commhub.ts` + `build-info.json` 在包根 ⇒ 两处都看。
1489
+ const candidates = [start, dirname(start)];
1490
+ let buildInfoInvalid = false;
1491
+ for (const c of candidates) {
1492
+ const read = readBuildInfo(c);
1493
+ if (read.kind === "present") {
1494
+ return { commit: read.info.commit, dirty: read.info.dirty, reason: null, root_kind: "build_info" };
1495
+ }
1496
+ if (read.kind === "invalid") buildInfoInvalid = true;
1497
+ }
1478
1498
  let dir = start;
1479
1499
  for (let i = 0; i < 6; i += 1) {
1480
1500
  if (existsSync(join(dir, ".git"))) {
@@ -1508,7 +1528,13 @@ function detectBootGitIdentity(): {
1508
1528
  if (parent === dir) break;
1509
1529
  dir = parent;
1510
1530
  }
1511
- return { commit: null, dirty: null, reason: "not_a_git_checkout", root_kind: rootKind };
1531
+ return {
1532
+ commit: null,
1533
+ dirty: null,
1534
+ // 注入文件在但写坏了 ⇒ 这是缺陷,不能与「部署形态没有 .git」同形
1535
+ reason: buildInfoInvalid ? "build_info_invalid" : "not_a_git_checkout",
1536
+ root_kind: rootKind,
1537
+ };
1512
1538
  }
1513
1539
 
1514
1540
  const BOOT_GIT = detectBootGitIdentity();