@sleep2agi/commhub-server 0.9.0-preview.254 → 0.9.0-preview.256

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,8 +1,7 @@
1
1
  {
2
2
  "schema": 1,
3
- "commit": "8955cf5352f9d50467c5c16a84f384fc60ce3b40",
3
+ "commit": "48dfcef3d19bda8f1b70090fb55d763f047868df",
4
4
  "dirty": false,
5
- "built_at": "2026-10-31T22:31:27.402Z",
6
- "source": "git",
7
- "event_sha": "3cd0931c7c1d45d5a1050613ea13fd68c622f162"
5
+ "built_at": "2026-10-31T22:51:35.425Z",
6
+ "source": "git"
8
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sleep2agi/commhub-server",
3
- "version": "0.9.0-preview.254",
3
+ "version": "0.9.0-preview.256",
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",
@@ -112,6 +112,43 @@ describe("#3271 派单侧硬闸:从未取走过的目标", () => {
112
112
  });
113
113
  });
114
114
 
115
+ describe("#3271 证据的生命期必须 ≥ 故障的生命期(进程内计数器不够)", () => {
116
+ const NOW = Date.parse("2026-10-31T10:00:00.000Z");
117
+ const empty = { since: "2026-10-31T10:00:00.000Z", total: 0, by_node: {}, last_at: {} };
118
+
119
+ // 🔴 这条是 2026-10-31 生产实测的 must-fire:
120
+ // `.254` 部署(22:39)后,我给一台**已经 10 次到死没被取走**的节点派单,
121
+ // 闸返回 ok:true —— 因为计数器随进程重启归零,而故障是以「周」计的。
122
+ test("🔴 内存计数为空,但 tasks 表里有 3 条历史 ⇒ 必须拒绝", () => {
123
+ const r = neverConsumeGate({
124
+ alias: "ghost", counters: empty, force: false, forceAllowed: true, now: NOW,
125
+ persistent: { expiries: 3, last_at: new Date(NOW - 60_000).toISOString().replace("T", " ").slice(0, 19) },
126
+ });
127
+ expect(r.ok).toBe(false);
128
+ if (r.ok) throw new Error("unreachable");
129
+ expect(r.expiries).toBe(3);
130
+ });
131
+
132
+ test("两个来源取**并集**(内存 2 + 表里 3 ⇒ 按 3 判,不是相加也不是取小)", () => {
133
+ const counters = { since: "s", total: 2, by_node: { ghost: 2 }, last_at: { ghost: new Date(NOW - 60_000).toISOString() } };
134
+ const r = neverConsumeGate({
135
+ alias: "ghost", counters, force: false, forceAllowed: true, now: NOW,
136
+ persistent: { expiries: 3, last_at: new Date(NOW - 60_000).toISOString().replace("T", " ").slice(0, 19) },
137
+ });
138
+ expect(r.ok).toBe(false);
139
+ if (r.ok) throw new Error("unreachable");
140
+ expect(r.expiries).toBe(3);
141
+ });
142
+
143
+ test("表里的历史很旧(超过时效)⇒ 放行:节点可能已经恢复", () => {
144
+ const r = neverConsumeGate({
145
+ alias: "ghost", counters: empty, force: false, forceAllowed: true, now: NOW,
146
+ persistent: { expiries: 9, last_at: "2026-10-20T00:00:00" },
147
+ });
148
+ expect(r.ok).toBe(true);
149
+ });
150
+ });
151
+
115
152
  describe("#3271 硬闸的时效:只数不衰减会把恢复了的节点永久拉黑", () => {
116
153
  const NOW = Date.parse("2026-10-31T10:00:00.000Z");
117
154
  const mk = (lastAtIso: string) => ({
@@ -72,6 +72,46 @@ export const NEVER_CONSUME_LIMIT = 3;
72
72
  /** 「最近一次从未取走」超过这个时长 ⇒ 不再拒发(节点可能已经恢复;计数仍留在读数里)。 */
73
73
  export const NEVER_CONSUME_STALE_MS = 2 * 60 * 60_000;
74
74
 
75
+ /**
76
+ * #3271 🔴 2026-10-31 修 —— 这道闸原来**只读进程内计数器**,而计数器随部署归零。
77
+ *
78
+ * 实测打脸:`.254` 部署(22:39)之后我给 TM官网运维 派了一条自检任务,
79
+ * 它明明已经 10 次「到死没被取走」,闸却 `ok:true` 放行了 —— 因为计数器在重启时被清空。
80
+ * ⇒ **证据的生命期比故障短**:故障以「周」计,计数器以「本次进程」计。
81
+ * 一条只在本次进程内有效的判据,会被每一次发版重置,而发版比故障频繁得多。
82
+ *
83
+ * 所以判据必须有一个**持久**来源:tasks 表里已经写着每一条过期的 `status='expired'` 与
84
+ * `consumed_at IS NULL` —— 那是过期发生时就落库的事实,不随重启消失。
85
+ *
86
+ * 两个来源**取并集**(不是二选一):
87
+ * · 进程内计数器:本次进程内发生的最新鲜的那几条(可能在 tasks 行写之前就有)
88
+ * · tasks 表:跨重启的历史(窗口由调用方给,默认 7 天 —— 与「节点可能恢复」同一个取舍)
89
+ */
90
+ export interface PersistentExpiryEvidence { expiries: number; last_at: string | null }
91
+
92
+ export const NEVER_CONSUME_LOOKBACK_MS = 7 * 24 * 60 * 60_000;
93
+
94
+ export function persistentNeverConsumedExpiries(
95
+ db: { get<T = any>(sql: string, ...params: any[]): T | null },
96
+ alias: string,
97
+ networkId: string | null,
98
+ opts: { now?: number; lookbackMs?: number } = {},
99
+ ): PersistentExpiryEvidence {
100
+ const since = new Date((opts.now ?? Date.now()) - (opts.lookbackMs ?? NEVER_CONSUME_LOOKBACK_MS)).toISOString().replace("T", " ").slice(0, 19);
101
+ const row = networkId
102
+ ? db.get<{ n: number; last: string | null }>(
103
+ `SELECT COUNT(*) AS n, MAX(created_at) AS last FROM tasks
104
+ WHERE to_name = ?1 AND network_id = ?2 AND status = 'expired' AND consumed_at IS NULL
105
+ AND created_at >= ?3`,
106
+ alias, networkId, since)
107
+ : db.get<{ n: number; last: string | null }>(
108
+ `SELECT COUNT(*) AS n, MAX(created_at) AS last FROM tasks
109
+ WHERE to_name = ?1 AND status = 'expired' AND consumed_at IS NULL
110
+ AND created_at >= ?2`,
111
+ alias, since);
112
+ return { expiries: Number(row?.n ?? 0), last_at: row?.last ?? null };
113
+ }
114
+
75
115
  export type NeverConsumeGate =
76
116
  | { ok: true }
77
117
  | { ok: false; error: "target_never_consumes"; alias: string; expiries: number; window_since: string; message: string };
@@ -86,14 +126,21 @@ export function neverConsumeGate(input: {
86
126
  /** 「最近一次」的时效:超过它就不再拒发(节点可能已经恢复)。 */
87
127
  staleAfterMs?: number;
88
128
  now?: number;
129
+ /** tasks 表里的历史(跨重启)。与进程内计数器**取并集**,见 persistentNeverConsumedExpiries 的注释。 */
130
+ persistent?: PersistentExpiryEvidence;
89
131
  }): NeverConsumeGate {
90
132
  const limit = input.limit ?? NEVER_CONSUME_LIMIT;
91
- const expiries = input.counters.by_node[input.alias] ?? 0;
133
+ const fromMemory = input.counters.by_node[input.alias] ?? 0;
134
+ const fromDb = input.persistent?.expiries ?? 0;
135
+ const expiries = Math.max(fromMemory, fromDb);
92
136
  if (expiries < limit) return { ok: true };
93
137
  // 2026-10-31 —— **只数不衰减会把恢复了的节点永久拉黑**。
94
138
  // 实测的教训来自另一台机(TM中转运维):连「抑制了多少」这个数本身都在被环缓冲淘汰,
95
139
  // 所以任何「累计」都只在它的窗口内可引用;这里把窗口写进判据:最近一次过期超过 TTL ⇒ 放行。
96
- const lastAt = input.counters.last_at?.[input.alias];
140
+ const lastAt = [input.counters.last_at?.[input.alias], input.persistent?.last_at ?? undefined]
141
+ .filter((x): x is string => typeof x === "string")
142
+ .sort()
143
+ .pop();
97
144
  if (lastAt) {
98
145
  const age = (input.now ?? Date.now()) - Date.parse(lastAt);
99
146
  if (Number.isFinite(age) && age > (input.staleAfterMs ?? NEVER_CONSUME_STALE_MS)) return { ok: true };
@@ -50,6 +50,8 @@ export const PUBLIC_HEALTH_KEY_READERS: Readonly<Record<string, AnonReaderEntry>
50
50
  // ⇒ 聚合走匿名投影;by_node 仍是拓扑,不给。
51
51
  task_expiries_never_consumed_total: { reader: "operator", why: "运维/agent 判断「派单硬闸有没有真的 fire 过」;只有总数,不含节点名" },
52
52
  counters_since: { reader: "operator", why: "上一条的窗口起点:计数器随重启归零,只有总数时「刚重启」与「一次都没发生」同值" },
53
+ // #3193 子卡 —— 与上一条同形:拒绝次数的总数给匿名,by_reason 明细留在鉴权投影。
54
+ task_rejections_total: { reader: "operator", why: "运维/agent 判断「今天拒了多少」而不必翻日志(日志轮转后 grep 会静默 0)" },
53
55
  auth: { reader: "cli", why: "客户端据此决定登录方式" },
54
56
  security: { reader: "cli", why: "客户端据此提示是否需要 TLS/密钥配置" },
55
57
  tmux: { reader: "cli", why: "共存 TUI 的前置检查" },
@@ -266,6 +266,22 @@ describe("#473 anonymous /health — watchdog contract intact, no topology leak"
266
266
  expect(Object.keys(agg.by_node)).toContain("unread-probe-node");
267
267
  });
268
268
 
269
+ // #3193 子卡 —— 拒绝次数的**总数**也必须匿名可读(明细 by_reason 仍留鉴权投影)。
270
+ test("#3193 拒绝计数:匿名给总数,by_reason 留鉴权", async () => {
271
+ const { PUBLIC_HEALTH_KEYS } = await import("./server.js");
272
+ expect(PUBLIC_HEALTH_KEYS.has("task_rejections_total")).toBe(true);
273
+ expect(PUBLIC_HEALTH_KEYS.has("counters")).toBe(false); // 明细不外泄
274
+ const { recordTaskRejection, taskRejectionCounters, resetTaskRejectionCounters } = await import("./rejection-counters.js");
275
+ resetTaskRejectionCounters();
276
+ recordTaskRejection(401, "invalid_token");
277
+ recordTaskRejection(401, "invalid_token");
278
+ recordTaskRejection(403, "forbidden");
279
+ const c = taskRejectionCounters();
280
+ expect(c.total).toBe(3);
281
+ expect(c.by_reason["401:invalid_token"]).toBe(2);
282
+ expect(c.by_reason["403:forbidden"]).toBe(1);
283
+ });
284
+
269
285
  // 2026-10-31 —— 出口清单里「before_route_table」那一行原本 pinned_by 为空(= 缺口)。
270
286
  // 补上它的钉:未匹配的 /api/* 在路由表之前就 404,**不经过 handler,也不计数**。
271
287
  // 这一条同时是「清单要能被一次坏输入打出来」的实例(对方那句)。
package/src/server.ts CHANGED
@@ -122,7 +122,7 @@ import { createProductionSideThreadTransport } from "./side-thread-production.js
122
122
  import { parseHubTimestamp } from "./hub-timestamp";
123
123
  import { logTaskRejection } from "./task-rejection-log.js";
124
124
  import { taskRejectionCounters } from "./rejection-counters.js";
125
- import { neverConsumedExpiryCounters, noteNeverConsumedExpiry, neverConsumeGate } from "./expiry-counters.js";
125
+ import { neverConsumedExpiryCounters, noteNeverConsumedExpiry, neverConsumeGate, persistentNeverConsumedExpiries } from "./expiry-counters.js";
126
126
  import { legacyLicenseField, licenseStateOf } from "./license-state.js";
127
127
  import { AVATAR_FIELD, avatarUrl, inspectAvatarImage, isMultipart, isValidAvatarVersion, MAX_AVATAR_BYTES, MAX_AVATAR_STORAGE_BYTES } from "./user-avatar-image.js";
128
128
 
@@ -1057,6 +1057,8 @@ export const PUBLIC_HEALTH_KEYS: ReadonlySet<string> = new Set([
1057
1057
  // #3271 —— 「到死没被取走」的**总数**(聚合,不含 by_node:节点名是拓扑)。
1058
1058
  // 配 counters_since 一起读:只有总数时,「进程刚重启」与「一次都没发生」同值。
1059
1059
  "task_expiries_never_consumed_total", "counters_since",
1060
+ // 同一个理由:拒绝次数的**总数**是规模读数;by_reason 的明细留在鉴权投影。
1061
+ "task_rejections_total",
1060
1062
  // 事件循环停顿是**一个对象**(event_loop: {max_gap_ms, recent_stalls,…}),
1061
1063
  // 不是我原先以为的三个顶层键 —— 死条目测试当场抓到了这一点。
1062
1064
  "event_loop",
@@ -1275,6 +1277,7 @@ export const HEALTH_FIELD_META: Readonly<Record<string, HealthFieldMeta>> = {
1275
1277
  event_loop: { class: "gauge", granularity: "cumulative" },
1276
1278
  // #3271 —— 聚合计数:规模/强度,不含拓扑(by_node 留在鉴权投影里)。
1277
1279
  task_expiries_never_consumed_total: { class: "gauge", granularity: "cumulative" },
1280
+ task_rejections_total: { class: "gauge", granularity: "cumulative" },
1278
1281
  counters_since: { class: "gauge", granularity: "label" },
1279
1282
  auth: { class: "gauge", granularity: "label" },
1280
1283
  security: { class: "gauge", granularity: "label" },
@@ -3847,6 +3850,8 @@ return Bun.serve({
3847
3850
  // ⇒ 聚合值走匿名投影:**只给总数与窗口,不给 by_node**(节点名是拓扑,计数不是)。
3848
3851
  // 这也与 sessions_count 同一条取舍:规模可以公开,明细不行。
3849
3852
  task_expiries_never_consumed_total: neverConsumedExpiryCounters().total,
3853
+ // #3193 子卡 —— 拒绝计数同一个缺口:原来只在鉴权投影里。聚合给匿名,by_reason 留鉴权。
3854
+ task_rejections_total: taskRejectionCounters().total,
3850
3855
  // 窗口的另一端:计数器随进程重启归零,而「归零」与「没有发生」同值 ⇒ 必须配起点。
3851
3856
  counters_since: startedAtIso,
3852
3857
  // #496 — public, stable capability data. Dashboard upload proxies
@@ -5860,6 +5865,8 @@ return Bun.serve({
5860
5865
  counters: neverConsumedExpiryCounters(),
5861
5866
  force: body.force === true,
5862
5867
  forceAllowed: !restAuth?.networkId,
5868
+ // #3271 —— 与 MCP 面同一份持久证据。
5869
+ persistent: persistentNeverConsumedExpiries(db, targetAlias, taskNetId ?? null),
5863
5870
  });
5864
5871
  if (!gate.ok) return reject(withCors(req, Response.json(gate, { status: 409 })));
5865
5872
  }
@@ -210,7 +210,11 @@ describe("task consumed_at identity and lifecycle", () => {
210
210
  expect(queued?.task).toBe(content);
211
211
  expect(queued?.last_seen_at).toBe(before?.last_seen_at);
212
212
 
213
- expect((await call(nodeTools.ack_inbox, { alias: NODE_A, message_id: taskId })).ok).toBe(true);
213
+ // #3275 批次 1 —— 同变量口径:断言的对象就是这次调用的返回值(不是「附近的某个断言」)。
214
+ // ack_inbox 成功路径的键集是**闭合的两态**:成功 {ok},失败 {ok, error}。
215
+ const acked = await call(nodeTools.ack_inbox, { alias: NODE_A, message_id: taskId });
216
+ expect(Object.keys(acked).sort()).toEqual(["ok"]);
217
+ expect(acked.ok).toBe(true);
214
218
  expect(runtimeSubmittedAt(taskId)).toBeNull();
215
219
  expect(consumedAt(taskId)).toBeNull();
216
220
  });
package/src/tools.ts CHANGED
@@ -112,7 +112,7 @@ import { parseHubTimestamp } from "./hub-timestamp";
112
112
  import { noteTerminalResultRead, purgeLogsResultNow, sweepNodeRequestContent } from "./node-request-retention.js";
113
113
  import { listTaskLateReplies } from "./task-late-replies.js";
114
114
  import { pollPacer } from "./poll-pacing.js";
115
- import { neverConsumedExpiryCounters, neverConsumeGate } from "./expiry-counters.js";
115
+ import { neverConsumedExpiryCounters, neverConsumeGate, persistentNeverConsumedExpiries } from "./expiry-counters.js";
116
116
  import { auditDepartment, createDepartment, deleteDepartment, listDepartments, setAgentDepartment, updateDepartment } from "./departments.js";
117
117
 
118
118
  function ts(): string {
@@ -2278,6 +2278,8 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
2278
2278
  counters: neverConsumedExpiryCounters(),
2279
2279
  force: force === true,
2280
2280
  forceAllowed: !callerTokenIsNetwork,
2281
+ // #3271 —— 进程内计数器随部署归零,所以必须并上 tasks 表里的历史(跨重启)。
2282
+ persistent: persistentNeverConsumedExpiries(db, targetAlias, effectiveNetId ?? null),
2281
2283
  });
2282
2284
  if (!gate.ok) return { content: [{ type: "text" as const, text: JSON.stringify(gate) }] };
2283
2285
  }