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

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.212",
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",
@@ -115,4 +115,35 @@ describe('broadcastRecentState', () => {
115
115
  expect(typeof rec!.took_ms).toBe('number');
116
116
  expect(Number.isNaN(Date.parse(rec!.at))).toBe(false);
117
117
  });
118
+
119
+ // 🔴 这条是 2026-10-30 补的:上半句只把 INSERT 摊开,notify 仍然在所有批次之后。
120
+ // 那等于「入库分 3 批、唤醒仍旧同一 tick」—— 而唤醒才是让 Hub 停顿 143.9 秒的原因。
121
+ test("通知与入库同批(不是全部入库完再一起推)", async () => {
122
+ const order: string[] = [];
123
+ const targets = Array.from({ length: 120 }, (_, i) => ({ alias: `a${i}`, node_id: null, network_id: "net_x" }));
124
+ await enqueueBroadcast(targets, "hi", "hub", "net_x", {
125
+ isActive: () => true,
126
+ notify: (alias) => order.push(`n:${alias}`),
127
+ yieldBetweenChunks: async () => { order.push("y"); },
128
+ chunkSize: 50,
129
+ });
130
+ // 结构应为 n×50 y n×50 y n×20 y —— 每一批后面紧跟一个让出,而不是 n×120 全在末尾
131
+ const firstYield = order.indexOf("y");
132
+ expect(firstYield).toBe(50);
133
+ expect(order.filter((x) => x === "y").length).toBe(3);
134
+ // 最后一批的通知必须在最后一次让出之前
135
+ const lastNotify = order.lastIndexOf(order.filter((x) => x.startsWith("n:")).at(-1)!);
136
+ expect(lastNotify).toBeLessThan(order.lastIndexOf("y"));
137
+ });
138
+
139
+ test("某一条通知抛错:其余收件人照常入库(不能因为推不出去就漏发)", async () => {
140
+ const targets = Array.from({ length: 120 }, (_, i) => ({ alias: `b${i}`, node_id: null, network_id: "net_y" }));
141
+ const { ids } = await enqueueBroadcast(targets, "hi", "hub", "net_y", {
142
+ isActive: () => true,
143
+ notify: (alias) => { if (alias === "b0") throw new Error("sse down"); },
144
+ yieldBetweenChunks: async () => {},
145
+ chunkSize: 50,
146
+ });
147
+ expect(ids.length).toBe(120);
148
+ });
118
149
  });
@@ -11,6 +11,11 @@
11
11
  // 但每 50 个收件人一批、批间让出事件循环,把「同一毫秒 384 次 commit」
12
12
  // 变成「8 批、每批一次事务」。
13
13
  //
14
+ // 2026-10-30 补下半句:**通知(SSE 推送)也必须在批内**。
15
+ // 上半句只摊开了入库,通知仍是「所有批次之后一次性循环」——
16
+ // 于是 384 个 agent 还是在同一个 tick 里被唤醒。入库摊开对客户端几乎无感,
17
+ // 唤醒摊开才是「随机大停顿」的解法。
18
+ //
14
19
  // 为什么有用:真正的负载大头是收件 agent 随后各自的 report_status/get_inbox/send_reply
15
20
  // (实测一条广播 ≈ 500+ 次调用)。把入库摊开几百毫秒,能让唤醒时刻自然分散,
16
21
  // 而不是让 384 个 agent 在同一秒同时醒来。
@@ -68,6 +73,7 @@ export async function enqueueBroadcast(
68
73
 
69
74
  for (let i = 0; i < targets.length; i += chunk) {
70
75
  const slice = targets.slice(i, i + chunk);
76
+ const batch: BroadcastDelivered[] = [];
71
77
  // 一批一个事务:把 N 次 autocommit 变成 1 次,既快又不会长时间占写锁。
72
78
  db.transaction(() => {
73
79
  for (const t of slice) {
@@ -80,14 +86,27 @@ export async function enqueueBroadcast(
80
86
  [id, t.alias, t.node_id ?? null, message, fromSession, netId],
81
87
  );
82
88
  ids.push(id);
83
- delivered.push({ alias: t.alias, netId });
89
+ const d = { alias: t.alias, netId };
90
+ delivered.push(d);
91
+ batch.push(d);
84
92
  }
85
93
  });
94
+ // #2721 下半 —— 通知也必须在批内做。
95
+ // 原来这句循环在**所有批次之后**:入库摊开了,但 384 次 SSE 推送又落回同一个 tick,
96
+ // 于是「同一秒全员唤醒」这个真正的问题一点没变 —— 只是把 INSERT 挪开了。
97
+ // 推送失败绝不能中断后续批次:原来通知在所有入库之后,抛错时「入库已全」;
98
+ // 现在挪进批内,一次推送异常会让剩下的人**收不到广播**。这里逐条兜住。
99
+ for (const d of batch) {
100
+ try {
101
+ deps.notify(d.alias, d.netId);
102
+ } catch (e) {
103
+ console.error(`[broadcast] notify failed alias=${d.alias}: ${(e as Error).message}`);
104
+ }
105
+ }
86
106
  // 批间让出:没有这一句,384 行仍然是在同一个 tick 里写完的。
87
107
  await yieldNow();
88
108
  }
89
109
 
90
- for (const d of delivered) deps.notify(d.alias, d.netId);
91
110
  lastBroadcast = {
92
111
  at: new Date().toISOString(),
93
112
  recipients: delivered.length,
@@ -17,7 +17,7 @@ import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
17
17
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
18
18
  import { addNetworkMember, createNetworkTokenForNode, register } from "./auth.js";
19
19
  import { replaceTaskGrants } from "./task-access.js";
20
- import { db } from "./db.js";
20
+ import { db, hashToken } from "./db.js";
21
21
  import { NODE_TOOL_CLASS, pruneNodePermissionLog, __resetNodePermissionLogStateForTest } from "./node-permissions.js";
22
22
  import { registerTools } from "./tools.js";
23
23
 
@@ -548,6 +548,31 @@ describe("未绑定令牌的写调用:默认只记录,不拦", () => {
548
548
  expect(after).toBe(before + 1); // 但记了一笔
549
549
  });
550
550
 
551
+ // 🔴 令牌前缀必须是 `ntok_`:`atok_` 会被当成**用户**令牌(服务端按前缀分流),
552
+ // 那样测出来的是「用户派活」,不是「未绑定节点令牌派活」—— 我第一次就这么写错了,
553
+ // 结果任务记在 boss 名下、账本一行都没有。
554
+ // 🔴 上面两条只调了**判据函数**(nodeDecide),而生产里真正决定「记不记」的是
555
+ // tools.ts 里那层 MCP 包装:它只在 `if (id)` 内部才走到判据。如果哪天有人把包装
556
+ // 改成「只对绑定节点记账」,上面两条测试仍然全绿,而未绑定令牌的写调用会**静默消失** ——
557
+ // 那正是 #3221 想解决的问题。所以这里补一条真正走 HTTP + MCP 的端到端。
558
+ test("HTTP 端到端:未绑定令牌真的调 MCP send_task ⇒ 进 node_permission_log", async () => {
559
+ const alias = `ghost-e2e-${stamp}`;
560
+ const tokenId = `tok_ghost_e2e_${stamp}`;
561
+ const plain = `ntok_ghost_e2e_${stamp}`;
562
+ db.run("INSERT INTO api_tokens (token_id, token_hash, user_id, network_id, name, scope) VALUES (?1, ?2, ?3, ?4, ?5, 'network') ON CONFLICT (token_id) DO NOTHING",
563
+ [tokenId, hashToken(plain), user.boss.id, net, `node:${alias}`]);
564
+
565
+ const out = await mcp(plain, "send_task", { alias: node.nN.alias, task: "hello from a ghost token" });
566
+ // log 模式(默认):不因「未绑定」被拦 —— 拦不拦是另一个开关的事
567
+ expect(out.error ?? "").not.toBe("unbound_token");
568
+
569
+ const hits = Number(db.get<{ h: number | string | null }>(
570
+ `SELECT SUM(hits) AS h FROM node_permission_log
571
+ WHERE network_id = ?1 AND node_id = ?2 AND reason = 'unbound_token' AND route = 'mcp:send_task'`,
572
+ net, `token:${tokenId}`)?.h ?? 0);
573
+ expect(hits).toBe(1);
574
+ });
575
+
551
576
  test("enforce 模式:同一个调用被拒,原因是 unbound_token", async () => {
552
577
  process.env.COMMHUB_NODE_PERMISSIONS = "enforce";
553
578
  const { nodeIdentity, nodeDecide } = await import("./node-permissions.js");
@@ -0,0 +1,74 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { POLL_PACING_NOTE, POLL_NUDGE_THRESHOLD, POLL_RECOMMENDED_SECONDS, createPollPacer } from "./poll-pacing";
3
+
4
+ // #3001 —— Hub 侧的轮询节奏提示。
5
+ // 现场:一个节点在空闲等待里以约 13 次/分钟连续拉了 8 小时 get_task(约 6000 次),
6
+ // 每次都是一整轮 LLM。这里钉住三件事:什么时候提示、什么时候**不**提示、提示里说了什么。
7
+ describe("#3001 get_task 轮询节奏提示", () => {
8
+ function pacerWithClock() {
9
+ let t = 1_000_000;
10
+ const pacer = createPollPacer({ now: () => t });
11
+ return { pacer, advance: (ms: number) => { t += ms; } };
12
+ }
13
+
14
+ test("偶发查询不提示(正常等子任务不会被这句打扰)", () => {
15
+ const { pacer, advance } = pacerWithClock();
16
+ for (let i = 0; i < POLL_NUDGE_THRESHOLD; i++) {
17
+ expect(pacer.record("tok:t1:task-a")).toBeNull();
18
+ advance(3_000);
19
+ }
20
+ });
21
+
22
+ test("60 秒内超过阈值才提示,且带次数与建议间隔", () => {
23
+ const { pacer, advance } = pacerWithClock();
24
+ let pacing = null as ReturnType<typeof pacer.record>;
25
+ for (let i = 0; i <= POLL_NUDGE_THRESHOLD; i++) {
26
+ pacing = pacer.record("tok:t1:task-a");
27
+ advance(4_600); // 约 13 次/分钟:实测的失控频率
28
+ }
29
+ expect(pacing).not.toBeNull();
30
+ expect(pacing!.calls_last_60s).toBeGreaterThan(POLL_NUDGE_THRESHOLD);
31
+ expect(pacing!.recommended_interval_seconds).toBe(POLL_RECOMMENDED_SECONDS);
32
+ });
33
+
34
+ test("隔一分钟以上再看,计数清零、不再提示(纪律生效后自动安静)", () => {
35
+ const { pacer, advance } = pacerWithClock();
36
+ for (let i = 0; i <= POLL_NUDGE_THRESHOLD; i++) {
37
+ pacer.record("tok:t1:task-a");
38
+ advance(500);
39
+ }
40
+ advance(POLL_RECOMMENDED_SECONDS * 1000 + 1);
41
+ expect(pacer.record("tok:t1:task-a")).toBeNull();
42
+ });
43
+
44
+ test("不同 task_id 互不累加(同时等多个子任务不算连环打)", () => {
45
+ const { pacer, advance } = pacerWithClock();
46
+ for (let i = 0; i <= POLL_NUDGE_THRESHOLD; i++) {
47
+ expect(pacer.record(`tok:t1:task-${i}`)).toBeNull();
48
+ advance(500);
49
+ }
50
+ });
51
+
52
+ test("身份查询用更宽的阈值(p50 约 2.3 次/分钟是设计频率,不该被提示打扰)", () => {
53
+ const { pacer } = pacerWithClock();
54
+ // 同一个 60 秒窗口内:task_poll 第 5 次就提示,identity_poll 要到第 9 次
55
+ for (let i = 1; i <= 8; i++) expect(pacer.record("whoami:x", "identity_poll")).toBeNull();
56
+ const pacing = pacer.record("whoami:x", "identity_poll");
57
+ expect(pacing).not.toBeNull();
58
+ expect(pacing!.calls_last_60s).toBe(9);
59
+ expect(pacing!.note).toContain("org_whoami");
60
+ });
61
+
62
+ test("提示文案必须说明「结果会自动 chain」——否则 agent 仍会紧盯", () => {
63
+ expect(POLL_PACING_NOTE).toContain("60 秒");
64
+ expect(POLL_PACING_NOTE).toContain("chain 回上游");
65
+ expect(POLL_PACING_NOTE).toContain("一整轮 LLM");
66
+ });
67
+
68
+ test("key 数量有上限(调用方是外部输入,不能当它只查自己的任务)", () => {
69
+ const pacer = createPollPacer({ maxKeys: 10, windowMs: 1, now: () => 1_000_000 });
70
+ for (let i = 0; i < 500; i++) pacer.record(`tok:t1:task-${i}`);
71
+ // 窗口 1ms,每次 record 时旧条目都已过期,应被回收
72
+ expect(pacer.size()).toBeLessThanOrEqual(11);
73
+ });
74
+ });
@@ -0,0 +1,123 @@
1
+ /**
2
+ * #3001 —— get_task 的轮询节奏提示(Hub 侧)。
3
+ *
4
+ * 为什么放在 Hub 而不是只改 agent-node 的提示词:
5
+ * 提示词在 `agent-node/src/cli.ts` 里,改完要发 agent-node + CLI 配对版本,
6
+ * 而且**只有升级过的节点才会变**。而 `get_task` 是 Hub 提供的 MCP 工具 ——
7
+ * 在响应里加一句话,所有节点下一次调用就能看到,不需要任何客户端升级。
8
+ *
9
+ * 现场(TMW微软欧,2026-10-29 16:00Z → 10-30 01:00Z):
10
+ *
11
+ * 每小时 get_task:256 / 565 / 647 / 703 / 770 / 855 / 893 / 972 / 736
12
+ * ⇒ 约 13 次/分钟、连续 8 小时、合计约 6000 次
13
+ *
14
+ * 每次 `get_task` 都是一整轮 LLM 调用。这 6000 次没有推进任何工作,
15
+ * 只是在问「好没好」。而子任务的最终结果本来就会通过 parent_task_id 自动 chain 回上游。
16
+ *
17
+ * 设计取舍:
18
+ * · **不返回错误、不改状态**,只在同一个响应里多一个 `pacing` 字段 ——
19
+ * 调用方即使完全忽略它也照常工作(信息不缺,行为不破)。
20
+ * · 阈值 4 次/60 秒:正常的「隔几分钟看一眼」永远碰不到;
21
+ * 只有真正在连环打的才会看到这句提示。
22
+ * · 计数按 (调用方, task_id) 分开,避免把「同时等多个子任务」误判成连环打。
23
+ */
24
+
25
+ export type PollPacing = {
26
+ calls_last_60s: number;
27
+ recommended_interval_seconds: number;
28
+ note: string;
29
+ };
30
+
31
+ export const WHOAMI_PACING_NOTE =
32
+ "org_whoami 只需要在「不确定自己是谁/团队变了」时查。实测有节点以约 4–6 次/分钟连续查询、" +
33
+ "同时窗口内没接到任何任务 —— 这些调用没有推进工作。建议隔 60 秒以上再看。";
34
+
35
+ export const POLL_PACING_NOTE =
36
+ "每次 get_task 都是一整轮 LLM 调用。子任务的最终结果会通过 parent_task_id 自动 chain 回上游," +
37
+ "所以不必连续轮询 —— 建议隔 60 秒以上再看。";
38
+
39
+ export const POLL_WINDOW_MS = 60_000;
40
+ export const POLL_NUDGE_THRESHOLD = 4;
41
+ export const POLL_RECOMMENDED_SECONDS = 60;
42
+
43
+ /** 两类轮询的阈值与文案。分开是因为「正常频率」差一个数量级。 */
44
+ export const PACE_KINDS = {
45
+ /** 等子任务:正常是「隔几分钟看一眼」,1 分钟内 4 次以上基本就是连环打。 */
46
+ task_poll: { threshold: POLL_NUDGE_THRESHOLD, note: POLL_PACING_NOTE },
47
+ /** 身份查询:p50 约 2.3 次/分钟是设计频率,1 分钟内 8 次以上才提示。 */
48
+ identity_poll: { threshold: 8, note: WHOAMI_PACING_NOTE },
49
+ } as const;
50
+
51
+ export type PaceKind = keyof typeof PACE_KINDS;
52
+
53
+ export type PollPacer = {
54
+ /** 记一次调用;超过阈值时返回提示,否则返回 null。 */
55
+ record(key: string, kind?: PaceKind): PollPacing | null;
56
+ /** 仅测试用:当前记录的 key 数。 */
57
+ size(): number;
58
+ };
59
+
60
+ export function createPollPacer(opts: {
61
+ windowMs?: number;
62
+ threshold?: number;
63
+ maxKeys?: number;
64
+ now?: () => number;
65
+ } = {}): PollPacer {
66
+ const windowMs = opts.windowMs ?? POLL_WINDOW_MS;
67
+ const defaultThreshold = opts.threshold ?? POLL_NUDGE_THRESHOLD;
68
+ const maxKeys = opts.maxKeys ?? 2000;
69
+ const now = opts.now ?? Date.now;
70
+ const seen = new Map<string, number[]>();
71
+
72
+ function prune(ts: number[], cutoff: number): number[] {
73
+ // 时间戳按升序追加,从头部删到窗口内为止。
74
+ let i = 0;
75
+ while (i < ts.length && ts[i] <= cutoff) i++;
76
+ return i === 0 ? ts : ts.slice(i);
77
+ }
78
+
79
+ return {
80
+ record(key: string, kind: PaceKind = "task_poll"): PollPacing | null {
81
+ // 显式传了 threshold(测试用)就压过 kind 表
82
+ const spec = opts.threshold !== undefined
83
+ ? { threshold: defaultThreshold, note: PACE_KINDS[kind].note }
84
+ : PACE_KINDS[kind];
85
+ const t = now();
86
+ const cutoff = t - windowMs;
87
+ const prev = seen.get(key);
88
+ const ts = prune(prev ?? [], cutoff);
89
+ ts.push(t);
90
+ seen.set(key, ts);
91
+
92
+ // 无上限的 Map 就是一条内存泄漏 —— 调用方是外部输入,不能假设它只查自己的任务。
93
+ if (seen.size > maxKeys) {
94
+ for (const k of seen.keys()) {
95
+ if (seen.size <= maxKeys) break;
96
+ const keep = prune(seen.get(k) ?? [], cutoff);
97
+ if (keep.length === 0) seen.delete(k);
98
+ else seen.set(k, keep);
99
+ }
100
+ // 光靠过期回收不够:如果所有 key 都在窗口内(例如有人用几百个 task_id 乱打),
101
+ // 过期一条也删不掉,长度仍然无界 —— 这里再按插入顺序硬砍到上限。
102
+ while (seen.size > maxKeys) {
103
+ const oldest = seen.keys().next();
104
+ if (oldest.done) break;
105
+ seen.delete(oldest.value);
106
+ }
107
+ }
108
+
109
+ if (ts.length <= spec.threshold) return null;
110
+ return {
111
+ calls_last_60s: ts.length,
112
+ recommended_interval_seconds: POLL_RECOMMENDED_SECONDS,
113
+ note: spec.note,
114
+ };
115
+ },
116
+ size(): number {
117
+ return seen.size;
118
+ },
119
+ };
120
+ }
121
+
122
+ /** 进程级单例:Hub 只需要看「最近一分钟这位调用方问了多少次」。 */
123
+ export const pollPacer = createPollPacer();
@@ -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
@@ -109,6 +109,7 @@ import { dispatchQueueInfo, queueDepthByNode, queueDepthKey } from "./task-queue
109
109
  import { parseHubTimestamp } from "./hub-timestamp";
110
110
  import { noteTerminalResultRead, purgeLogsResultNow, sweepNodeRequestContent } from "./node-request-retention.js";
111
111
  import { listTaskLateReplies } from "./task-late-replies.js";
112
+ import { pollPacer } from "./poll-pacing.js";
112
113
  import { auditDepartment, createDepartment, deleteDepartment, listDepartments, setAgentDepartment, updateDepartment } from "./departments.js";
113
114
 
114
115
  function ts(): string {
@@ -2996,10 +2997,17 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
2996
2997
  if (task) {
2997
2998
  task.late_replies = listTaskLateReplies(db, task_id, typeof task.network_id === "string" ? task.network_id : null);
2998
2999
  }
3000
+ // #3001 —— 轮询节奏提示。只多一个字段,不改状态、不返回错误:
3001
+ // 调用方忽略它照常工作;连着打的才会看到这句话。
3002
+ // 放在 Hub 侧而不是只改 agent-node,是因为 get_task 由 Hub 提供 ——
3003
+ // 发版即对所有节点生效,不必等客户端升级。
3004
+ const pacing = pollPacer.record(`${callerTokenId ?? callerAlias ?? "anon"}:${task_id}`);
2999
3005
  return {
3000
3006
  content: [{
3001
3007
  type: "text" as const,
3002
- text: JSON.stringify(task ? { ok: true, task } : { ok: false, error: "task not found" }),
3008
+ text: JSON.stringify(task
3009
+ ? { ok: true, task, ...(pacing ? { pacing } : {}) }
3010
+ : { ok: false, error: "task not found", ...(pacing ? { pacing } : {}) }),
3003
3011
  }],
3004
3012
  };
3005
3013
  }
@@ -3035,7 +3043,18 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
3035
3043
  )?.bound_node_id ?? null
3036
3044
  : null;
3037
3045
  if (!boundNodeId || from_node_id !== boundNodeId) {
3038
- return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: "from_node_id_identity_mismatch" }) }] };
3046
+ // #2768 —— 这个码其实合并了两种原因:token **没有绑定**(注册漏绑)
3047
+ // 与 token **绑到了别的节点**(注入/串号)。客户端把两者都当「未绑定」处理
3048
+ // (agent-node 的 UNBOUND_TOKEN_REJECTIONS 就是这个集合),行为上没问题;
3049
+ // 但运维排障必须能分开 —— 否则只能凭日志猜是漏绑还是串号。
3050
+ //
3051
+ // 加 detail 是向后兼容的:错误码不变,客户端不必改;多出来的一段只给人和日志看。
3052
+ return { content: [{ type: "text" as const, text: JSON.stringify({
3053
+ ok: false,
3054
+ error: "from_node_id_identity_mismatch",
3055
+ detail: boundNodeId ? "bound_to_other_node" : "no_binding",
3056
+ bound_node_id: boundNodeId ?? null,
3057
+ }) }] };
3039
3058
  }
3040
3059
  }
3041
3060
  if (durable_terminal_cursor) {
@@ -7077,7 +7096,21 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
7077
7096
 
7078
7097
  // #765: exact authenticated node; team tree is independent of human departments.
7079
7098
  server.tool("org_whoami", "Your Agent team, ancestors, lead, owner and up to 50 teammates. Read-only.", {},
7080
- async () => scheduleCall(id => agentTeamWhoami(id.networkId, id.nodeId)));
7099
+ async () => {
7100
+ const res = scheduleCall(id => agentTeamWhoami(id.networkId, id.nodeId));
7101
+ // #3001 续 —— 全舰队 6 小时 52522 次工具调用里,org_whoami 占 21900(42%),
7102
+ // 而其中十来个节点在同期收到 0 个任务(实测 1420–2190 次/6h)。
7103
+ // 这些调用与 get_task 那一类一样:每次都跑完一轮 LLM,却没有推进任何工作。
7104
+ // 阈值比 get_task 宽(8 次/60 秒)—— p50 约 2.3 次/分钟是设计频率,不该被提示打扰。
7105
+ const pacing = pollPacer.record(`whoami:${callerTokenId ?? callerAlias ?? "anon"}`, "identity_poll");
7106
+ if (!pacing) return res;
7107
+ try {
7108
+ const body = JSON.parse(res.content[0].text);
7109
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ...body, pacing }) }] };
7110
+ } catch {
7111
+ return res; // 解析失败就原样返回:提示绝不该让一个只读工具失败
7112
+ }
7113
+ });
7081
7114
 
7082
7115
  // #478:tools/list 只列这个调用者真能用的工具(tool-audience.ts)。只滤列表,tools/call 不变。
7083
7116
  const caller: ToolCaller = callerTokenIsNetwork