@sleep2agi/commhub-server 0.9.0-preview.250 → 0.9.0-preview.251

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/build-info.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "schema": 1,
3
- "commit": "bdafec51e863f48faff870f6489a8a77579a42dd",
3
+ "commit": "5e4967928cf61365b6b0b1ed91aee293576a8250",
4
4
  "dirty": false,
5
- "built_at": "2026-10-31T19:42:20.517Z",
5
+ "built_at": "2026-10-31T20:01:25.689Z",
6
6
  "source": "ci"
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sleep2agi/commhub-server",
3
- "version": "0.9.0-preview.250",
3
+ "version": "0.9.0-preview.251",
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",
@@ -69,23 +69,25 @@ describe("#3271 从未取走过的过期计数", () => {
69
69
  });
70
70
 
71
71
  // ---- 派单侧硬闸(#3271)----
72
- import { neverConsumeGate, NEVER_CONSUME_LIMIT } from "./expiry-counters.js";
72
+ import { neverConsumeGate, NEVER_CONSUME_LIMIT, NEVER_CONSUME_STALE_MS } from "./expiry-counters.js";
73
73
 
74
74
  describe("#3271 派单侧硬闸:从未取走过的目标", () => {
75
- const counters = (n: number, alias = "ghost") => ({
75
+ const NOW = Date.parse("2026-10-31T10:00:00.000Z");
76
+ const counters = (n: number, alias = "ghost", lastAt = new Date(NOW - 60_000).toISOString()) => ({
76
77
  since: "2026-10-31T00:00:00.000Z",
77
78
  total: n,
78
79
  by_node: n > 0 ? { [alias]: n } : {},
80
+ last_at: n > 0 ? { [alias]: lastAt } : {},
79
81
  });
80
82
 
81
83
  test("窗口内 0–2 次 ⇒ 放行(一次两次可能是宿主重启,三次才是形态)", () => {
82
84
  for (const n of [0, 1, 2]) {
83
- expect(neverConsumeGate({ alias: "ghost", counters: counters(n), force: false, forceAllowed: true }).ok).toBe(true);
85
+ expect(neverConsumeGate({ alias: "ghost", counters: counters(n), force: false, forceAllowed: true, now: Date.parse("2026-10-31T10:00:00.000Z") }).ok).toBe(true);
84
86
  }
85
87
  });
86
88
 
87
89
  test("🔴 达到阈值 ⇒ 拒绝,且拒绝体给全(alias / expiries / window_since / 下一步)", () => {
88
- const r = neverConsumeGate({ alias: "ghost", counters: counters(NEVER_CONSUME_LIMIT), force: false, forceAllowed: true });
90
+ const r = neverConsumeGate({ alias: "ghost", counters: counters(NEVER_CONSUME_LIMIT), force: false, forceAllowed: true, now: Date.parse("2026-10-31T10:00:00.000Z") });
89
91
  expect(r.ok).toBe(false);
90
92
  if (r.ok) throw new Error("unreachable");
91
93
  expect(r.error).toBe("target_never_consumes");
@@ -96,16 +98,44 @@ describe("#3271 派单侧硬闸:从未取走过的目标", () => {
96
98
  });
97
99
 
98
100
  test("人令牌 + force ⇒ 放行(出口存在,但必须显式)", () => {
99
- expect(neverConsumeGate({ alias: "ghost", counters: counters(9), force: true, forceAllowed: true }).ok).toBe(true);
101
+ expect(neverConsumeGate({ alias: "ghost", counters: counters(9), force: true, forceAllowed: true, now: Date.parse("2026-10-31T10:00:00.000Z") }).ok).toBe(true);
100
102
  });
101
103
 
102
104
  test("🔴 节点令牌不能自己放行:force 传了也不算(forceAllowed=false)", () => {
103
- const r = neverConsumeGate({ alias: "ghost", counters: counters(9), force: true, forceAllowed: false });
105
+ const r = neverConsumeGate({ alias: "ghost", counters: counters(9), force: true, forceAllowed: false, now: Date.parse("2026-10-31T10:00:00.000Z") });
104
106
  expect(r.ok).toBe(false);
105
107
  });
106
108
 
107
109
  test("别的节点的计数不影响本目标(分桶不是总数)", () => {
108
- const c = { since: "s", total: 9, by_node: { other: 9 } };
109
- expect(neverConsumeGate({ alias: "ghost", counters: c, force: false, forceAllowed: true }).ok).toBe(true);
110
+ const c = { since: "s", total: 9, by_node: { other: 9 }, last_at: { other: new Date().toISOString() } };
111
+ expect(neverConsumeGate({ alias: "ghost", counters: c, force: false, forceAllowed: true, now: Date.parse("2026-10-31T10:00:00.000Z") }).ok).toBe(true);
112
+ });
113
+ });
114
+
115
+ describe("#3271 硬闸的时效:只数不衰减会把恢复了的节点永久拉黑", () => {
116
+ const NOW = Date.parse("2026-10-31T10:00:00.000Z");
117
+ const mk = (lastAtIso: string) => ({
118
+ since: "2026-10-31T00:00:00.000Z",
119
+ total: 5,
120
+ by_node: { ghost: 5 },
121
+ last_at: { ghost: lastAtIso },
122
+ });
123
+
124
+ test("最近一次是 1 分钟前 ⇒ 仍然拒(形态是新鲜的)", () => {
125
+ const r = neverConsumeGate({ alias: "ghost", counters: mk(new Date(NOW - 60_000).toISOString()), force: false, forceAllowed: true, now: NOW });
126
+ expect(r.ok).toBe(false);
127
+ });
128
+
129
+ test("🔴 最近一次超过 TTL ⇒ 放行(节点可能已恢复;计数仍留在读数里)", () => {
130
+ const r = neverConsumeGate({ alias: "ghost", counters: mk(new Date(NOW - NEVER_CONSUME_STALE_MS - 1).toISOString()), force: false, forceAllowed: true, now: NOW });
131
+ expect(r.ok).toBe(true);
132
+ });
133
+
134
+ test("读数里带 last_at —— 光有计数看不出「多久没犯了」", () => {
135
+ resetNeverConsumedExpiryCountersForTest(new Date(NOW));
136
+ noteNeverConsumedExpiry("ghost", NOW);
137
+ const c = neverConsumedExpiryCounters();
138
+ expect(c.last_at["ghost"]).toBe(new Date(NOW).toISOString());
139
+ expect(c.by_node["ghost"]).toBe(1);
110
140
  });
111
141
  });
@@ -23,25 +23,31 @@ export type NeverConsumedExpiryCounters = {
23
23
  total: number;
24
24
  /** 按节点分桶;键是 node alias(可读),值是计数。空桶不出现。 */
25
25
  by_node: Record<string, number>;
26
+ /** 每个节点最近一次「从未取走」的时刻(ISO)。**光有计数会永久拉黑一台恢复了的节点。** */
27
+ last_at: Record<string, string>;
26
28
  };
27
29
 
28
- const counters = new Map<string, number>();
30
+ type Bucket = { count: number; lastAt: number };
31
+ const counters = new Map<string, Bucket>();
29
32
  let since = new Date().toISOString();
30
33
 
31
34
  /** 记一次「过期且从未取走」。node 名用别名(人读),没有别名时退回 node id。 */
32
- export function noteNeverConsumedExpiry(node: string): void {
35
+ export function noteNeverConsumedExpiry(node: string, now = Date.now()): void {
33
36
  const key = node || "(unknown)";
34
- counters.set(key, (counters.get(key) ?? 0) + 1);
37
+ const prev = counters.get(key);
38
+ counters.set(key, { count: (prev?.count ?? 0) + 1, lastAt: now });
35
39
  }
36
40
 
37
41
  export function neverConsumedExpiryCounters(): NeverConsumedExpiryCounters {
38
42
  let total = 0;
39
43
  const by_node: Record<string, number> = {};
44
+ const last_at: Record<string, string> = {};
40
45
  for (const [k, v] of [...counters.entries()].sort(([a], [b]) => a.localeCompare(b))) {
41
- by_node[k] = v;
42
- total += v;
46
+ by_node[k] = v.count;
47
+ last_at[k] = new Date(v.lastAt).toISOString();
48
+ total += v.count;
43
49
  }
44
- return { since, total, by_node };
50
+ return { since, total, by_node, last_at };
45
51
  }
46
52
 
47
53
  /** 仅测试用:清零并重置窗口。 */
@@ -63,6 +69,8 @@ export function resetNeverConsumedExpiryCountersForTest(now = new Date()): void
63
69
  * ③ 拒绝体给全:alias / expiries / window_since / 下一步。只说 "refused" 会让调用方去猜。
64
70
  */
65
71
  export const NEVER_CONSUME_LIMIT = 3;
72
+ /** 「最近一次从未取走」超过这个时长 ⇒ 不再拒发(节点可能已经恢复;计数仍留在读数里)。 */
73
+ export const NEVER_CONSUME_STALE_MS = 2 * 60 * 60_000;
66
74
 
67
75
  export type NeverConsumeGate =
68
76
  | { ok: true }
@@ -75,10 +83,21 @@ export function neverConsumeGate(input: {
75
83
  /** 人令牌才能用 force;节点令牌传 false。 */
76
84
  forceAllowed: boolean;
77
85
  limit?: number;
86
+ /** 「最近一次」的时效:超过它就不再拒发(节点可能已经恢复)。 */
87
+ staleAfterMs?: number;
88
+ now?: number;
78
89
  }): NeverConsumeGate {
79
90
  const limit = input.limit ?? NEVER_CONSUME_LIMIT;
80
91
  const expiries = input.counters.by_node[input.alias] ?? 0;
81
92
  if (expiries < limit) return { ok: true };
93
+ // 2026-10-31 —— **只数不衰减会把恢复了的节点永久拉黑**。
94
+ // 实测的教训来自另一台机(TM中转运维):连「抑制了多少」这个数本身都在被环缓冲淘汰,
95
+ // 所以任何「累计」都只在它的窗口内可引用;这里把窗口写进判据:最近一次过期超过 TTL ⇒ 放行。
96
+ const lastAt = input.counters.last_at?.[input.alias];
97
+ if (lastAt) {
98
+ const age = (input.now ?? Date.now()) - Date.parse(lastAt);
99
+ if (Number.isFinite(age) && age > (input.staleAfterMs ?? NEVER_CONSUME_STALE_MS)) return { ok: true };
100
+ }
82
101
  if (input.force && input.forceAllowed) return { ok: true };
83
102
  return {
84
103
  ok: false,
@@ -298,13 +298,13 @@ describe.skipIf(!isProdMode)("#500 CR2 — HEAD /api/files/:file_id authorizatio
298
298
  // — check Content-Type so a future fallback rewrite (e.g. adding
299
299
  // "requested resource type: X") does not silently form an oracle
300
300
  // while HEAD still returns 200 from that page.
301
- expect(res.headers.get("content-type")?.toLowerCase()).toContain("application/json");
301
+ expect((res.headers.get("content-type") || "").toLowerCase().split(";")[0].trim()).toBe("application/json");
302
302
  });
303
303
 
304
304
  test("HEAD unknown file_id → 404 with same shape as cross-owner (no enumeration signal)", async () => {
305
305
  const res = await headAs(userAToken, "0123456789abcdef0123456789abcdef");
306
306
  expect(res.status).toBe(404);
307
- expect(res.headers.get("content-type")?.toLowerCase()).toContain("application/json");
307
+ expect((res.headers.get("content-type") || "").toLowerCase().split(";")[0].trim()).toBe("application/json");
308
308
  });
309
309
 
310
310
  test("HEAD anonymous → 401 (auth still required, symmetric with GET)", async () => {
@@ -666,7 +666,7 @@ describe("#473 anonymous /health — watchdog contract intact, no topology leak"
666
666
  test("anonymous /health does not leak build identity through headers", async () => {
667
667
  const res = await fetch(`${BASE}/health`);
668
668
  expect(res.status).toBe(200);
669
- expect(res.headers.get("content-type") || "").toContain("application/json");
669
+ expect((res.headers.get("content-type") || "").split(";")[0].trim()).toBe("application/json");
670
670
  // 正文里我们只给 build_identified;头里更不能给指纹
671
671
  const leaky = [...res.headers.keys()].filter((h) => /git|commit|build[-_]?(sha|id)/i.test(h));
672
672
  expect(leaky).toEqual([]);
@@ -23,7 +23,7 @@ test("a large JSON body is gzipped only when the client asked, and round-trips",
23
23
  expect(bytes.byteLength).toBeLessThan(big.length / 3);
24
24
  expect(Number(out!.headers.get("Content-Length"))).toBe(bytes.byteLength);
25
25
  expect(new TextDecoder().decode(Bun.gunzipSync(bytes))).toBe(big);
26
- expect(out!.headers.get("Content-Type")).toContain("application/json");
26
+ expect((out!.headers.get("Content-Type") || "").split(";")[0].trim()).toBe("application/json");
27
27
 
28
28
  const plain = json(big);
29
29
  expect(await maybeGzipResponse(reqWith(), plain)).toBe(plain); // untouched object
@@ -147,7 +147,7 @@ describe("#461 GET /events/network/:id — auth", () => {
147
147
  test("member user token → SSE stream with observer connected frame", async () => {
148
148
  const res = await fetch(`${BASE}/events/network/${memberNetworkId}`, { headers: auth(memberToken) });
149
149
  expect(res.status).toBe(200);
150
- expect(res.headers.get("content-type") || "").toContain("text/event-stream");
150
+ expect((res.headers.get("content-type") || "").split(";")[0].trim()).toBe("text/event-stream");
151
151
  const reader = res.body!.getReader();
152
152
  const connected = await readFrame(reader);
153
153
  expect(connected.type).toBe("connected");
@@ -226,7 +226,7 @@ describe("GET /events/users/me — Desktop user stream auth", () => {
226
226
  test("member utok → user stream connected frame keyed to authenticated user", async () => {
227
227
  const res = await fetch(`${BASE}/events/users/me?network_id=${encodeURIComponent(memberNetworkId)}`, { headers: auth(memberToken) });
228
228
  expect(res.status).toBe(200);
229
- expect(res.headers.get("content-type") || "").toContain("text/event-stream");
229
+ expect((res.headers.get("content-type") || "").split(";")[0].trim()).toBe("text/event-stream");
230
230
  const reader = res.body!.getReader();
231
231
  const connected = await readFrame(reader);
232
232
  expect(connected.type).toBe("connected");
@@ -25,7 +25,7 @@ describe("#695 fetch exceptions become JSON with the exception's own message", (
25
25
  try {
26
26
  const res = await fetch(`http://127.0.0.1:${server.port}/mcp`, { method: "POST", body: "{}" });
27
27
  expect(res.status).toBe(500);
28
- expect(res.headers.get("content-type") ?? "").toContain("application/json");
28
+ expect((res.headers.get("content-type") ?? "").split(";")[0].trim()).toBe("application/json");
29
29
  const json = await res.json() as { error: { code: number; message: string }; ok: boolean };
30
30
  expect(json.error.code).toBe(-32603);
31
31
  expect(json.error.message).toBe("boom-695-live");
@@ -17,6 +17,7 @@
17
17
  // 跑法:cd server && COMMHUB_DB=/tmp/x.db bun test src/task-expiry-notice-http.test.ts
18
18
 
19
19
  import { afterAll, beforeAll, beforeEach, describe, expect, test } from "bun:test";
20
+ import { resetNeverConsumedExpiryCountersForTest } from "./expiry-counters.js";
20
21
  import { mkdtempSync, rmSync } from "node:fs";
21
22
  import { tmpdir } from "node:os";
22
23
  import { join } from "node:path";
@@ -89,7 +90,10 @@ const until = async (cond: () => boolean, tries = 150) => { for (let k = 0; k <
89
90
  let seq = 0;
90
91
  /** 经 POST /api/task 派一条;返回 task_id。 */
91
92
  async function dispatch(token: string, to: string, extra: Record<string, unknown> = {}): Promise<string> {
92
- const r = await send(token, "POST", "/api/task", { alias: to, task: `expiry case ${stamp} #${++seq}`, network_id: NET, ...extra });
93
+ // 2026-10-31 —— 这里**故意**发 expired 任务(本文件测的就是过期通知),
94
+ // 所以同一目标很快就会攒到 ≥3 次「从未取走」。#3271 的硬闸会因此拒发(这是它的本意:
95
+ // 不让任务继续堆到一台从不消费的节点上)。测过期通知走的是**人工知情**的路径 ⇒ 带 force。
96
+ const r = await send(token, "POST", "/api/task", { alias: to, task: `expiry case ${stamp} #${++seq}`, network_id: NET, force: true, ...extra });
93
97
  expect(r.status).toBe(200);
94
98
  expect(r.body.ok).toBe(true);
95
99
  return r.body.task_id;
@@ -138,6 +142,10 @@ beforeAll(async () => {
138
142
  }, 30_000);
139
143
 
140
144
  beforeEach(() => {
145
+ // 2026-10-31 —— #3271 的硬闸是**进程级**计数:上一条用例攒下的「从未取走」会带到这里,
146
+ // 于是本文件的下一条用例第一次派发就被拒(我第一次只清在循环里,正是漏了这个)。
147
+ // 本文件测的是过期通知,不是那道闸 ⇒ 每条用例前清零。
148
+ resetNeverConsumedExpiryCountersForTest();
141
149
  // 每条用例自己的数据:上一条留下的开着的任务不许算进「前面还有几个」,也不许被这一次巡检过期。
142
150
  db.run("UPDATE tasks SET status = 'replied', completed_at = datetime('now') WHERE network_id = ?1 AND status IN ('created', 'delivered', 'acked', 'running')", [NET]);
143
151
  db.run("DELETE FROM inbox WHERE network_id = ?1 AND id LIKE 'exp_%'", [NET]);
@@ -268,7 +276,10 @@ describe("#500 child task expires", () => {
268
276
  describe("#500 one notice per (sender, target) per patrol pass", () => {
269
277
  test("5 expiring to the same target → one summarized notice listing all 5", async () => {
270
278
  const ids: string[] = [];
271
- for (let i = 0; i < 5; i++) ids.push(await dispatch(nodes.sender.token, nodes.target.alias));
279
+ // 2026-10-31 —— 这里连发 5 条给同一目标,会攒到 #3271 的硬闸阈值(≥3 次从未取走)。
280
+ // 而本文件测的是**过期通知的合并**,不是那道闸;闸自己的行为在 node-health-dispatch-http 与
281
+ // expiry-counters.test 里钉着。⇒ 每次派发后清一次进程内计数,把闸本意地旁路掉(并写明理由)。
282
+ for (let i = 0; i < 5; i++) { ids.push(await dispatch(nodes.sender.token, nodes.target.alias)); resetNeverConsumedExpiryCountersForTest(); }
272
283
  // 再来一条派给另一个目标:那是另一组,单独一条。
273
284
  const elsewhere = await dispatch(nodes.sender.token, nodes.other.alias);
274
285
  for (const id of [...ids, elsewhere]) backdate(id);