@sleep2agi/commhub-server 0.9.0-preview.210 → 0.9.0-preview.211

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.210",
3
+ "version": "0.9.0-preview.211",
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",
@@ -75,13 +75,20 @@ test("buckets older than the retention are dropped", () => {
75
75
  test("p95 comes from the histogram: close to the true value and never above max", () => {
76
76
  __resetRouteTimingForTest();
77
77
  const now = 4_000_000_000;
78
+ // 🔴 时长是 recordRouteTiming **内部**用 performance.now() 算的(`performance.now() - started`),
79
+ // 外部给不了固定值。两个坑都踩过:
80
+ // ① `at(1)`(每次都取当前时钟)—— 正常,但 CI 负载高时「取样 → 调用」之间可能被抢占,
81
+ // 1ms 的样本变成 6ms+(实测 6.4 / 6.9);
82
+ // ② 循环外取一次 base 再 `base - 1` —— 时长随循环进度单调增长,96 次后 7ms+,更糟。
83
+ // 这条用例真正钉的是**分桶位置**(96 个快样本 vs 4 个 200ms),不是「精确等于 1ms」,
84
+ // 所以上界放到快带内部(<150),仍能与 200ms 的慢带明确区分。
78
85
  // 96 fast (~1 ms) and 4 slow (~200 ms): p95 (the 96th of 100, same rank as the old ring's
79
86
  // sorted[floor(n·0.95)]) must be in the fast band, max in the slow band.
80
87
  for (let i = 0; i < 96; i++) recordRouteTiming(req("/api/p"), at(1), res(), now);
81
88
  for (let i = 0; i < 4; i++) recordRouteTiming(req("/api/p"), at(200), res(), now);
82
89
  const r = routeStats(60_000, now).routes[0];
83
90
  expect(r.p95_ms).toBeGreaterThanOrEqual(1);
84
- expect(r.p95_ms).toBeLessThan(5);
91
+ expect(r.p95_ms).toBeLessThan(150); // 快带内即可(见注释:精确到 1ms 不是本用例的性质)
85
92
  expect(r.max_ms).toBeGreaterThanOrEqual(200);
86
93
  __resetRouteTimingForTest();
87
94
  recordRouteTiming(req("/api/q"), at(3), res(), now);
@@ -389,3 +389,44 @@ describe("provenance: an Agent's schedule never passes as a person's", () => {
389
389
  expect(replyRow(hr.body.taskId)?.session_name).toBe(`sa_boss_${stamp}`); // the person's unread, as before
390
390
  });
391
391
  });
392
+
393
+ // #2935 —— 「周期比单轮工作耗时短」的排程会**永久 skip**:退避只会让它更稀疏,追不上。
394
+ // 以前没有任何一处给出「这个排程每轮实际跑多久」,于是只能靠人翻 scheduled_task_runs。
395
+ // 这里只报数,不改调度行为:observed_run_seconds_p50 / period_shorter_than_run / suggested_every_seconds。
396
+ describe("#2935 排程周期诊断", () => {
397
+ test("周期短于实测单轮耗时时,列表里直接标出来并给建议值", async () => {
398
+ const c = await mcp(node.a.token, "schedule_create", {
399
+ name: `diag-${stamp}`, task: "t", target_node_id: node.a.id,
400
+ schedule: { type: "interval", every_seconds: 180 }, timezone: "Asia/Shanghai",
401
+ });
402
+ expect(c.ok).toBe(true);
403
+ const id = c.schedule.schedule_id;
404
+ // 造 3 条「一轮跑了 600 秒」的已完成 run(中位数 600s > 周期 180s)。
405
+ // scheduled_for 必须每行不同(表上有唯一约束);时间戳在 JS 里算好再传字面量 ——
406
+ // SQL 里写 `datetime('now','-'||?||' minute')` 这种拼接适配层翻译不了,
407
+ // PostgreSQL 会报 `function datetime(unknown, text) does not exist`(PG 梯形套件实测)。
408
+ const hubTs = (msAgo: number) => new Date(Date.now() - msAgo).toISOString().slice(0, 19).replace("T", " ");
409
+ for (let i = 0; i < 3; i++) {
410
+ const minsAgo = i * 20 + 20;
411
+ db.run(`INSERT INTO scheduled_task_runs (run_id, schedule_id, network_id, scheduled_for, status, created_at, completed_at)
412
+ VALUES (?1, ?2, ?3, ?4, 'replied', ?5, ?4)`,
413
+ [`srun_diag_${stamp}_${i}`, id, net, hubTs(minsAgo * 60_000), hubTs((minsAgo + 10) * 60_000)]);
414
+ }
415
+ const l = await mcp(node.a.token, "schedule_list");
416
+ const row = l.schedules.find((x: any) => x.schedule_id === id);
417
+ expect(row.observed_run_seconds_p50).toBe(600);
418
+ expect(row.period_shorter_than_run).toBe(true);
419
+ expect(row.suggested_every_seconds).toBe(600);
420
+ });
421
+
422
+ test("样本不足 3 条时不判断(p50 / flag 均为 null)", async () => {
423
+ const c = await mcp(node.a.token, "schedule_create", {
424
+ name: `diag2-${stamp}`, task: "t", target_node_id: node.a.id,
425
+ schedule: { type: "interval", every_seconds: 180 }, timezone: "Asia/Shanghai",
426
+ });
427
+ const l = await mcp(node.a.token, "schedule_list");
428
+ const row = l.schedules.find((x: any) => x.schedule_id === c.schedule.schedule_id);
429
+ expect(row.observed_run_seconds_p50).toBeNull();
430
+ expect(row.period_shorter_than_run).toBeNull();
431
+ });
432
+ });
@@ -86,7 +86,67 @@ export function agentListSchedules(id: NodeIdentity, status?: string): AgentSche
86
86
  let sql = `SELECT ${SCHEDULED_TASK_STORAGE_SELECT} FROM scheduled_tasks WHERE network_id = ?1 AND (target_node_id = ?2 OR created_by_node_id = ?2)`;
87
87
  if (status) { sql += " AND status = ?3"; params.push(status); }
88
88
  sql += " ORDER BY updated_at DESC LIMIT 200";
89
- return { ok: true, schedules: db.all<ScheduledRow>(sql, ...params).map(decodeRowForAgent) };
89
+ const rows = db.all<ScheduledRow>(sql, ...params).map(decodeRowForAgent);
90
+ // #2935 —— 「周期比单轮工作耗时短」的排程会**永久 skip**:退避只会让它更稀疏,追不上。
91
+ // 数据是现成的(scheduled_task_runs 的 completed_at - created_at),只是以前没人给出来。
92
+ // 这里只**报数**,不改任何调度行为。
93
+ for (const row of rows) {
94
+ const scheduleId = String((row as Record<string, unknown>).schedule_id ?? "");
95
+ if (!scheduleId) continue;
96
+ const period = intervalSecondsOf(row);
97
+ const p50 = medianRunSeconds(scheduleId);
98
+ const r = row as Record<string, unknown>;
99
+ r.observed_run_seconds_p50 = p50;
100
+ if (period !== null && p50 !== null) {
101
+ r.period_shorter_than_run = period < p50;
102
+ r.suggested_every_seconds = period < p50 ? Math.max(period, Math.round(p50)) : null;
103
+ } else {
104
+ r.period_shorter_than_run = null;
105
+ r.suggested_every_seconds = null;
106
+ }
107
+ }
108
+ return { ok: true, schedules: rows };
109
+ }
110
+
111
+ /** 从 schedule_json 里取 interval 秒数;非 interval 类型返回 null。 */
112
+ function intervalSecondsOf(row: unknown): number | null {
113
+ const spec = (row as Record<string, unknown>)?.schedule;
114
+ const m = /"every_seconds"\s*:\s*(\d+)/.exec(JSON.stringify(spec ?? ""));
115
+ return m ? Number(m[1]) : null;
116
+ }
117
+
118
+ /**
119
+ * 近 7 天该排程「完成一轮」耗时的中位数(秒)。样本 < 3 返回 null(不够判断)。
120
+ *
121
+ * 🔴 不在 SQL 里算时长:`julianday()` 是 SQLite 专有,PostgreSQL 没有。
122
+ * test2123-hub-postgres-ladder 实测报错:`PG: function datetime(unknown, text) does not exist`。
123
+ * 两列都是 Hub 的 TEXT UTC 时间戳,取回来在 JS 里减最稳 —— 两边方言都不用碰。
124
+ */
125
+ function medianRunSeconds(scheduleId: string): number | null {
126
+ const parse = (t: string | null): number | null => {
127
+ if (!t) return null;
128
+ const iso = /[zZ]|[+-]\d\d:?\d\d$/.test(t) ? t : `${t.replace(" ", "T")}Z`;
129
+ const ms = Date.parse(iso);
130
+ return Number.isFinite(ms) ? ms : null;
131
+ };
132
+ const rows = db.all<{ created_at: string | null; completed_at: string | null }>(
133
+ `SELECT created_at, completed_at FROM scheduled_task_runs
134
+ WHERE schedule_id = ?1 AND status = 'replied' AND completed_at IS NOT NULL
135
+ AND created_at >= datetime('now','-7 day')
136
+ ORDER BY created_at DESC LIMIT 200`,
137
+ scheduleId,
138
+ );
139
+ const secs = rows
140
+ .map((r) => {
141
+ const a = parse(r.created_at), b = parse(r.completed_at);
142
+ return a === null || b === null ? null : (b - a) / 1000;
143
+ })
144
+ .filter((n): n is number => n !== null && Number.isFinite(n) && n >= 0)
145
+ .sort((x, y) => x - y);
146
+ if (secs.length < 3) return null;
147
+ const mid = Math.floor(secs.length / 2);
148
+ const median = secs.length % 2 ? secs[mid] : (secs[mid - 1] + secs[mid]) / 2;
149
+ return Math.round(median);
90
150
  }
91
151
 
92
152
  export function agentGetSchedule(id: NodeIdentity, scheduleId: string): AgentScheduleResult {
@@ -255,15 +255,40 @@ export function applyFailureBackoff(scheduleId: string, now = new Date()): { str
255
255
  * · 与 `no_change_backoff=1` 的排程互斥(那套逻辑自己拥有 backoff_* 三列)。
256
256
  */
257
257
  const NO_PROGRESS_CODES = ["previous_run_active", "target_offline"] as const;
258
+
259
+ /**
260
+ * #2935 —— 「目标根本不会接活」的**失败**码,也要按 no-progress 退避,而不是普通失败退避。
261
+ *
262
+ * 生产实测(2026-10-30,近 7 天):
263
+ *
264
+ * failed node_degraded 2391 其中 TMA云盘鲸 1388 · TMA云鲸 981
265
+ * 「节点 X 处于降级状态(TUI 会话不在),任务不会被执行,已拒绝派发」
266
+ * failed target_node_not_found 1166 「The bound node no longer exists in this network」
267
+ *
268
+ * 这两类不是「上游额度打满」那种会自愈的失败:
269
+ * · `node_degraded` 的节点已经离线好几天(TMA云盘鲸/云鲸 自 10-27 起没心跳),
270
+ * 它的恢复时间是「小时/天」级,不是「下一次 180 秒」级;
271
+ * · `target_node_not_found` 更彻底 —— 目标行已经不存在,**永远不可能成功**。
272
+ *
273
+ * 而它们走的是 `applyFailureBackoff`(上限 1 小时、且要求「连续」失败,被任何一次成功打断就清零),
274
+ * 于是 `every=180` 的排程在目标永久不可用的情况下依然每小时烧掉 20 次派发。
275
+ *
276
+ * 这里只把它们并进「无进展」链(上限 2 小时),**不暂停、不改谁来决定暂停**。
277
+ */
278
+ const NO_PROGRESS_FAILED_CODES = ["node_degraded", "target_node_not_found"] as const;
258
279
  /** 统计窗口:看最近多少次 run 里同因跳过出现了几次(默认 10)。 */
259
280
  const NO_PROGRESS_WINDOW = 10;
260
- export type NoProgressCause = (typeof NO_PROGRESS_CODES)[number];
281
+ export type NoProgressCause = (typeof NO_PROGRESS_CODES)[number] | (typeof NO_PROGRESS_FAILED_CODES)[number];
261
282
 
262
283
  function noProgressFromRuns(runs: Array<{ status: string; error_code: string | null }>): { cause: NoProgressCause | null; streak: number } {
263
284
  const first = runs[0];
264
285
  if (!first) return { cause: null, streak: 0 };
265
286
  let cause: NoProgressCause | null = null;
266
- if (first.status === "failed") cause = null; // 由 applyFailureBackoff 负责,避免两套逻辑抢同一列
287
+ if (first.status === "failed") {
288
+ // 默认交给 applyFailureBackoff;但「目标根本不会接活」的两类并进来(见上面注释)。
289
+ const code = first.error_code ?? "";
290
+ cause = (NO_PROGRESS_FAILED_CODES as readonly string[]).includes(code) ? (code as unknown as NoProgressCause) : null;
291
+ }
267
292
  else if (first.status === "skipped" && (NO_PROGRESS_CODES as readonly string[]).includes(first.error_code ?? "")) {
268
293
  cause = first.error_code as NoProgressCause;
269
294
  }
@@ -277,7 +302,9 @@ function noProgressFromRuns(runs: Array<{ status: string; error_code: string | n
277
302
  const window = runs.slice(0, NO_PROGRESS_WINDOW);
278
303
  let streak = 0;
279
304
  for (const r of window) {
280
- if (r.status === "skipped" && r.error_code === cause) streak++;
305
+ // #2935 —— failed 也计入:node_degraded / target_node_not_found 的 run 状态是 `failed`,
306
+ // 只数 `skipped` 会让它们永远攒不到阈值(改了分类却没改计数口径 = 等于没改)。
307
+ if ((r.status === "skipped" || r.status === "failed") && r.error_code === cause) streak++;
281
308
  }
282
309
  return { cause, streak };
283
310
  }
@@ -331,7 +358,9 @@ export function applyNoProgressBackoff(scheduleId: string, now = new Date()): {
331
358
  // target_offline —— 目标连续 6 次不在(按 180s 基底已是 18 分钟),
332
359
  // 再用 3 分钟一次的节奏去敲没有意义;2 小时一次仍能及时接住它回来。
333
360
  // 判据:#2622「同类原因日增量 ≤20」——180s 基底配 2 小时上限 ⇒ 12 次/天。
334
- const cap = cause === "target_offline" ? 7200 : 1800;
361
+ // target_offline / node_degraded / target_node_not_found 都是「目标不接活」的形状,
362
+ // 恢复是小时/天级 ⇒ 统一用 2 小时上限。previous_run_active 仍用 30 分钟。
363
+ const cap = cause === "previous_run_active" ? 1800 : 7200;
335
364
  if (streak < from) { restore(); return null; }
336
365
 
337
366
  const effective = Math.min(cap, base * 2 ** Math.min(streak - from + 1, 5));
@@ -369,9 +398,28 @@ export function failureSummary(scheduleId: string): { consecutive_failures: numb
369
398
  setScheduledRunTerminalHook((scheduleId, status) => {
370
399
  if (status === "failed") evaluateScheduleFailures(scheduleId);
371
400
  // #2622 —— 成功一次就把间隔恢复原样;失败则按连续失败次数放大间隔。
401
+ //
402
+ // #2935 —— 但「目标根本不会接活」的失败码(node_degraded / target_node_not_found)
403
+ // 不走失败退避:它们的恢复是小时/天级,用 1 小时上限 + 「连续失败」判据等于每 3 分钟继续烧。
404
+ // 这两类改走 no-progress 链(2 小时上限),与 skipped 的 target_offline 同一形状。
372
405
  try {
373
- applyFailureBackoff(scheduleId);
406
+ if (isNoProgressFailedCode(lastRunErrorCode(scheduleId))) applyNoProgressBackoff(scheduleId);
407
+ else applyFailureBackoff(scheduleId);
374
408
  } catch (e: any) {
375
409
  console.error(`[scheduled-tasks] failure backoff failed schedule=${scheduleId}: ${e?.message || e}`);
376
410
  }
377
411
  });
412
+
413
+ function isNoProgressFailedCode(code: string | null): boolean {
414
+ return !!code && (NO_PROGRESS_FAILED_CODES as readonly string[]).includes(code);
415
+ }
416
+
417
+ /** 最近一条 run 的 error_code(终态 hook 里用它判断走哪条退避链)。 */
418
+ function lastRunErrorCode(scheduleId: string): string | null {
419
+ const row = db.get<{ error_code: string | null }>(
420
+ `SELECT error_code FROM scheduled_task_runs WHERE schedule_id = ?1
421
+ ORDER BY created_at DESC, run_id DESC LIMIT 1`,
422
+ scheduleId,
423
+ );
424
+ return row?.error_code ?? null;
425
+ }
@@ -131,3 +131,33 @@ describe("applyNoProgressBackoff (#2622)", () => {
131
131
  expect(reload(id).backoff_effective_seconds).toBeNull();
132
132
  });
133
133
  });
134
+
135
+ // #2935 —— 「目标根本不会接活」的**失败**码(node_degraded / target_node_not_found)
136
+ // 也必须走这条链。生产近 7 天:node_degraded 2391(TMA云盘鲸 1388 / TMA云鲸 981)、
137
+ // target_node_not_found 1166 —— 全部是 `every=180` 的排程在目标永久不可用时按原速烧。
138
+ describe("#2935 目标不会接活的失败码也退避", () => {
139
+ test("连续 node_degraded 失败 ⇒ 间隔放大到 2 小时上限(而不是失败退避的 1 小时)", () => {
140
+ const id = seedSchedule(180);
141
+ // 窗口是 10 条;指数封顶 5 ⇒ 180s 基底最多到 180*32 = 5760s。
142
+ // 注意:「cap 7200」对 180s 基底其实够不到 —— 真正生效的是指数封顶那一条。
143
+ for (let i = 0; i < 10; i++) addRun(id, "failed", "node_degraded");
144
+ const r = applyNoProgressBackoff(id)!;
145
+ expect(r.cause).toBe("node_degraded");
146
+ expect(r.effective_seconds).toBe(5760);
147
+ expect(r.effective_seconds!).toBeGreaterThan(3600); // 严格大于失败退避的 1 小时上限
148
+ });
149
+
150
+ test("连续 target_node_not_found 同样走 2 小时上限", () => {
151
+ const id = seedSchedule(180);
152
+ for (let i = 0; i < 10; i++) addRun(id, "failed", "target_node_not_found");
153
+ const r = applyNoProgressBackoff(id)!;
154
+ expect(r.cause).toBe("target_node_not_found");
155
+ expect(r.effective_seconds).toBe(5760);
156
+ });
157
+
158
+ test("普通 task_failed 不被本链接管(仍由失败退避负责)", () => {
159
+ const id = seedSchedule(180);
160
+ for (let i = 0; i < 6; i++) addRun(id, "failed", "task_failed");
161
+ expect(applyNoProgressBackoff(id)).toBeNull();
162
+ });
163
+ });
@@ -124,7 +124,11 @@ describe("task consumed_at identity and lifecycle", () => {
124
124
  expect(second.tasks).toHaveLength(25);
125
125
  expect(new Set([...first.tasks, ...second.tasks].map((task: any) => task.task_id)).size).toBe(125);
126
126
  expect([...first.tasks, ...second.tasks].some((task: any) => task.task_id === "foreign-node-row")).toBe(false);
127
- expect((await call(handler, { from_node_id: `id_${NODE_B}`, durable_cursor: true, limit: 100 })).error).toBe("from_node_id_identity_mismatch");
127
+ const mismatch = await call(handler, { from_node_id: `id_${NODE_B}`, durable_cursor: true, limit: 100 });
128
+ expect(mismatch.error).toBe("from_node_id_identity_mismatch");
129
+ // #2768 —— 同一错误码要能区分「绑到别的节点」与「根本没有绑定」
130
+ expect(mismatch.detail).toBe("bound_to_other_node");
131
+ expect(mismatch.bound_node_id).toBe(`id_${NODE_A}`);
128
132
  });
129
133
  test("a legacy unbound node token is refused the durable cursor even for its own node", async () => {
130
134
  // Pre-RFC-036 tokens carry no immutable node binding. The durable outbox
@@ -132,7 +136,11 @@ describe("task consumed_at identity and lifecycle", () => {
132
136
  // degrades to inbox-only compensation on this exact error code.
133
137
  db.run("UPDATE api_tokens SET bound_node_id = NULL WHERE token_id = ?1", [`token_${NODE_A}`]);
134
138
  const handler = toolsFor({ alias: NODE_A, nodeToken: true }).list_tasks;
135
- expect((await call(handler, { from_node_id: `id_${NODE_A}`, durable_cursor: true, limit: 10 })).error).toBe("from_node_id_identity_mismatch");
139
+ const unbound = await call(handler, { from_node_id: `id_${NODE_A}`, durable_cursor: true, limit: 10 });
140
+ expect(unbound.error).toBe("from_node_id_identity_mismatch");
141
+ // 同一个码,但这里的原因是「没有绑定」——detail 让人和日志都不必再猜
142
+ expect(unbound.detail).toBe("no_binding");
143
+ expect(unbound.bound_node_id).toBeNull();
136
144
  expect((await call(handler, { from_node_id: `id_${NODE_B}`, durable_cursor: true, limit: 10 })).error).toBe("from_node_id_identity_mismatch");
137
145
  const bound = db.get<{ bound_node_id: string | null }>("SELECT bound_node_id FROM api_tokens WHERE token_id = ?1", `token_${NODE_A}`);
138
146
  expect(bound?.bound_node_id).toBeNull();
package/src/tools.ts CHANGED
@@ -3035,7 +3035,18 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
3035
3035
  )?.bound_node_id ?? null
3036
3036
  : null;
3037
3037
  if (!boundNodeId || from_node_id !== boundNodeId) {
3038
- return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: "from_node_id_identity_mismatch" }) }] };
3038
+ // #2768 —— 这个码其实合并了两种原因:token **没有绑定**(注册漏绑)
3039
+ // 与 token **绑到了别的节点**(注入/串号)。客户端把两者都当「未绑定」处理
3040
+ // (agent-node 的 UNBOUND_TOKEN_REJECTIONS 就是这个集合),行为上没问题;
3041
+ // 但运维排障必须能分开 —— 否则只能凭日志猜是漏绑还是串号。
3042
+ //
3043
+ // 加 detail 是向后兼容的:错误码不变,客户端不必改;多出来的一段只给人和日志看。
3044
+ return { content: [{ type: "text" as const, text: JSON.stringify({
3045
+ ok: false,
3046
+ error: "from_node_id_identity_mismatch",
3047
+ detail: boundNodeId ? "bound_to_other_node" : "no_binding",
3048
+ bound_node_id: boundNodeId ?? null,
3049
+ }) }] };
3039
3050
  }
3040
3051
  }
3041
3052
  if (durable_terminal_cursor) {