@sleep2agi/commhub-server 0.9.0-preview.260 → 0.9.0-preview.262

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": "01a790c1c8b5ecfa4bfe6a44bf96262b894fd039",
3
+ "commit": "f7f664ca87d1d85ce11b9118d43d25260e2af9b0",
4
4
  "dirty": false,
5
- "built_at": "2026-11-01T02:21:02.159Z",
5
+ "built_at": "2026-11-01T03:44:41.934Z",
6
6
  "source": "git"
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sleep2agi/commhub-server",
3
- "version": "0.9.0-preview.260",
3
+ "version": "0.9.0-preview.262",
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",
@@ -99,6 +99,25 @@ test("上限按「有没有真的丢过一条」判,不按「集合是否已
99
99
  assert.equal(s.distinct_locked_usernames, 0);
100
100
  });
101
101
 
102
+ // 2026-11-01 —— 「同一个对象里」只保证同一次调用;**已读出的那份之后不得再变**。
103
+ // 这条可判:读一次快照 → 再触发计数 → 早先那份的值不许动。
104
+ // 缺它时,一次读取拿到的是**活引用**与**不可变快照**在报告上同形,
105
+ // 而活引用会让「读完之后又涨了」被读成「同一份读数自相矛盾」。
106
+ test("快照是不可变的一份,不是内部状态的活引用", () => {
107
+ noteRegisterRateLimited("10.1.1.1");
108
+ const first = authAbuseSnapshot();
109
+ const before = first.register_rate_limited_total;
110
+ noteRegisterRateLimited("10.1.1.2");
111
+ noteRegisterRateLimited("10.1.1.3");
112
+ // 早先那份必须一字不动
113
+ expect(first.register_rate_limited_total).toBe(before);
114
+ expect(first.distinct_register_limited_ips).toBe(1);
115
+ // 再读一次才看得到新的
116
+ const second = authAbuseSnapshot();
117
+ expect(second.register_rate_limited_total).toBe(before + 2);
118
+ expect(second.distinct_register_limited_ips).toBe(3);
119
+ });
120
+
102
121
  test("快照形状固定(键集是契约,不是实现细节)", () => {
103
122
  const keys = Object.keys(authAbuseSnapshot()).sort();
104
123
  assert.deepEqual(keys, [
@@ -34,7 +34,10 @@ function tools(callerUserId: string): Record<string, ToolHandler> {
34
34
  return out;
35
35
  }
36
36
 
37
- // 精确键集 = 集合相等(不是计数、也不是「有这几个字段」)。
37
+ // 🔴 basis: impl —— 下面这些键集**取自真实调用的响应**,因此它是**变更探测器**,不是契约读数。
38
+ // 红的意思是「实现变了,去看是不是故意的」;而「实现错了」这一类它测不出来
39
+ // (若实现多返回一个字段,断言会红,但那可能是正确的修复)。
40
+ // 要不要升级成 spec 列:需要一处**独立于实现**的书面来源;指不出来时,它就只能留在这里。
38
41
  function expectKeys(obj: Record<string, unknown>, want: string[]) {
39
42
  expect(Object.keys(obj).sort(), "键集合必须完全等于期望").toEqual([...want].sort());
40
43
  }
@@ -183,6 +183,29 @@ describe("#473 anonymous /health — watchdog contract intact, no topology leak"
183
183
  // 🔴 这条断言的语义是:**目前如此**,不是「应该如此」。
184
184
  // 将来谁把计数上移到中间件,这条会红 —— 那就对了:他必须同时更新
185
185
  // 模块注释里的覆盖比例(现在是 2/6 类出口)。
186
+ // #669 —— 新加的计数必须**两侧都验**:鉴权侧看得到形状,匿名侧看不到键。
187
+ // 只验一侧时有两种假绿:
188
+ // · 只验匿名侧「没有」⇒ 字段根本没加也能过;
189
+ // · 只验鉴权侧「有」 ⇒ 它同时泄露给了匿名读者也能过。
190
+ // 这两句合起来才是「加进了 counters,且仍在鉴权侧」这个事实。
191
+ test("#669 counters.parent_infer 在鉴权投影里,匿名投影里没有", async () => {
192
+ const authed = await (await fetch(`${BASE}/health`, { headers: { Authorization: `Bearer ${adminToken}` } })).json() as any;
193
+ const pi = authed.counters?.parent_infer;
194
+ expect(pi).toBeTruthy();
195
+ // 形状是契约:五个键,一个不多一个不少。
196
+ expect(Object.keys(pi).sort()).toEqual([
197
+ "accepted", "rejected_ambiguous", "rejected_too_old", "since", "window_ms",
198
+ ]);
199
+ // 窗口常量本身也是读数:「10 分钟」这个策略值必须从服务端读得到,
200
+ // 否则客户端只能写死一份拷贝,而那两份迟早不一致。
201
+ expect(pi.window_ms).toBe(600_000);
202
+
203
+ const anon = await (await fetch(`${BASE}/health`)).json() as any;
204
+ expect(anon.counters).toBeUndefined();
205
+ // 否定断言要配镜像:不能只在顶层没有就过 —— 也可能被拍平成了 counters_parent_infer。
206
+ expect(JSON.stringify(anon).includes("parent_infer")).toBe(false);
207
+ });
208
+
186
209
  test("KNOWN GAP: unauthenticated /api/task rejection is NOT counted (see rejection-counters.ts)", async () => {
187
210
  const before = await (await fetch(`${BASE}/health`, { headers: { Authorization: `Bearer ${adminToken}` } })).json() as any;
188
211
  const beforeTotal = before.counters.task_rejections.total as number;
@@ -17,9 +17,12 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
17
17
  import { registerTools } from "./tools.js";
18
18
 
19
19
  const NET = "net_10th_err";
20
+ const NET_OTHER = "net_10th_other"; // 调用者**不在**里面的网络(用来触发 scope.denied)
21
+ const NET_DAEMON = "net_10th_daemon"; // daemon 所在的另一个网络(用来触发 daemon_cross_tenant)
20
22
  const OWNER = "u_10th_owner";
21
23
  const DAEMON = "node_10th_daemon";
22
24
  const ADOPTED = "node_10th_adopted";
25
+ const DAEMON_OTHER_NET = "node_10th_daemon_other";
23
26
 
24
27
  type ToolHandler = (args: any) => Promise<{ content: Array<{ type: "text"; text: string }> }>;
25
28
 
@@ -41,7 +44,9 @@ function cleanup() {
41
44
  for (const t of ["node_daemon_bindings", "node_create_requests", "nodes", "network_members"]) {
42
45
  try { db.run(`DELETE FROM ${t} WHERE network_id = ?1`, [NET]); } catch {}
43
46
  }
44
- try { db.run("DELETE FROM networks WHERE network_id = ?1", [NET]); } catch {}
47
+ for (const n of [NET, NET_OTHER, NET_DAEMON]) {
48
+ try { db.run("DELETE FROM networks WHERE network_id = ?1", [n]); } catch {}
49
+ }
45
50
  try { db.run("DELETE FROM users WHERE user_id = ?1", [OWNER]); } catch {}
46
51
  }
47
52
 
@@ -59,6 +64,10 @@ function seed() {
59
64
  db.run("INSERT INTO users (user_id, username, password_hash, role, created_at) VALUES (?1, ?1, 'x', 'user', datetime('now'))", [OWNER]);
60
65
  db.run("INSERT INTO networks (network_id, network_name, owner_id, created_at) VALUES (?1, ?1, ?2, datetime('now'))", [NET, OWNER]);
61
66
  db.run("INSERT INTO network_members (user_id, network_id, role, joined_at) VALUES (?1, ?2, 'owner', datetime('now'))", [OWNER, NET]);
67
+ // 两个「不属于我」的网络:NET_OTHER 我完全不在里面;NET_DAEMON 里放一台别的网络的 daemon
68
+ for (const n of [NET_OTHER, NET_DAEMON]) {
69
+ db.run("INSERT INTO networks (network_id, network_name, owner_id, created_at) VALUES (?1, ?1, ?2, datetime('now'))", [n, OWNER]);
70
+ }
62
71
  node(DAEMON, "10th-daemon", { role: "host_supervisor" });
63
72
  node(ADOPTED, "10th-adopted", null);
64
73
  // adopted 的判据:有 **active** binding,且不是 created(没有 cr_ 记录)
@@ -88,6 +97,37 @@ describe("#3309 restart_node / start_node 的两条拒绝", () => {
88
97
  expect(r.error).not.toBe("adopted_restart_requires_daemon");
89
98
  });
90
99
 
100
+ test("start_node 传一个我不属于的 network_id ⇒ forbidden_cross_tenant(scope.denied)", async () => {
101
+ // 先让 child→daemon 可解析,否则会先撞 daemon_not_resolvable(我上一轮就撞过)。
102
+ db.run(
103
+ `INSERT INTO node_create_requests (request_id, daemon_node_id, child_name, network_id, runtime, model,
104
+ flags_json, env_keys, status, created_at, created_by_token)
105
+ VALUES ('cr_lc_child_x', ?1, 'lc-child-x', ?2, 'opencode-cli', NULL, '{}', '[]', 'succeeded', ?3, 'tok_x')`,
106
+ [DAEMON, NET, Date.now()],
107
+ );
108
+ const r = await call("start_node", { node_id: "node_lc_child_x", network_id: NET_OTHER });
109
+ expect(r.ok).toBe(false);
110
+ expect(r.error).toBe("forbidden_cross_tenant");
111
+ });
112
+
113
+ test("stop_node:daemon 与 child 分属不同网络 ⇒ daemon_cross_tenant(SEC-1 加固)", async () => {
114
+ // 这个状态正常流程造不出来(代码注释也这么写:shouldn't be possible in normal flow),
115
+ // 所以这条测的是**加固分支本身**:库被写坏时它必须拒绝,而不是跨租户操作。
116
+ // 夹具:child 在 NET,daemon 在 NET_DAEMON,且 create 记录把两者绑在一起。
117
+ node(DAEMON_OTHER_NET, "10th-daemon-other", null);
118
+ db.run("UPDATE nodes SET network_id = ?1 WHERE node_id = ?2", [NET_DAEMON, DAEMON_OTHER_NET]);
119
+ node("node_lc_child_2", "10th-child-2", null);
120
+ db.run(
121
+ `INSERT INTO node_create_requests (request_id, daemon_node_id, child_name, network_id, runtime, model,
122
+ flags_json, env_keys, status, created_at, created_by_token)
123
+ VALUES ('cr_lc_child_2', ?1, 'lc-child-2', ?2, 'opencode-cli', NULL, '{}', '[]', 'succeeded', ?3, 'tok_x')`,
124
+ [DAEMON_OTHER_NET, NET, Date.now()],
125
+ );
126
+ const r = await call("stop_node", { node_id: "node_lc_child_2" });
127
+ expect(r.ok).toBe(false);
128
+ expect(r.error).toBe("daemon_cross_tenant");
129
+ });
130
+
91
131
  test("start_node 对不存在的 node ⇒ **第三次值** daemon_not_resolvable(不是我猜的两个)", async () => {
92
132
  // 我原本以为这里是 forbidden_cross_tenant 或 node_not_found —— 实测都不是。
93
133
  // 这是本组测试里唯一一次「期望值被真实调用纠正」:猜错的那个值(daemon_not_resolvable)
@@ -0,0 +1,82 @@
1
+ // #669 —— 父任务推断收窄的判据:**候选唯一 + 在窗口内**,且每一种拒绝都要能被数出来。
2
+ //
3
+ // 为什么这三件事要一起测:
4
+ // 收窄是「减少推断」,而减少在派发日志里不留痕(任务照常派出,只是没有父)。
5
+ // 没有 rejected 计数时,「收窄生效」与「收窄没写对」同形——两者的 7 天失败率都会降。
6
+ //
7
+ // 为什么「年龄未知」要算拒绝而不是放行:
8
+ // 这条约束的全部价值是「刚派不久」,而 age 未知时无法证明它成立。
9
+ // 放行会让这一条在最需要它的输入上失效。
10
+ import { test, beforeEach } from "node:test";
11
+ import assert from "node:assert/strict";
12
+ import {
13
+ INFER_WINDOW_MS,
14
+ __resetParentInferForTest,
15
+ decideParentInference,
16
+ noteInferAccepted,
17
+ noteInferRejected,
18
+ parentInferCounters,
19
+ } from "./parent-infer.js";
20
+
21
+ const NOW = 1_800_000_000_000;
22
+
23
+ beforeEach(() => __resetParentInferForTest());
24
+
25
+ test("唯一候选且在窗口内 ⇒ 推断到它", () => {
26
+ const r = decideParentInference([{ task_id: "t1", created_at_ms: NOW - 60_000 }], NOW);
27
+ assert.equal(r.ok, true);
28
+ assert.equal(r.ok && r.task_id, "t1");
29
+ });
30
+
31
+ test("多个候选 ⇒ 不推断(挑最近一条正是挂错的来源)", () => {
32
+ const r = decideParentInference([
33
+ { task_id: "new", created_at_ms: NOW - 10_000 },
34
+ { task_id: "old", created_at_ms: NOW - 500_000 },
35
+ ], NOW);
36
+ assert.equal(r.ok, false);
37
+ // 关键:**不是**退化成「取最新那条」
38
+ assert.equal(!r.ok && r.rejection.reason, "ambiguous_candidates");
39
+ assert.equal(!r.ok && r.rejection.candidates, 2);
40
+ });
41
+
42
+ test("唯一候选但太旧 ⇒ 不推断(那是排在后面还没轮到的)", () => {
43
+ const r = decideParentInference(
44
+ [{ task_id: "t1", created_at_ms: NOW - INFER_WINDOW_MS - 1 }], NOW);
45
+ assert.equal(r.ok, false);
46
+ assert.equal(!r.ok && r.rejection.reason, "candidate_too_old");
47
+ });
48
+
49
+ test("窗口边界:正好等于窗口 ⇒ 仍然推断(<= 而非 <)", () => {
50
+ const r = decideParentInference(
51
+ [{ task_id: "t1", created_at_ms: NOW - INFER_WINDOW_MS }], NOW);
52
+ assert.equal(r.ok, true);
53
+ });
54
+
55
+ test("年龄未知 ⇒ 不推断(无法证明「刚派不久」,而那是这条约束的全部价值)", () => {
56
+ const r = decideParentInference([{ task_id: "t1", created_at_ms: null }], NOW);
57
+ assert.equal(r.ok, false);
58
+ assert.equal(!r.ok && r.rejection.reason, "candidate_too_old");
59
+ assert.equal(!r.ok && r.rejection.age_ms, null);
60
+ });
61
+
62
+ test("没有候选 ⇒ 也是 ok:false,但 candidates=0(调用方据此决定不计数)", () => {
63
+ const r = decideParentInference([], NOW);
64
+ assert.equal(r.ok, false);
65
+ assert.equal(!r.ok && r.rejection.candidates, 0);
66
+ // 「没有要接的任务」是常态,不是拒绝;把它记成拒绝会让分母虚高。
67
+ });
68
+
69
+ test("计数:accepted 与两种 rejected 分开,且窗口值随快照给出", () => {
70
+ noteInferAccepted();
71
+ noteInferRejected({ reason: "ambiguous_candidates", candidates: 2, age_ms: 1000 });
72
+ noteInferRejected({ reason: "candidate_too_old", candidates: 1, age_ms: 999999 });
73
+ noteInferRejected({ reason: "candidate_too_old", candidates: 1, age_ms: 999999 });
74
+ const c = parentInferCounters();
75
+ assert.equal(c.accepted, 1);
76
+ assert.equal(c.rejected_ambiguous, 1);
77
+ assert.equal(c.rejected_too_old, 2);
78
+ assert.equal(c.window_ms, INFER_WINDOW_MS);
79
+ assert.deepEqual(Object.keys(c).sort(), [
80
+ "accepted", "rejected_ambiguous", "rejected_too_old", "since", "window_ms",
81
+ ]);
82
+ });
@@ -0,0 +1,110 @@
1
+ // #669 —— 父任务**推断**的收窄:从「取最近一条 delivered」改成「候选唯一且在窗口内」。
2
+ //
3
+ // ## 为什么收窄,而不是取消
4
+ //
5
+ // 生产实测(近 7 天,`meta_json.parent_source`):
6
+ //
7
+ // inferred 795 条(78% 的有父任务派发靠推断)
8
+ // explicit 222 条
9
+ //
10
+ // inferred 非正常收尾 48/795 = **6.0%**(expired 43 + failed 17 + cancelled 5 里与 expired 合并计)
11
+ // explicit 非正常收尾 1/222 = **0.5%**
12
+ //
13
+ // ⇒ 取消会让 795 条/周失去父链(不可接受);但 12 倍的失败率说明它确实在挂错父任务
14
+ // (子任务回复提前关掉那条还没开始的 delivered)。
15
+ //
16
+ // ## 收窄的两条约束
17
+ //
18
+ // ① **候选必须唯一**:该节点名下 `delivered` 的条数 == 1。多于一条时无法判断
19
+ // 「你要接的是哪一条」,而挑最近一条正是挂错的来源。
20
+ // ② **必须在窗口内**:那条 delivered 的 `created_at` 距今 ≤ INFER_WINDOW_MS。
21
+ // 太旧的 delivered 更可能是「排在后面还没轮到」的,而不是「刚派给我、我正在做」的。
22
+ //
23
+ // 两个常量都可改;改完的效果由 `inferred_rejected` 计数与 7 天后的失败率对比来读。
24
+ //
25
+ // ## 为什么每一条拒绝都要计数
26
+ //
27
+ // 收窄是**减少**推断,而「减少」在派发日志里不留痕:任务照常派出,只是没有父。
28
+ // 没有计数时,「收窄了多少」与「收窄没生效」同形——两者的 7 天失败率都会下降。
29
+
30
+ export const INFER_WINDOW_MS = 10 * 60_000;
31
+
32
+ export interface InferRejection {
33
+ /** 被拒绝的原因:候选不唯一 / 候选太旧 */
34
+ reason: "ambiguous_candidates" | "candidate_too_old";
35
+ /** 候选条数(不唯一时 >1;太旧时 ==1) */
36
+ candidates: number;
37
+ /** 最近那条候选的年龄(毫秒,未知时 null) */
38
+ age_ms: number | null;
39
+ }
40
+
41
+ const counters = {
42
+ accepted: 0,
43
+ rejected_ambiguous: 0,
44
+ rejected_too_old: 0,
45
+ since: new Date().toISOString(),
46
+ };
47
+
48
+ export function noteInferAccepted(): void {
49
+ counters.accepted += 1;
50
+ }
51
+
52
+ export function noteInferRejected(r: InferRejection): void {
53
+ if (r.reason === "ambiguous_candidates") counters.rejected_ambiguous += 1;
54
+ else counters.rejected_too_old += 1;
55
+ }
56
+
57
+ export interface InferCounters {
58
+ since: string;
59
+ /** 推断成功挂上父任务的次数 */
60
+ accepted: number;
61
+ /** 因候选不唯一而放弃推断 */
62
+ rejected_ambiguous: number;
63
+ /** 因候选太旧而放弃推断 */
64
+ rejected_too_old: number;
65
+ window_ms: number;
66
+ }
67
+
68
+ export function parentInferCounters(): InferCounters {
69
+ return {
70
+ since: counters.since,
71
+ accepted: counters.accepted,
72
+ rejected_ambiguous: counters.rejected_ambiguous,
73
+ rejected_too_old: counters.rejected_too_old,
74
+ window_ms: INFER_WINDOW_MS,
75
+ };
76
+ }
77
+
78
+ /** 裁定:候选列表(按 created_at DESC 排好)+ 现在的时间 ⇒ 是否推断、以及为什么。 */
79
+ export function decideParentInference(
80
+ candidates: Array<{ task_id: string; created_at_ms: number | null }>,
81
+ now: number,
82
+ windowMs: number = INFER_WINDOW_MS,
83
+ ): { ok: true; task_id: string } | { ok: false; rejection: InferRejection } {
84
+ if (candidates.length === 0) {
85
+ // 没有候选不是「拒绝」,是「本来就不该推断」—— 由调用方决定要不要记。
86
+ return { ok: false, rejection: { reason: "ambiguous_candidates", candidates: 0, age_ms: null } };
87
+ }
88
+ if (candidates.length > 1) {
89
+ const newest = candidates[0]?.created_at_ms ?? null;
90
+ return { ok: false, rejection: {
91
+ reason: "ambiguous_candidates", candidates: candidates.length,
92
+ age_ms: newest === null ? null : Math.max(0, now - newest),
93
+ } };
94
+ }
95
+ const only = candidates[0]!;
96
+ const age = only.created_at_ms === null ? null : Math.max(0, now - only.created_at_ms);
97
+ // 年龄未知时**不推断**:无法证明它「刚派不久」,而正是这个条件在防挂错。
98
+ if (age === null || age > windowMs) {
99
+ return { ok: false, rejection: { reason: "candidate_too_old", candidates: 1, age_ms: age } };
100
+ }
101
+ return { ok: true, task_id: only.task_id };
102
+ }
103
+
104
+ /** 只在测试里用。 */
105
+ export function __resetParentInferForTest(): void {
106
+ counters.accepted = 0;
107
+ counters.rejected_ambiguous = 0;
108
+ counters.rejected_too_old = 0;
109
+ counters.since = new Date().toISOString();
110
+ }
@@ -15,7 +15,27 @@ const src = readFileSync(new URL("./tools.ts", import.meta.url), "utf8");
15
15
  describe("#669 parent source marker", () => {
16
16
  test("显式 parent 记为 explicit,推断命中时改写为 inferred", () => {
17
17
  expect(src).toContain('let parentSource: "explicit" | "inferred" | null = parentIn ? "explicit" : null;');
18
- expect(src).toContain('if (recent?.task_id) { parentTaskId = recent.task_id; parentSource = "inferred"; }');
18
+ // #669 收窄之后,推断不再是「取最近一条」,而是「裁定通过才认」。
19
+ // 断言从「命中最近一条就改写」改成「裁定 ok 才改写」,并且配一条否定断言:
20
+ // 那条 SQL 不能退回 `LIMIT 1` —— 退回之后裁定拿不到候选条数,
21
+ // 「候选唯一」这条约束会静默失效,而它失效时测试仍然全绿(拿到的永远是一条)。
22
+ const block = src.slice(src.indexOf("const verdict = decideParentInference("),
23
+ src.indexOf("// #669 —— 把来源写进 meta"));
24
+ expect(block).toContain("if (verdict.ok)");
25
+ expect(block).toContain('parentSource = "inferred"');
26
+ expect(block).toContain("noteInferAccepted()");
27
+ expect(block).toContain("noteInferRejected(verdict.rejection)");
28
+ });
29
+
30
+ // 分成独立一条,而不是塞进上一条:「候选唯一」这条约束的见证是 LIMIT,
31
+ // 「裁定通过才改写」的见证是 verdict.ok。两者放在同一个 test 里时,
32
+ // 任一被破都只让同一条红 —— 红的集合相同,归因就得靠读行号。
33
+ // 独立成条之后,「只破 LIMIT」只红这一条,「只破 verdict」只红上一条。
34
+ test("取候选必须看得到「不止一条」—— LIMIT 1 会让「候选唯一」静默失效", () => {
35
+ const sqlBlock = src.slice(src.indexOf("SELECT task_id, created_at FROM tasks WHERE to_name"),
36
+ src.indexOf("const cands = db.all"));
37
+ expect(sqlBlock).toContain("LIMIT 5");
38
+ expect(sqlBlock).not.toContain("LIMIT 1");
19
39
  });
20
40
 
21
41
  test("来源只在确实有 parent 时写进 meta,且序列化失败不影响派发", () => {
@@ -0,0 +1,121 @@
1
+ // #3348 —— 父被丢弃时,**来源必须一起丢弃**。
2
+ //
3
+ // ## 生产读数(修之前)
4
+ //
5
+ // tasks 131684 行里 2 条:
6
+ // meta = {"parent_source":"explicit"},parent_task_id / in_reply_to / thread_id 全空
7
+ // 5bc82d72 2026-10-30 16:08:38 · d002b739 2026-10-31 02:23:09
8
+ //
9
+ // ## 为什么会出现
10
+ //
11
+ // `send_task` 里的顺序是:
12
+ //
13
+ // ① `if (parentSource && parentTaskId) { meta.parent_source = parentSource }` ← 拼 meta
14
+ // ② 校验显式父是否存在;不存在 ⇒ `parentTaskId = null` ← 丢父
15
+ // ③ INSERT(meta 用 ①,父用 ② 之后的值)
16
+ //
17
+ // ⇒ ② 与 ① 之间没有连线。`meta` 里保留了「有一个 explicit 父」这个陈述,
18
+ // 而那一行本身没有父。
19
+ //
20
+ // ## 为什么这条不变式的正向断言抓不到它
21
+ //
22
+ // `#669` 的不变式是「父有值 ⇒ 来源有值」。这一格是「来源有值 ⇒ 父有值」的反面,
23
+ // 两个方向各自都合理,合起来留了一个空格 —— 而空格里正好能站下一行坏数据。
24
+ // `scripts/report-parent-source-coverage.py` 现在把这一格单列成 `source, no parent` 并报数。
25
+ //
26
+ // ## 这里测什么
27
+ //
28
+ // 走**真 handler**(不是镜像映射):派一条带不存在父的任务,断言
29
+ // ① 任务照样建成(丢父是「不阻塞派发」的决定,不是错误)
30
+ // ② parent_task_id 落库为 NULL
31
+ // ③ meta_json 里**没有** parent_source —— 这一条是本次修的
32
+ import { afterAll, beforeEach, describe, expect, test } from "bun:test";
33
+ import { mkdtempSync } from "fs";
34
+ import { join } from "path";
35
+ import { tmpdir } from "os";
36
+
37
+ process.env.COMMHUB_DB = join(mkdtempSync(join(tmpdir(), "anet-orphan-source-")), "commhub.db");
38
+
39
+ const { McpServer } = await import("@modelcontextprotocol/sdk/server/mcp.js");
40
+ const { db } = await import("./db.js");
41
+ const { registerTools } = await import("./tools.js");
42
+
43
+ const NET = "net_orphan_src";
44
+ const USER = "u_orphan_src";
45
+ const PEER = "osp-peer";
46
+ const TARGET = "osp-target";
47
+
48
+ type Handler = (args: any, extra?: any) => Promise<{ content: Array<{ type: "text"; text: string }> }>;
49
+
50
+ function cleanup(): void {
51
+ for (const table of ["task_events", "inbox", "tasks", "sessions", "nodes", "network_members", "networks"]) {
52
+ try { db.run(`DELETE FROM ${table} WHERE network_id = ?1`, [NET]); } catch {}
53
+ }
54
+ try { db.run("DELETE FROM users WHERE user_id = ?1", [USER]); } catch {}
55
+ }
56
+
57
+ function seed(): void {
58
+ db.run("INSERT INTO users (user_id, username, password_hash, role, created_at) VALUES (?1, ?2, 'x', 'user', datetime('now'))", [USER, USER]);
59
+ db.run("INSERT INTO networks (network_id, network_name, owner_id, created_at) VALUES (?1, ?1, ?2, datetime('now'))", [NET, USER]);
60
+ db.run("INSERT INTO network_members (user_id, network_id, role, joined_at) VALUES (?1, ?2, 'owner', datetime('now'))", [USER, NET]);
61
+ for (const alias of [PEER, TARGET]) {
62
+ db.run(
63
+ `INSERT INTO nodes (node_id, node_name, alias, network_id, lifecycle_state)
64
+ VALUES (?1, ?2, ?2, ?3, 'active')`,
65
+ [`n_${alias}`, alias, NET],
66
+ );
67
+ db.run(
68
+ `INSERT INTO sessions (resume_id, alias, status, node_id, network_id, updated_at, last_seen_at)
69
+ VALUES (?1, ?2, 'idle', ?3, ?4, datetime('now'), datetime('now'))`,
70
+ [`r_${alias}`, alias, `n_${alias}`, NET],
71
+ );
72
+ }
73
+ }
74
+
75
+ function handlers(): Record<string, Handler> {
76
+ const server = new McpServer({ name: "test-orphan-source", version: "0" }) as any;
77
+ const out: Record<string, Handler> = {};
78
+ const original = server.tool.bind(server);
79
+ server.tool = (name: string, ...args: any[]) => {
80
+ const h = args.at(-1);
81
+ if (typeof h === "function") out[name] = h;
82
+ return original(name, ...args);
83
+ };
84
+ registerTools(server, undefined, NET, USER, PEER, false, null);
85
+ return out;
86
+ }
87
+
88
+ async function call(handler: Handler, args: any): Promise<any> {
89
+ const r = await handler(args);
90
+ return JSON.parse(r.content[0].text);
91
+ }
92
+
93
+ beforeEach(() => { cleanup(); seed(); });
94
+ afterAll(() => { cleanup(); });
95
+
96
+ describe("#3348 不存在的显式父:父与来源一起丢", () => {
97
+ test("父不存在 ⇒ 任务照样建成,但 parent_task_id 为 NULL 且 meta 里没有 parent_source", async () => {
98
+ const ghost = "00000000-0000-4000-8000-000000000000"; // 不存在的父
99
+ const r = await call(handlers().send_task, {
100
+ alias: TARGET,
101
+ task: "osp dispatch with a ghost parent",
102
+ priority: "normal",
103
+ from_session: PEER,
104
+ network_id: NET,
105
+ parent_task_id: ghost,
106
+ });
107
+ // 丢父是「不阻塞派发」的决定:这条**不能**变成错误,否则一个幻觉 id 会挡掉整条任务。
108
+ expect(r.ok).toBe(true);
109
+
110
+ const row = db.get<{ task_id: string; parent_task_id: string | null; meta_json: string | null }>(
111
+ "SELECT task_id, parent_task_id, meta_json FROM tasks WHERE content = ?1",
112
+ ["osp dispatch with a ghost parent"],
113
+ );
114
+ expect(row).toBeTruthy();
115
+ expect(row!.parent_task_id).toBeNull();
116
+ // 关键断言:来源不许单独留下。
117
+ // 留着的后果是库里出现「有来源、没父」这一格 —— #669 的不变式两个方向都放过它,
118
+ // 于是它既不被算作 explicit 也不被算作无父,只在有人专门数「source 无 parent」时才看得见。
119
+ expect(String(row!.meta_json ?? "")).not.toContain("parent_source");
120
+ });
121
+ });
@@ -51,6 +51,10 @@ const base = { provider_id: PROVIDER, model_name: "probe-model", daemon_node_id:
51
51
 
52
52
  // 2026-11-01 —— **精确键集,写成集合相等**(不是计数、也不是「有这几个字段」)。
53
53
  // 计数可以被换名满足;字段级断言放过多给的键。两者都放过「换名 + 少给」这种最常见的结构变动。
54
+ // 🔴 basis: impl —— 下面这些键集**取自真实调用的响应**,因此它是**变更探测器**,不是契约读数。
55
+ // 红的意思是「实现变了,去看是不是故意的」;而「实现错了」这一类它测不出来
56
+ // (若实现多返回一个字段,断言会红,但那可能是正确的修复)。
57
+ // 要不要升级成 spec 列:需要一处**独立于实现**的书面来源;指不出来时,它就只能留在这里。
54
58
  function expectKeys(obj: Record<string, unknown>, want: string[]) {
55
59
  expect(Object.keys(obj).sort(), "键集合必须完全等于期望").toEqual([...want].sort());
56
60
  }
package/src/server.ts CHANGED
@@ -123,6 +123,7 @@ import { parseHubTimestamp } from "./hub-timestamp";
123
123
  import { logTaskRejection } from "./task-rejection-log.js";
124
124
  import { taskRejectionCounters } from "./rejection-counters.js";
125
125
  import { neverConsumedExpiryCounters, noteNeverConsumedExpiry, neverConsumeGate, persistentNeverConsumedExpiries } from "./expiry-counters.js";
126
+ import { parentInferCounters } from "./parent-infer.js";
126
127
  import { authAbuseSnapshot, noteLoginIpRateLimited, noteLoginLocked, noteRegisterRateLimited } from "./auth-abuse-counters.js";
127
128
  import { legacyLicenseField, licenseStateOf } from "./license-state.js";
128
129
  import { AVATAR_FIELD, avatarUrl, inspectAvatarImage, isMultipart, isValidAvatarVersion, MAX_AVATAR_BYTES, MAX_AVATAR_STORAGE_BYTES } from "./user-avatar-image.js";
@@ -3852,6 +3853,9 @@ return Bun.serve({
3852
3853
  // 比值才是有意义的部分:命中数 ≫ 去重数 ⇒ 单点重试;两者接近 ⇒ 换 IP / 撒网。
3853
3854
  // 只给计数与去重数,不给 IP / 用户名的值(集合本身不出进程)。
3854
3855
  auth_abuse: authAbuseSnapshot(),
3856
+ // #669 —— 父任务推断的收窄效果:accepted 与两个 rejected 一起看,
3857
+ // 否则「收窄了多少」与「收窄没生效」同形(两者都让 7 天失败率下降)。
3858
+ parent_infer: parentInferCounters(),
3855
3859
  },
3856
3860
  // 🔴 2026-10-31 —— 上面那个 counters 对象**不在匿名投影里**(PUBLIC_HEALTH_KEYS)。
3857
3861
  // 而 #3271 交付时我把「观察它有没有 fire」写成了 `/health.counters.…` ——
@@ -50,6 +50,44 @@ function seed() {
50
50
  beforeEach(seed);
51
51
  afterAll(cleanup);
52
52
 
53
+ // #3325 第一格运行时对照 —— 静态口径说「断言写了什么」,这一条说「它实际返回什么」。
54
+ // 只做**键集**比较(不比对值):值的语义要另一套夹具,而键集已经有静态期望可对照。
55
+ describe("#3325 运行时键集(list_tasks 成功路径)", () => {
56
+ test("list_tasks 成功响应的键集 == 静态期望(两者不符即有一侧是缺陷)", async () => {
57
+ const r = await call("list_tasks", { limit: 20 });
58
+ expect(r.ok).toBe(true);
59
+ // 这个期望来自**一次真实调用**(先跑出来,再抄进来),因此它同时是:
60
+ // ① 运行时事实(它刚刚确实这么返回)
61
+ // ② 变更探测器(实现改了键 ← 会红)
62
+ // 它**不是**契约读数:指不出一份独立于实现的书面来源。
63
+ // 🔴 我第一次写的是四个键(count/ok/stats/tasks)—— 真实调用给出 **五个**:
64
+ // `next_cursor` 也在里面。这就是这一格存在的理由:静态读代码得到的键集是
65
+ // 「我以为它返回什么」,而运行时对照得到的是「它实际返回什么」。
66
+ expect(Object.keys(r).sort()).toEqual([
67
+ "count", "next_cursor", "ok", "stats", "tasks",
68
+ ].sort());
69
+ // 空库时这几格的具体形态也钉住(**第二次被真实调用纠正**:我写「stats 是对象」,
70
+ // 实测它是**数组** —— 源码里 stats 来自 `GROUP BY status` 的 db.all(...),本来就是行数组)。
71
+ expect(r.count).toBe(0);
72
+ expect(r.tasks).toEqual([]);
73
+ expect(Array.isArray(r.stats)).toBe(true);
74
+ });
75
+ });
76
+
77
+ describe("#3325 运行时键集(get_task 失败路径)", () => {
78
+ test("get_task 的失败载荷**只有两个键**(运行时,不是从代码读出来的)", async () => {
79
+ // 我原本想钉 get_task 的**成功**键集,插了一行 tasks 之后仍回 "task not found"
80
+ // (它的可见性不看 from_name/to_name,我这里没构造出能被看见的那一行)。
81
+ // 于是改成钉失败载荷 —— 它同样是运行时读数,且这条**碰巧**是可判的:
82
+ // 失败体若哪天多带了 `task_id` 之类的定位信息,这条会红。
83
+ const r = await call("get_task", { task_id: "task_rt_missing" });
84
+ expect(r.ok).toBe(false);
85
+ expect(Object.keys(r).sort()).toEqual(["error", "ok"].sort());
86
+ // 成功路径的那一格**没做成**,记在这里而不是假装有:
87
+ // 需要一份「调用者视角可见」的 task 行(其可见性不由 from/to 决定),未构造出来。
88
+ });
89
+ });
90
+
53
91
  describe('#3309 「task not found」:三个工具共用同一句话', () => {
54
92
  test("三个工具在不存在的 id 上给出**同一句**(逐字相同)", async () => {
55
93
  const missing = "task_9th_does_not_exist";
package/src/tools.ts CHANGED
@@ -114,6 +114,7 @@ import { listTaskLateReplies } from "./task-late-replies.js";
114
114
  import { pollPacer } from "./poll-pacing.js";
115
115
  import { neverConsumedExpiryCounters, neverConsumeGate, persistentNeverConsumedExpiries } from "./expiry-counters.js";
116
116
  import { auditDepartment, createDepartment, deleteDepartment, listDepartments, setAgentDepartment, updateDepartment } from "./departments.js";
117
+ import { decideParentInference, noteInferAccepted, noteInferRejected } from "./parent-infer.js";
117
118
 
118
119
  function ts(): string {
119
120
  return new Date().toTimeString().slice(0, 8);
@@ -2125,12 +2126,25 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
2125
2126
  let parentSource: "explicit" | "inferred" | null = parentIn ? "explicit" : null;
2126
2127
  if (!humanSender && !parentTaskId && from_session && from_session !== "hub" && from_session !== "api") {
2127
2128
  try {
2129
+ // #669 —— 取**全部**候选而非最近一条:裁定需要知道「是不是唯一」。
2128
2130
  const recentParams: any[] = [from_session];
2129
- let recentSql = "SELECT task_id FROM tasks WHERE to_name = ?1 AND status IN ('delivered')"; // board668-parent-delivered-only
2131
+ let recentSql = "SELECT task_id, created_at FROM tasks WHERE to_name = ?1 AND status IN ('delivered')"; // board668-parent-delivered-only
2130
2132
  recentSql = addScope(recentSql, recentParams, effectiveNetId);
2131
- recentSql += " ORDER BY created_at DESC LIMIT 1";
2132
- const recent = db.get<{ task_id: string }>(recentSql, ...recentParams);
2133
- if (recent?.task_id) { parentTaskId = recent.task_id; parentSource = "inferred"; }
2133
+ recentSql += " ORDER BY created_at DESC LIMIT 5";
2134
+ const cands = db.all<{ task_id: string; created_at: string | null }>(recentSql, ...recentParams);
2135
+ const verdict = decideParentInference(
2136
+ cands.map((c) => ({ task_id: c.task_id, created_at_ms: c.created_at ? Date.parse(c.created_at) : null })),
2137
+ Date.now(),
2138
+ );
2139
+ if (verdict.ok) {
2140
+ parentTaskId = verdict.task_id;
2141
+ parentSource = "inferred";
2142
+ noteInferAccepted();
2143
+ } else if (verdict.rejection.candidates > 0) {
2144
+ // 只有「本来有候选但被拒」才计数:没有候选是常态(没有要接的任务),
2145
+ // 把它记成拒绝会让分母虚高。
2146
+ noteInferRejected(verdict.rejection);
2147
+ }
2134
2148
  } catch {}
2135
2149
  }
2136
2150
 
@@ -2160,6 +2174,15 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
2160
2174
  // still proceed; the LLM may have meant to dispatch fresh.
2161
2175
  console.log(`[${ts()}] ⚠ send_task: parent_task_id=${parentIn.slice(0, 8)} not found, dropping parent link`);
2162
2176
  parentTaskId = null;
2177
+ // #3348 —— **来源必须与父一起丢弃**。
2178
+ // 上面那段 meta 是在父校验**之前**拼的(`if (parentSource && parentTaskId)` 当时为真),
2179
+ // 而这里才把 parentTaskId 置空 ⇒ 落库会留下
2180
+ // parent_task_id = NULL,meta.parent_source = "explicit"
2181
+ // 这一格。#669 那条不变式正是「父有值 ⇒ 来源有值」,它只挡住了反方向
2182
+ // (父为空时来源也不必在),于是这一格两边都放过。
2183
+ // 生产实测:131684 行里有 2 条落在这里(10-30、10-31 各一条)。
2184
+ parentSource = null;
2185
+ metaJsonWithParent = metaJson;
2163
2186
  } else if ((parentRow.network_id ?? null) !== (effectiveNetId ?? null)) {
2164
2187
  console.log(`[${ts()}] 🚫 send_task: cross-network parent rejected, parent=${parentIn.slice(0, 8)} parent-net=${parentRow.network_id ?? "null"} caller-net=${effectiveNetId ?? "null"}`);
2165
2188
  return { content: [{ type: "text" as const, text: JSON.stringify({