@sleep2agi/commhub-server 0.9.0-preview.240 → 0.9.0-preview.242

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sleep2agi/commhub-server",
3
- "version": "0.9.0-preview.240",
3
+ "version": "0.9.0-preview.242",
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",
@@ -865,7 +865,7 @@ describe("#473 anonymous /health — watchdog contract intact, no topology leak"
865
865
  // allowed = 没打 frozen 标 ⇒ 变不变都可以,本测试不管
866
866
  // excluded = 会变且不该被 pinned ⇒ 必须存在并在正向对照里出现(见下)
867
867
  // 窗口显式:WINDOW_MS 写在断言里,而不是「两次读一下大概就行」。
868
- test("frozen_at_boot fields really do not change within a declared window", async () => {
868
+ test("frozen_at_boot fields do not change within a declared window (and this does NOT prove the pinning is correct)", async () => {
869
869
  const { HEALTH_FIELD_META } = await import("./server.js");
870
870
  const WINDOW_MS = 1200;
871
871
  expect(WINDOW_MS).toBeGreaterThan(0); // 窗口为 0 的「没变」不构成读数
@@ -1296,7 +1296,7 @@ describe("#473 anonymous /health — watchdog contract intact, no topology leak"
1296
1296
  // 谓词落在**名字**上而不是「源码里出现了减法」(外部复核:
1297
1297
  // 「`startedAt` / `lastSuccessAt` 也是减法算出来的但**稳**;只扫减法会漏掉无条件的那个」)。
1298
1298
  // 分母必须报出来:命中 0 个差值字段 ⇒ 这条断言是真空真。
1299
- test("any difference-shaped field names both of its endpoints in the same payload", async () => {
1299
+ test("difference-shaped fields name both endpoints in the same payload (proves endpoints exist, not that the value is right)", async () => {
1300
1300
  const { HEALTH_FIELD_META } = await import("./server.js");
1301
1301
  const DIFFY = /(age|elapsed|uptime|remaining|ttl|delta|drift|lag)/i;
1302
1302
  const named = Object.keys(HEALTH_FIELD_META).filter((k) => DIFFY.test(k));
@@ -1338,6 +1338,21 @@ describe("#473 anonymous /health — watchdog contract intact, no topology leak"
1338
1338
  expect(/git|commit|build[-_]?(sha|id)?/.test("x-commhub")).toBe(false);
1339
1339
  });
1340
1340
 
1341
+ // 2026-10-31 —— **一致时零证据**(外部复核:「status / db / mineruProxy 三个字段是同一个位,
1342
+ // 一致时零证据」)。本仓的 status 与 status_reasons 由构造保证一致 ⇒
1343
+ // 「status=='ok' ⟺ reasons 为空」是恒真断言,保护不了任何东西。
1344
+ // ⇒ 改成断言**映射本身**:给一个理由就必须 degraded;且映射是纯函数、可被单独喂输入。
1345
+ test("status mapping is a pure function of the reasons list (one reason is enough to degrade)", async () => {
1346
+ const { statusFromReasons } = await import("./server.js");
1347
+ expect(statusFromReasons([])).toBe("ok");
1348
+ expect(statusFromReasons(["db_unreadable"])).toBe("degraded");
1349
+ expect(statusFromReasons(["license_unreadable"])).toBe("degraded");
1350
+ expect(statusFromReasons(["anything_at_all"])).toBe("degraded"); // 不认识的理由也不许吞
1351
+ // 且线上载荷与函数一致(不是两套逻辑)
1352
+ const live = await (await fetch(`${BASE}/health`)).json() as any;
1353
+ expect(live.status).toBe(statusFromReasons(live.status_reasons ?? []));
1354
+ });
1355
+
1341
1356
  test("no dead entries: every allow-listed key is actually served to anonymous callers", async () => {
1342
1357
  const { PUBLIC_HEALTH_KEYS } = await import("./server.js");
1343
1358
  const plain = await (await fetch(`${BASE}/health`)).json() as any;
@@ -157,6 +157,14 @@ describe("GET /api/skills", () => {
157
157
  const back = await get(`/api/providers?network_id=${ownerNet}`, ownerToken);
158
158
  expect(back.body.state).toBe("configured");
159
159
  expect(back.body.counts.models_enabled).toBeGreaterThan(0);
160
+
161
+ // 2026-10-31 —— **形状测试必须先证明输入彼此不同,再断言各自属性**
162
+ // (外部复核 ③:「顺序不能反:先断言几种形状的字节两两不等,再断言各自含有应有的属性;
163
+ // 反过来时『四种其实是一种』也能全绿。」)
164
+ // 这里是三态:删掉 state 之后,三份载荷必须两两不同 —— 否则「三态」只是同一个载荷换了标签。
165
+ const strip = (b: any) => { const { state: _s, ...rest } = b; return JSON.stringify(rest); };
166
+ const three = [strip(before.body), strip(disabled.body), strip(back.body)];
167
+ expect(new Set(three).size).toBe(3);
160
168
  });
161
169
 
162
170
  test("a member of another network is refused", async () => {
@@ -367,6 +375,27 @@ describe("GET /api/providers", () => {
367
375
  // ⇒ A、B 两条向量改变的是同一个出口量」)。
368
376
  // 对应到本路由:五个 state 如果**去掉 state 字段**就分不出来,那 state 就是唯一信息源,
369
377
  // 载荷只是标签的复读 —— 秩 = 1。判据:把 state 删掉之后,五个载荷仍两两可区分。
378
+ // 2026-10-31 —— **从属字段在主条件为假时不得有值**(外部复核 (d):
379
+ // 「从属字段在主字段为假时不得有值;不校验就会存下不可能的状态,
380
+ // 后来者无法区分它与历史遗留,只会当成有效读数。」)
381
+ // 本路由的三个从属键:
382
+ // error ⟺ state === "failed"
383
+ // observed_status ⟺ state === "unknown"
384
+ // hint ⟺ state ∈ {never_switched, unknown}(pending/applied 不该有 hint)
385
+ const has = (o: any, k: string) => Object.prototype.hasOwnProperty.call(o, k);
386
+ const cases: Array<[string, any, { error: boolean; observed_status: boolean; hint: boolean }]> = [
387
+ ["never_switched", a.body, { error: false, observed_status: false, hint: true }],
388
+ ["pending", b.body, { error: false, observed_status: false, hint: false }],
389
+ ["applied", c.body, { error: false, observed_status: false, hint: false }],
390
+ ["failed", d.body, { error: true, observed_status: false, hint: false }],
391
+ ["unknown", e.body, { error: false, observed_status: true, hint: true }],
392
+ ];
393
+ for (const [label, body, want] of cases) {
394
+ expect({ label, error: has(body, "error") }).toEqual({ label, error: want.error });
395
+ expect({ label, observed: has(body, "observed_status") }).toEqual({ label, observed: want.observed_status });
396
+ expect({ label, hint: has(body, "hint") }).toEqual({ label, hint: want.hint });
397
+ }
398
+
370
399
  const strip = (b: any) => { const { state: _s, ...rest } = b; return JSON.stringify(rest); };
371
400
  const five = [a, b, c, d, e].map((r) => strip(r.body));
372
401
  expect(new Set(five).size).toBe(5); // 两两不同 ⇒ 秩 ≥ 2,state 不是唯一维度
@@ -457,7 +486,7 @@ describe("GET /api/providers", () => {
457
486
  // 「白名单管『怎么写』,这条管『写几处』」)。
458
487
  // 这两张状态映射各自只能有**一处定义**,且必须被生产代码**至少读一次**:
459
488
  // 只有定义、没有读取 ⇒ 它是一张装饰表(写 1 处、读 0 处)。
460
- test("status maps are defined exactly once and actually read by production code", async () => {
489
+ test("status maps are defined exactly once and read by production code (a comment mentioning them does not count)", async () => {
461
490
  const { readFileSync, readdirSync, statSync } = await import("node:fs");
462
491
  const { join } = await import("node:path");
463
492
  const root = join(import.meta.dir);
@@ -518,9 +547,19 @@ describe("GET /api/providers", () => {
518
547
  const { PROVIDER_WRITE_ERROR_CODES: CODES, PROVIDER_WRITE_STATUS: STATUS, providerWriteStatus: statusOf } =
519
548
  await import("./hub-provider-config.js");
520
549
  const CLOSED = new Set([400, 401, 403, 404, 409, 500, 503]);
550
+ // 2026-10-31 —— **把「恒真的断言」换成能假的那条**(外部复核 (a):
551
+ // 「同一个字面量 code 有两个 id 生产者,而选择依据是另一个观测量 ⇒
552
+ // 两条测试都没覆盖第二个分支 ⇒ `observed.id === body.error.diagnosticId` 永远成立」)。
553
+ //
554
+ // 本仓原来这里写的是 `expect(statusOf(code)).toBe(STATUS[code])` ——
555
+ // 而 statusOf 的实现就是 `STATUS[code] ?? 500` ⇒ 对表里的码**恒真**,
556
+ // 它证明不了任何东西(把状态表整个改成 200 它也绿,只要两边一起改)。
557
+ // ⇒ 换成两条能假、且各自守一件事的断言:
558
+ // ① 码清单与状态表的**键集相等**(新增一个码却没给状态 ⇒ 红)
559
+ // ② 每个值落在 HTTP 闭集里(有人写 299 / 0 ⇒ 红)
560
+ expect(Object.keys(STATUS).sort()).toEqual([...CODES].sort());
521
561
  for (const code of CODES) {
522
- expect(statusOf(code)).toBe(STATUS[code]);
523
- expect(CLOSED.has(statusOf(code))).toBe(true);
562
+ expect(CLOSED.has(STATUS[code])).toBe(true);
524
563
  }
525
564
  // 镜像(must-fire):一个**不在表里**的码必须落到 500,不能落 400
526
565
  const bogus = statusOf("definitely_not_a_listed_code" as any);
@@ -103,6 +103,16 @@ describe("assignee never contradicts a validated owner/agent_owner reference", (
103
103
  expect(manual.status).toBe(200);
104
104
  expect(manual.body.requirement.assignee).toBe("王工");
105
105
 
106
+ // 2026-10-31 —— **双向可测**(外部复核 ④:
107
+ // 「改粒度维度 ⇒ 结果变(确实相关);改其它维度 ⇒ 结果不变(确实无关)。
108
+ // 只做前一向时,一个『什么都相关』的模型也能满足它。」)
109
+ // 第一向(相关)上面已经有了:改 agent_owner ⇒ assignee 跟着变。
110
+ // 这一向(无关):改一个**不相干**的字段(name),assignee 必须**不变**。
111
+ const renamed = await send("PATCH", `/api/requirements/${id}?network_id=${NET}`, { name: "改个名字而已" });
112
+ expect(renamed.status).toBe(200);
113
+ expect(renamed.body.requirement.name).toBe("改个名字而已");
114
+ expect(renamed.body.requirement.assignee).toBe("asg-probe"); // 与上面那条同一张卡
115
+
106
116
  // 两者**同时存在**时读侧以引用为准(这是有意的取舍:引用写入时被校验过,自由文本没有)。
107
117
  // 记录在这里,免得下一个人把它当成 bug 再改回去。
108
118
  const both = await send("PATCH", `/api/requirements/${id}?network_id=${NET}`, { assignee: "王工" });
package/src/server.ts CHANGED
@@ -1212,6 +1212,17 @@ export const SELECTION_STATE_BY_STATUS: Record<string, "pending" | "applied" | "
1212
1212
  expired: "failed", // 过期=没生效;对使用者与失败同一档
1213
1213
  };
1214
1214
 
1215
+ /**
1216
+ * 2026-10-31 —— `status` 与 `status_reasons` **是同一个位的两种说法**(外部复核:
1217
+ * 「三字段一致时零证据」)。既然它们由构造保证一致,那么「status=='ok' ⟺ reasons 为空」
1218
+ * 这条断言**恒真**,它保护不了任何东西。
1219
+ * ⇒ 把映射抽成一个纯函数,测试改为断言**映射本身**(给一个理由就必须 degraded),
1220
+ * 这样「有人把映射改成忽略 reasons」会红,而「两者一致」这种同义反复不会写成测试。
1221
+ */
1222
+ export function statusFromReasons(reasons: readonly string[]): "ok" | "degraded" {
1223
+ return reasons.length === 0 ? "ok" : "degraded";
1224
+ }
1225
+
1215
1226
  export const HEALTH_FIELD_META: Readonly<Record<string, HealthFieldMeta>> = {
1216
1227
  // ── gauge:聚合 / 粗标签 ─────────────────────────────────────────────
1217
1228
  ok: {
@@ -1756,6 +1767,33 @@ const startedAtIso = new Date(Date.now() - Math.floor(process.uptime() * 1000)).
1756
1767
 
1757
1768
  const BOOT_KERNEL_START = detectKernelStart(startedAtIso);
1758
1769
 
1770
+ /**
1771
+ * 2026-10-31 —— **两条上传路径的两个逐字相同的生产者,收成一个**。
1772
+ *
1773
+ * 头像上传与文件上传各自写了一份 `earlyReject`(withCors + Connection: close)
1774
+ * 和一份 429 限流头(X-RateLimit-*)。计数报告实测:`x-ratelimit-limit` 等三个头各有 2 处写出点。
1775
+ * ⇒ 改一处只改了一半,而**没有任何测试会因为两处不一致而红**。
1776
+ *
1777
+ * 判据:这个值有几个生产者?>1 时,正确说法是「改掉了其中的 1/N」。
1778
+ */
1779
+ function uploadEarlyReject(req: Request, res: Response): Response {
1780
+ // pre-drain 拒绝统一关闭连接:keepalive 上残留的 multipart 未读字节会把
1781
+ // 下一个请求读成垃圾。
1782
+ const wrapped = withCors(req, res);
1783
+ wrapped.headers.set("Connection", "close");
1784
+ return wrapped;
1785
+ }
1786
+
1787
+ function uploadRateLimitHeaders(rate: { resetAt: number; retryAfterMs?: number }): Record<string, string> {
1788
+ const headers: Record<string, string> = {
1789
+ "X-RateLimit-Limit": String(60),
1790
+ "X-RateLimit-Remaining": "0",
1791
+ "X-RateLimit-Reset": String(Math.floor(rate.resetAt / 1000)),
1792
+ };
1793
+ if (rate.retryAfterMs) headers["Retry-After"] = String(Math.ceil(rate.retryAfterMs / 1000));
1794
+ return headers;
1795
+ }
1796
+
1759
1797
  function withCors(req: Request, res: Response): Response {
1760
1798
  const headers = corsHeaders(req);
1761
1799
  for (const [k, v] of Object.entries(headers)) {
@@ -2387,11 +2425,7 @@ return Bun.serve({
2387
2425
  if (url.pathname === "/api/auth/me/avatar/upload" && req.method === "POST") {
2388
2426
  // pre-drain 拒绝统一关闭连接:keepalive 上残留的 multipart 未读字节会把
2389
2427
  // 下一个请求读成垃圾(与 /api/upload 的 earlyReject 同一理由)。
2390
- const earlyReject = (res: Response): Response => {
2391
- const wrapped = withCors(req, res);
2392
- wrapped.headers.set("Connection", "close");
2393
- return wrapped;
2394
- };
2428
+ const earlyReject = (res: Response): Response => uploadEarlyReject(req, res);
2395
2429
  const token = req.headers.get("Authorization")?.replace("Bearer ", "");
2396
2430
  if (!token) return earlyReject(Response.json({ ok: false, error: "token required" }, { status: 401 }));
2397
2431
  const resolved = resolveToken(token);
@@ -2404,12 +2438,7 @@ return Bun.serve({
2404
2438
  const rateKey = authCtx?.tokenId ?? `ip:${getClientIP(req, server)}`;
2405
2439
  const rate = sharedUploadRateLimiter.check(rateKey);
2406
2440
  if (!rate.allowed) {
2407
- const headers: Record<string, string> = {
2408
- "X-RateLimit-Limit": String(60),
2409
- "X-RateLimit-Remaining": "0",
2410
- "X-RateLimit-Reset": String(Math.floor(rate.resetAt / 1000)),
2411
- };
2412
- if (rate.retryAfterMs) headers["Retry-After"] = String(Math.ceil(rate.retryAfterMs / 1000));
2441
+ const headers = uploadRateLimitHeaders(rate);
2413
2442
  return earlyReject(new Response(
2414
2443
  JSON.stringify({ ok: false, error: "rate_limited", message: "Upload rate limit exceeded (60/hour). Try again later.", retry_after_ms: rate.retryAfterMs }),
2415
2444
  { status: 429, headers: { ...headers, "Content-Type": "application/json; charset=utf-8" } },
@@ -3662,7 +3691,7 @@ return Bun.serve({
3662
3691
  const body: Record<string, unknown> = {
3663
3692
  ok: true,
3664
3693
  // 200 是**承诺**(watchdog 契约),不等于「健康」。健康与否放在 body 里:
3665
- status: statusReasons.length === 0 ? "ok" : "degraded",
3694
+ status: statusFromReasons(statusReasons),
3666
3695
  status_reasons: statusReasons,
3667
3696
  version: SERVER_VERSION,
3668
3697
  version_source: SERVER_VERSION_SOURCE,
@@ -5083,11 +5112,7 @@ return Bun.serve({
5083
5112
  // just made it visible under aggregate `bun test` with a 12MiB
5084
5113
  // upload immediately followed by another request. Per-file green
5085
5114
  // hides this class of bug.
5086
- const earlyReject = (res: Response): Response => {
5087
- const wrapped = withCors(req, res);
5088
- wrapped.headers.set("Connection", "close");
5089
- return wrapped;
5090
- };
5115
+ const earlyReject = (res: Response): Response => uploadEarlyReject(req, res);
5091
5116
  const authErr = requireAuth(req);
5092
5117
  if (authErr) return earlyReject(authErr);
5093
5118
 
@@ -5097,12 +5122,7 @@ return Bun.serve({
5097
5122
  const rateKey = authCtx?.tokenId ?? `ip:${getClientIP(req, server)}`;
5098
5123
  const rate = sharedUploadRateLimiter.check(rateKey);
5099
5124
  if (!rate.allowed) {
5100
- const headers: Record<string, string> = {
5101
- "X-RateLimit-Limit": String(60),
5102
- "X-RateLimit-Remaining": "0",
5103
- "X-RateLimit-Reset": String(Math.floor(rate.resetAt / 1000)),
5104
- };
5105
- if (rate.retryAfterMs) headers["Retry-After"] = String(Math.ceil(rate.retryAfterMs / 1000));
5125
+ const headers = uploadRateLimitHeaders(rate);
5106
5126
  return earlyReject(new Response(
5107
5127
  JSON.stringify({ ok: false, error: "rate_limited", message: "Upload rate limit exceeded (60/hour). Try again later.", retry_after_ms: rate.retryAfterMs }),
5108
5128
  { status: 429, headers: { ...headers, "Content-Type": "application/json; charset=utf-8" } }, // #426 — legacy clients default to ISO-8859-1 without charset