@sleep2agi/commhub-server 0.9.0-preview.265 → 0.9.0-preview.267

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": "67b398a34011ddc3b7eb8beb0299b790e54fe618",
3
+ "commit": "54d87dd2c5a1d5261b5953a6fc1204e34024c0cb",
4
4
  "dirty": false,
5
- "built_at": "2026-11-01T11:04:39.383Z",
5
+ "built_at": "2026-11-05T12:41:26.525Z",
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.265",
3
+ "version": "0.9.0-preview.267",
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",
@@ -11,6 +11,7 @@
11
11
  // 成员资格仍由调用方原有的 getUserNetworkRole 判定。两件事分开,别合并成一个判据。
12
12
 
13
13
  import { db } from "./db.js";
14
+ import { departmentSubtree } from "./department-heads.js";
14
15
 
15
16
  const UNRESTRICTED_ROLES = new Set(["owner", "admin"]);
16
17
 
@@ -98,7 +99,7 @@ export function visibleAgents(userId: string, networkId: string): VisibleAgents
98
99
  const messageNodeIds = new Set<string>();
99
100
  // RFC-038 §8:组授权展开成「该组此刻的成员节点」—— 每次现算,组里新加的节点下一次请求就可见。
100
101
  // 只并同网络、且 nodes 表里还在的节点;可对话取并集(直接授权或任一组给了就算)。
101
- const grants: AgentGrant[] = [...listAgentGrants(networkId, userId), ...groupGrantNodes(networkId, userId)];
102
+ const grants: AgentGrant[] = [...listAgentGrants(networkId, userId), ...groupGrantNodes(networkId, userId), ...departmentGrantNodes(networkId, userId)];
102
103
  // #2133:所有授权节点的 alias 一次查完(原来每个节点单独查一次 nodes ∪ sessions:300 条授权 ≈ 300 次查询,
103
104
  // 而受限成员的每次 /api/status 轮询都走这里)。结果与原实现逐字一致:授权按上面数组的顺序,
104
105
  // 同一节点内的 alias 按 UNION 的去重升序 —— agent-access-batch.test.ts 在随机夹具上逐字比对。
@@ -168,6 +169,68 @@ export function listGroupGrants(networkId: string, userId: string): AgentGroupGr
168
169
  ).map((row) => ({ group_id: row.group_id, name: row.name, can_message: row.can_message === 1 }));
169
170
  }
170
171
 
172
+ // ══════════════ 部门维度授权(admin 2026-11-05) ══════════════
173
+ //
174
+ // 用户问的是「给某个用户授权,让他看到**某个组织架构下**的所有节点」。
175
+ // Agent 组授权(RFC-038 §8)回答的是 Agent 侧的树;人的组织架构是另一条轴
176
+ // (network_departments + nodes.department_id),此前**没有**这一档。
177
+ //
178
+ // 语义与组授权完全同构,只有展开源不同:
179
+ // 组 ⇒ agent_group_members
180
+ // 部门 ⇒ departmentSubtree(dept) 里的所有部门 → nodes.department_id ∈ 该集合
181
+ // 同样是**每次现算**:部门里新挂的节点,下一次请求就可见,不需要重新授权。
182
+ //
183
+ // 已知边界(必须让调用方看见,否则会静默少人):
184
+ // 没有填 department_id 的节点**永远**不会因为部门授权而可见。
185
+ // ⇒ 接口把它作为 `coverage` 一起返回,而不是让人以为「授权了就应该全看见」。
186
+
187
+ export type DepartmentGrant = { department_id: string; name: string; can_message: boolean };
188
+
189
+ export function departmentGrantNodes(networkId: string, userId: string): AgentGrant[] {
190
+ const rows = db.all<{ department_id: string; can_message: number }>(
191
+ "SELECT department_id, can_message FROM network_member_department_grants WHERE network_id = ?1 AND user_id = ?2",
192
+ networkId, userId,
193
+ );
194
+ if (rows.length === 0) return [];
195
+ const canMessage = new Map<string, boolean>();
196
+ for (const row of rows) {
197
+ for (const deptId of departmentSubtree(networkId, row.department_id)) {
198
+ // 任一授权允许对话即允许(与组授权「取并集」一致)。
199
+ canMessage.set(deptId, (canMessage.get(deptId) ?? false) || row.can_message === 1);
200
+ }
201
+ }
202
+ if (canMessage.size === 0) return [];
203
+ const deptIds = [...canMessage.keys()];
204
+ const inList = deptIds.map((_, i) => `?${i + 2}`).join(", ");
205
+ return db.all<{ node_id: string; department_id: string }>(
206
+ `SELECT node_id, department_id FROM nodes WHERE network_id = ?1 AND department_id IN (${inList}) ORDER BY node_id`,
207
+ networkId, ...deptIds,
208
+ ).map((row) => ({ node_id: row.node_id, alias: null, can_message: canMessage.get(row.department_id) === true }));
209
+ }
210
+
211
+ export function listDepartmentGrants(networkId: string, userId: string): DepartmentGrant[] {
212
+ return db.all<{ department_id: string; name: string | null; can_message: number }>(
213
+ `SELECT g.department_id, d.name, g.can_message
214
+ FROM network_member_department_grants g
215
+ LEFT JOIN network_departments d ON d.department_id = g.department_id AND d.network_id = g.network_id
216
+ WHERE g.network_id = ?1 AND g.user_id = ?2 ORDER BY d.name, g.department_id`,
217
+ networkId, userId,
218
+ ).map((row) => ({ department_id: row.department_id, name: row.name ?? row.department_id, can_message: row.can_message === 1 }));
219
+ }
220
+
221
+ /** 覆盖率:网络里有多少节点填了部门、有多少没填(没填的永远不可能被部门授权覆盖)。 */
222
+ export function departmentCoverage(networkId: string): { nodes_total: number; nodes_with_department: number; nodes_without_department: number } {
223
+ const row = db.get<{ total: number; with_dept: number }>(
224
+ `SELECT COUNT(*) AS total,
225
+ SUM(CASE WHEN department_id IS NOT NULL AND department_id <> '' THEN 1 ELSE 0 END) AS with_dept
226
+ FROM nodes WHERE network_id = ?1`,
227
+ networkId,
228
+ );
229
+ const total = row?.total ?? 0;
230
+ const withDept = row?.with_dept ?? 0;
231
+ return { nodes_total: total, nodes_with_department: withDept, nodes_without_department: total - withDept };
232
+ }
233
+
171
234
  export function listAgentGroups(networkId: string): AgentGroup[] {
172
235
  const groups = db.all<{ group_id: string; network_id: string; name: string; description: string | null; created_at: string; updated_at: string | null }>(
173
236
  "SELECT group_id, network_id, name, description, created_at, updated_at FROM agent_groups WHERE network_id = ?1 ORDER BY name",
@@ -331,7 +394,7 @@ export function canMessageAgent(userId: string, networkId: string | null | undef
331
394
  export type AgentGrantInput = { node_id?: unknown; alias?: unknown; can_message?: unknown };
332
395
 
333
396
  export type ReplaceGrantsResult =
334
- | { ok: true; agent_access: AgentAccessMode; grants: AgentGrant[]; group_grants: AgentGroupGrant[] }
397
+ | { ok: true; agent_access: AgentAccessMode; grants: AgentGrant[]; group_grants: AgentGroupGrant[]; department_grants: DepartmentGrant[] }
335
398
  | { ok: false; error: string; status: number; detail?: unknown };
336
399
 
337
400
  const MAX_GRANTS = 1000;
@@ -347,6 +410,8 @@ export function replaceAgentGrants(input: {
347
410
  agentAccess?: unknown;
348
411
  /** RFC-038 §8:组授权。undefined = 保持原样(旧 app 的 PUT 不带它,不能把组授权清掉)。 */
349
412
  groupGrants?: unknown;
413
+ /** 部门维度授权。undefined = 保持原样(旧客户端的 PUT 不带它,不能把部门授权清掉)。 */
414
+ departmentGrants?: unknown;
350
415
  actorUserId: string;
351
416
  }): ReplaceGrantsResult {
352
417
  const member = db.get<{ role: string }>(
@@ -415,7 +480,38 @@ export function replaceAgentGrants(input: {
415
480
  }
416
481
  }
417
482
 
483
+ let departmentRows: Array<{ department_id: string; can_message: number }> | undefined;
484
+ if (input.departmentGrants !== undefined) {
485
+ if (!Array.isArray(input.departmentGrants)) return { ok: false, error: "department_grants_must_be_array", status: 400 };
486
+ if (input.departmentGrants.length > MAX_GRANTS) return { ok: false, error: "too_many_grants", status: 400, detail: { limit: MAX_GRANTS } };
487
+ const seenDepts = new Set<string>();
488
+ departmentRows = [];
489
+ for (const [index, raw] of input.departmentGrants.entries()) {
490
+ const item = typeof raw === "string" ? { department_id: raw } : (raw && typeof raw === "object" && !Array.isArray(raw) ? raw as { department_id?: unknown; can_message?: unknown } : {});
491
+ const deptId = typeof item.department_id === "string" ? item.department_id.trim() : "";
492
+ if (!deptId) return { ok: false, error: "department_grant_needs_department_id", status: 400, detail: { index } };
493
+ if (item.can_message !== undefined && typeof item.can_message !== "boolean") {
494
+ return { ok: false, error: "can_message_must_be_boolean", status: 400, detail: { index } };
495
+ }
496
+ if (!db.get("SELECT 1 FROM network_departments WHERE department_id = ?1 AND network_id = ?2", deptId, input.networkId)) {
497
+ return { ok: false, error: "department_not_in_network", status: 400, detail: { index, department_id: deptId } };
498
+ }
499
+ if (seenDepts.has(deptId)) continue;
500
+ seenDepts.add(deptId);
501
+ departmentRows.push({ department_id: deptId, can_message: item.can_message === false ? 0 : 1 });
502
+ }
503
+ }
504
+
418
505
  db.transaction(() => {
506
+ if (departmentRows) {
507
+ db.run("DELETE FROM network_member_department_grants WHERE network_id = ?1 AND user_id = ?2", [input.networkId, input.userId]);
508
+ for (const row of departmentRows) {
509
+ db.run(
510
+ `INSERT INTO network_member_department_grants (network_id, user_id, department_id, can_message, created_by) VALUES (?1, ?2, ?3, ?4, ?5)`,
511
+ [input.networkId, input.userId, row.department_id, row.can_message, input.actorUserId],
512
+ );
513
+ }
514
+ }
419
515
  if (groupRows) {
420
516
  db.run("DELETE FROM network_member_group_grants WHERE network_id = ?1 AND user_id = ?2", [input.networkId, input.userId]);
421
517
  for (const row of groupRows) {
@@ -445,6 +541,7 @@ export function replaceAgentGrants(input: {
445
541
  agent_access: getAgentAccessMode(input.networkId, input.userId) ?? "granted",
446
542
  grants: listAgentGrants(input.networkId, input.userId),
447
543
  group_grants: listGroupGrants(input.networkId, input.userId),
544
+ department_grants: listDepartmentGrants(input.networkId, input.userId),
448
545
  };
449
546
  }
450
547
 
@@ -452,6 +549,7 @@ export function replaceAgentGrants(input: {
452
549
  export function deleteAgentGrants(networkId: string, userId: string): void {
453
550
  db.run("DELETE FROM network_member_agent_grants WHERE network_id = ?1 AND user_id = ?2", [networkId, userId]);
454
551
  db.run("DELETE FROM network_member_group_grants WHERE network_id = ?1 AND user_id = ?2", [networkId, userId]);
552
+ db.run("DELETE FROM network_member_department_grants WHERE network_id = ?1 AND user_id = ?2", [networkId, userId]);
455
553
  }
456
554
 
457
555
  // 多用户 Agent 权限 —— 受限成员(只看授权 Agent 的成员)能调的 MCP 工具。每一个都逐条审过:
@@ -0,0 +1,129 @@
1
+ // #3432 —— 部门维度授权:把「人的组织架构」当授权单位。
2
+ //
3
+ // 用户问的是「给某个用户授权,让他看到某个组织架构下的所有节点」。
4
+ // 此前只有三档:all / 逐 Agent / Agent 组 —— 前两档都不回答这个问题,
5
+ // 第三档是 **Agent 侧**的树,而人的组织架构是另一条轴(network_departments + nodes.department_id)。
6
+ //
7
+ // 判据分两半,缺一半就只是「能写进去」:
8
+ // ① 能看到:授权部门 D ⇒ D 与全部下级部门里的节点可见(含下级,这才是「组织架构下」)
9
+ // ② 不该看到的看不到:没填部门的节点、别的部门的节点,都不出现(镜像否定)
10
+ import './require-explicit-test-db';
11
+ // network_departments 是在 departments.ts 的模块顶层建的(不是 db.ts)。
12
+ // 不把这个 import 放进来,测试会直接报 no such table —— 而生产是因为 server.ts 导入了它。
13
+ import './departments';
14
+ import { afterAll, beforeEach, describe, expect, test } from 'bun:test';
15
+ import { db } from './db';
16
+ import {
17
+ departmentGrantNodes,
18
+ visibleAgents,
19
+ replaceAgentGrants,
20
+ listDepartmentGrants,
21
+ departmentCoverage,
22
+ } from './agent-access';
23
+
24
+ const net = 'net_deptgrant';
25
+ const user = 'u_deptgrant';
26
+ const actor = 'u_deptgrant_actor';
27
+ const root = 'd_root';
28
+ const child = 'd_child';
29
+ const other = 'd_other';
30
+
31
+ function cleanup() {
32
+ for (const t of ['network_member_agent_grants', 'network_member_group_grants', 'network_member_department_grants']) {
33
+ try { db.run(`DELETE FROM ${t} WHERE network_id = ?1`, [net]); } catch {}
34
+ }
35
+ db.run('DELETE FROM nodes WHERE network_id = ?1', [net]);
36
+ db.run('DELETE FROM network_departments WHERE network_id = ?1', [net]);
37
+ db.run('DELETE FROM network_members WHERE network_id = ?1', [net]);
38
+ db.run('DELETE FROM networks WHERE network_id = ?1', [net]);
39
+ db.run('DELETE FROM users WHERE user_id IN (?1, ?2)', [user, actor]);
40
+ }
41
+
42
+ beforeEach(() => {
43
+ cleanup();
44
+ db.run("INSERT INTO users(user_id,username,password_hash,role) VALUES(?1,?1,'x','user')", [user]);
45
+ db.run("INSERT INTO users(user_id,username,password_hash,role) VALUES(?1,?1,'x','user')", [actor]);
46
+ db.run('INSERT INTO networks(network_id,network_name,owner_id) VALUES(?1,?1,?2)', [net, actor]);
47
+ db.run("INSERT INTO network_members(user_id,network_id,role,agent_access) VALUES(?1,?2,'member','granted')", [user, net]);
48
+ db.run("INSERT INTO network_members(user_id,network_id,role,agent_access) VALUES(?1,?2,'owner','all')", [actor, net]);
49
+ // 三棵子树:root(父) → child(子);另一棵 other。
50
+ for (const [id, parent] of [[root, null], [child, root], [other, null]] as const) {
51
+ db.run('INSERT INTO network_departments(network_id,department_id,name,parent_id) VALUES(?1,?2,?2,?3)', [net, id, parent]);
52
+ }
53
+ const node = (id: string, dept: string | null) => db.run(
54
+ 'INSERT INTO nodes(node_id,node_name,alias,network_id,department_id) VALUES(?1,?1,?1,?2,?3)', [id, net, dept]);
55
+ node('n_root_direct', root);
56
+ node('n_child_member', child); // 下级部门里的节点
57
+ node('n_other_dept', other);
58
+ node('n_no_dept', null); // 没填部门:永远不该因部门授权而可见
59
+ });
60
+ afterAll(cleanup);
61
+
62
+ const grantDept = (deptId: string, canMessage = true) => replaceAgentGrants({
63
+ networkId: net, userId: user, grants: [], actorUserId: actor,
64
+ departmentGrants: [{ department_id: deptId, can_message: canMessage }],
65
+ });
66
+
67
+ describe("#3432 部门维度授权", () => {
68
+ test("① 授权部门 root ⇒ root 自己与**下级** child 里的节点都可见", () => {
69
+ const r = grantDept(root);
70
+ expect(r.ok).toBe(true);
71
+ const ids = departmentGrantNodes(net, user).map((g) => g.node_id).sort();
72
+ expect(ids).toEqual(['n_child_member', 'n_root_direct']);
73
+ const visible = visibleAgents(user, net);
74
+ expect(visible.nodeIds.sort()).toEqual(['n_child_member', 'n_root_direct']);
75
+ });
76
+
77
+ test("② 镜像否定:没填部门的节点、别的部门的节点都不出现", () => {
78
+ grantDept(root);
79
+ const ids = departmentGrantNodes(net, user).map((g) => g.node_id);
80
+ expect(ids).not.toContain('n_no_dept');
81
+ expect(ids).not.toContain('n_other_dept');
82
+ });
83
+
84
+ test("can_message 随部门授权传递;一处 false 不影响另一处 true(取并集)", () => {
85
+ replaceAgentGrants({
86
+ networkId: net, userId: user, grants: [], actorUserId: actor,
87
+ departmentGrants: [{ department_id: root, can_message: false }, { department_id: other, can_message: true }],
88
+ });
89
+ const byId = new Map(departmentGrantNodes(net, user).map((g) => [g.node_id, g.can_message]));
90
+ expect(byId.get('n_root_direct')).toBe(false);
91
+ expect(byId.get('n_other_dept')).toBe(true);
92
+ });
93
+
94
+ test("撤掉授权 ⇒ 立刻看不见(现算,不留缓存)", () => {
95
+ grantDept(root);
96
+ expect(departmentGrantNodes(net, user).length).toBe(2);
97
+ grantDept('') /* 非法,整批拒绝 */;
98
+ replaceAgentGrants({ networkId: net, userId: user, grants: [], actorUserId: actor, departmentGrants: [] });
99
+ expect(departmentGrantNodes(net, user)).toEqual([]);
100
+ });
101
+
102
+ test("部门里新挂的节点,下一次请求就可见(与组授权同一语义)", () => {
103
+ grantDept(root);
104
+ db.run('INSERT INTO nodes(node_id,node_name,alias,network_id,department_id) VALUES(?1,?1,?1,?2,?3)',
105
+ ['n_new_in_child', net, child]);
106
+ expect(departmentGrantNodes(net, user).map((g) => g.node_id)).toContain('n_new_in_child');
107
+ });
108
+
109
+ test("不在本网络的部门 ⇒ department_not_in_network(不静默忽略)", () => {
110
+ const r = replaceAgentGrants({
111
+ networkId: net, userId: user, grants: [], actorUserId: actor,
112
+ departmentGrants: [{ department_id: 'd_does_not_exist' }],
113
+ });
114
+ expect(r.ok).toBe(false);
115
+ if (!r.ok) expect(r.error).toBe('department_not_in_network');
116
+ });
117
+
118
+ test("listDepartmentGrants 带出部门名;coverage 把「没填部门」明说出来", () => {
119
+ grantDept(root);
120
+ expect(listDepartmentGrants(net, user)).toEqual([{ department_id: root, name: root, can_message: true }]);
121
+ expect(departmentCoverage(net)).toEqual({ nodes_total: 4, nodes_with_department: 3, nodes_without_department: 1 });
122
+ });
123
+
124
+ test("传 undefined 时不清空已有部门授权(旧客户端的 PUT 不带这个键)", () => {
125
+ grantDept(root);
126
+ replaceAgentGrants({ networkId: net, userId: user, grants: [], actorUserId: actor });
127
+ expect(listDepartmentGrants(net, user).length).toBe(1);
128
+ });
129
+ });
package/src/db.ts CHANGED
@@ -1219,6 +1219,22 @@ db.exec(`
1219
1219
  -- 展开查询本身走各表主键,见 agent-groups-perf.test.ts 的 EXPLAIN QUERY PLAN。
1220
1220
  CREATE INDEX IF NOT EXISTS idx_group_grants_group ON network_member_group_grants(group_id);
1221
1221
  `);
1222
+ // ── #3432(admin 2026-11-05) 部门维度授权:把「人的组织架构」当成授权单位 ──
1223
+ // 与组授权同构(每次现算展开),差别只在展开源是 departments 子树 + nodes.department_id。
1224
+ // 单独一张表:组那张表的主键/语义都是 Agent 侧的,部门是人的树,混在一张表里以后分不清。
1225
+ db.exec(`
1226
+ CREATE TABLE IF NOT EXISTS network_member_department_grants (
1227
+ network_id TEXT NOT NULL,
1228
+ user_id TEXT NOT NULL,
1229
+ department_id TEXT NOT NULL,
1230
+ can_message INTEGER NOT NULL DEFAULT 1,
1231
+ created_by TEXT,
1232
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
1233
+ PRIMARY KEY (network_id, user_id, department_id)
1234
+ );
1235
+ CREATE INDEX IF NOT EXISTS idx_dept_grants_user ON network_member_department_grants(network_id, user_id);
1236
+ `);
1237
+
1222
1238
 
1223
1239
  // ── #84: node rename — rename_txn table (RFC-010 §4) ──
1224
1240
  // Single isolated table holding the rename 2PC transaction state. It doubles
@@ -0,0 +1,96 @@
1
+ // #3119 —— list_tasks 的增量与「省掉 stats」。
2
+ //
3
+ // 生产实测(2026-11-05 近 6h):list_tasks 占全部工具调用 **35.7%**,是最大的一格;
4
+ // 提示词只能劝,改不了接口成本。这里补两个参数,让轮询本身变便宜:
5
+ // created_since 只取这之后创建的(空窗口回极短体)
6
+ // omit_stats 跳过按状态的全表 GROUP BY(轮询时它比任务列表还贵)
7
+ // server_time 服务端给水位,客户端别用本地时钟(差几秒就漏活或重复)
8
+ //
9
+ // 判据分四格,缺一格都只是「加了个参数」:
10
+ // ① created_since 真的过滤(旧的看不见、新的看得见)
11
+ // ② 镜像:不传 created_since ⇒ 行为与以前一致(旧调用方零影响)
12
+ // ③ omit_stats 真的不返回 stats,且返回值里明确写着 stats_omitted
13
+ // ④ server_time 一定在(两种分支都有),否则客户端拿不到水位
14
+ import './require-explicit-test-db';
15
+ import { afterAll, beforeEach, describe, expect, test } from 'bun:test';
16
+ import { db } from './db';
17
+ import { registerTools } from './tools';
18
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
19
+
20
+ const net = 'net_list_tasks_since';
21
+ const user = 'u_list_tasks_since';
22
+ // username 必须等于某个 nodes/sessions 的 alias,否则受限成员过滤会把任务全挡掉
23
+ const alias = user;
24
+
25
+ function client() {
26
+ const handlers: Record<string, any> = {};
27
+ const server = new McpServer({ name: 't-since', version: '0' }) as any;
28
+ const tool = server.tool.bind(server);
29
+ server.tool = (name: string, desc: any, shape: any, handler: any) => { handlers[name] = handler; return tool(name, desc, shape, handler); };
30
+ registerTools(server, undefined, null, user, alias, false, null);
31
+ return async (name: string, args: any = {}) => JSON.parse((await handlers[name](args)).content[0].text);
32
+ }
33
+
34
+ function cleanup() {
35
+ db.run('DELETE FROM tasks WHERE task_id LIKE ?1', ['t_since_%']);
36
+ db.run('DELETE FROM nodes WHERE network_id=?1', [net]);
37
+ db.run('DELETE FROM network_members WHERE network_id=?1', [net]);
38
+ db.run('DELETE FROM networks WHERE network_id=?1', [net]);
39
+ db.run('DELETE FROM users WHERE user_id=?1', [user]);
40
+ }
41
+
42
+ beforeEach(() => {
43
+ cleanup();
44
+ db.run("INSERT INTO users(user_id,username,password_hash,role) VALUES(?1,?1,'x','user')", [user]);
45
+ db.run('INSERT INTO networks(network_id,network_name,owner_id) VALUES(?1,?1,?2)', [net, user]);
46
+ db.run("INSERT INTO network_members(user_id,network_id,role) VALUES(?1,?2,'owner')", [user, net]);
47
+ // caller 的 username 必须能被认成「本网络的 Agent」,否则 addAgentTimelineScope 会按
48
+ // 受限成员把任务全过滤掉(那是安全边界,不是 bug)。建一行 nodes 让它认得出。
49
+ db.run('INSERT INTO nodes(node_id,node_name,alias,network_id) VALUES(?1,?2,?2,?3)', ['n_since', alias, net]);
50
+ // 两条任务:一条旧、一条新(时间列是 TEXT,字典序即时间序)
51
+ db.run(`INSERT INTO tasks(task_id, from_name, to_name, status, content, created_at, network_id)
52
+ VALUES ('t_since_old', 'peer', ?1, 'delivered', 'old work', '2026-11-05 01:00:00', ?2)`, [alias, net]);
53
+ db.run(`INSERT INTO tasks(task_id, from_name, to_name, status, content, created_at, network_id)
54
+ VALUES ('t_since_new', 'peer', ?1, 'delivered', 'new work', '2026-11-05 09:00:00', ?2)`, [alias, net]);
55
+ });
56
+ afterAll(cleanup);
57
+
58
+ describe("#3119 list_tasks 的增量与水印", () => {
59
+ test("① created_since 生效:旧的看不见、新的看得见", async () => {
60
+ const call = client();
61
+ const r = await call('list_tasks', { alias, network_id: net, created_since: '2026-11-05 08:00:00', omit_stats: true, limit: 20 });
62
+ expect(r.ok).toBe(true);
63
+ expect(r.tasks.map((t: any) => t.task_id)).toEqual(['t_since_new']);
64
+ });
65
+
66
+ test("② 镜像:不传 created_since ⇒ 两条都在(旧调用方零影响)", async () => {
67
+ const call = client();
68
+ const r = await call('list_tasks', { alias, network_id: net, limit: 20 });
69
+ expect(r.tasks.map((t: any) => t.task_id).sort()).toEqual(['t_since_new', 't_since_old']);
70
+ expect(r.stats).toBeDefined();
71
+ });
72
+
73
+ test("③ omit_stats ⇒ 不返回 stats,并明确写 stats_omitted(不是静默少一格)", async () => {
74
+ const call = client();
75
+ const r = await call('list_tasks', { alias, network_id: net, omit_stats: true, limit: 20 });
76
+ expect(r.stats).toBeUndefined();
77
+ expect(r.stats_omitted).toBe(true);
78
+ });
79
+
80
+ test("④ 两种分支都带 server_time(客户端的水位来源)", async () => {
81
+ const call = client();
82
+ const a = await call('list_tasks', { alias, network_id: net, limit: 20 });
83
+ const b = await call('list_tasks', { alias, network_id: net, omit_stats: true, limit: 20 });
84
+ expect(typeof a.server_time).toBe('string');
85
+ expect(typeof b.server_time).toBe('string');
86
+ expect(Number.isNaN(Date.parse(a.server_time))).toBe(false);
87
+ });
88
+
89
+ test("空窗口 ⇒ 短响应(tasks 空、无 stats、仍有 server_time)", async () => {
90
+ const call = client();
91
+ const r = await call('list_tasks', { alias, network_id: net, created_since: '2099-01-01 00:00:00', omit_stats: true, limit: 20 });
92
+ expect(r.tasks).toEqual([]);
93
+ expect(r.count).toBe(0);
94
+ expect(typeof r.server_time).toBe('string');
95
+ });
96
+ });
package/src/server.ts CHANGED
@@ -53,7 +53,7 @@ import { restrictedMemberSeesFile, restrictedMemberAttachmentsDenied } from "./r
53
53
  import { dmParticipantSeesFile, listDmThread, listDmThreads, sendHumanDm } from "./human-dm.js";
54
54
  import { groupMemberSeesFile, groupUnreadFor, listGroupMessages, listGroupThreads, markGroupRead, memberGroup, sendGroupMessage } from "./group-messages.js";
55
55
  import { getTaskAccessMode, isTaskScoped, listProjectGrants, replaceTaskGrants, newMemberTaskAccess } from "./task-access.js";
56
- import { canMessageAgent, isAgentRestricted, visibleAgents, listAgentGrants, listGroupGrants, getAgentAccessMode, replaceAgentGrants, restrictedNetworkIds, usernameIsAgentAlias, listAgentGroups, createAgentGroup, updateAgentGroup, replaceAgentGroupMembers, deleteAgentGroup, usersGrantedGroup } from "./agent-access.js";
56
+ import { canMessageAgent, isAgentRestricted, visibleAgents, listAgentGrants, listGroupGrants, getAgentAccessMode, replaceAgentGrants, restrictedNetworkIds, usernameIsAgentAlias, listAgentGroups, createAgentGroup, updateAgentGroup, replaceAgentGroupMembers, deleteAgentGroup, usersGrantedGroup, listDepartmentGrants, departmentCoverage } from "./agent-access.js";
57
57
  import { broadcastVerdict, dispatchVerdict, humanOnlyVerdict, NODE_PERMISSION_MODES, nodeDecide, nodeIdentity, nodePermissionDeniedBody, nodePermissionsFlag, streamVerdict, writeVerdict, type NodeIdentity, type NodePermissionMode, type Verdict } from "./node-permissions.js";
58
58
  import { validateAvatarUrl } from "./avatar-validate.js";
59
59
  import { narrowTags, parseStoredTags, validateScalarAttr } from "./node-attrs-validate.js";
@@ -3050,6 +3050,11 @@ return Bun.serve({
3050
3050
  restricted: isAgentRestricted(targetUid, netId),
3051
3051
  grants: listAgentGrants(netId, targetUid),
3052
3052
  group_grants: listGroupGrants(netId, targetUid),
3053
+ // 部门维度授权(admin 2026-11-05):与组授权同构,展开源是部门子树。
3054
+ department_grants: listDepartmentGrants(netId, targetUid),
3055
+ // 覆盖率必须一起给:没填 department_id 的节点永远不可能被部门授权覆盖,
3056
+ // 否则用户会以为「授权了就该全看见」,然后在界面上找不到人。
3057
+ department_coverage: departmentCoverage(netId),
3053
3058
  }));
3054
3059
  }
3055
3060
  // 网络 admin 不能改 owner / 其他 admin 的授权(对他们本来也不生效,但别让 admin 去碰平级)。
@@ -3059,7 +3064,8 @@ return Bun.serve({
3059
3064
  let body: any;
3060
3065
  try { body = await req.json(); } catch { return withCors(req, Response.json({ ok: false, error: "invalid JSON" }, { status: 400 })); }
3061
3066
  if (!body || typeof body !== "object" || Array.isArray(body)) return withCors(req, Response.json({ ok: false, error: "invalid JSON" }, { status: 400 }));
3062
- if (body.grants === undefined && body.node_ids === undefined && body.agent_access === undefined && body.group_grants === undefined) {
3067
+ if (body.grants === undefined && body.node_ids === undefined && body.agent_access === undefined
3068
+ && body.group_grants === undefined && body.department_grants === undefined) {
3063
3069
  return withCors(req, Response.json({ ok: false, error: "grants or agent_access required" }, { status: 400 }));
3064
3070
  }
3065
3071
  const result = replaceAgentGrants({
@@ -3068,13 +3074,14 @@ return Bun.serve({
3068
3074
  grants: body.grants ?? body.node_ids,
3069
3075
  agentAccess: body.agent_access,
3070
3076
  groupGrants: body.group_grants,
3077
+ departmentGrants: body.department_grants,
3071
3078
  actorUserId: resolved.user.user_id,
3072
3079
  });
3073
3080
  if (!result.ok) {
3074
3081
  return withCors(req, Response.json({ ok: false, error: result.error, ...(result.detail ? { detail: result.detail } : {}) }, { status: result.status }));
3075
3082
  }
3076
3083
  logAudit(resolved.user.user_id, resolved.user.username, "member_agent_grants_changed", "network", netId,
3077
- JSON.stringify({ user_id: targetUid, agent_access: result.agent_access, grants: result.grants.map((g) => ({ node_id: g.node_id, alias: g.alias, can_message: g.can_message })), group_grants: result.group_grants.map((g) => ({ group_id: g.group_id, can_message: g.can_message })) }).slice(0, 4000),
3084
+ JSON.stringify({ user_id: targetUid, agent_access: result.agent_access, grants: result.grants.map((g) => ({ node_id: g.node_id, alias: g.alias, can_message: g.can_message })), group_grants: result.group_grants.map((g) => ({ group_id: g.group_id, can_message: g.can_message })), department_grants: result.department_grants.map((g) => ({ department_id: g.department_id, can_message: g.can_message })) }).slice(0, 4000),
3078
3085
  undefined, netId);
3079
3086
  // 已连着的观察流 / 用户流按旧权限鉴权过,断开让它按新权限重连。
3080
3087
  closeUserStreamsInNetwork(netId, targetUid);
package/src/tools.ts CHANGED
@@ -3122,8 +3122,16 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
3122
3122
  durable_terminal_cursor: z.boolean().optional().describe("Read terminal outbound journal in monotonic order"),
3123
3123
  after_terminal_seq: z.number().int().min(0).optional().describe("Exclusive terminal journal watermark"),
3124
3124
  limit: z.number().min(1).max(100).optional().default(20),
3125
+ // #3119 —— 轮询增量。生产实测(2026-11-05 近 6h)list_tasks 占全部工具调用 35.7%、
3126
+ // 是最大的一格:每次轮询都拉全量再自己筛。给它一个「只要这之后创建的」,
3127
+ // 空窗口就回极短体,比任何提示词都省(提示词只能劝,改不了接口成本)。
3128
+ created_since: z.string().max(64).optional()
3129
+ .describe("Only tasks created after this timestamp (ISO 8601 or 'YYYY-MM-DD HH:MM:SS'). Use the previous response's server_time as the next value."),
3130
+ // #3119 —— stats 是全表 GROUP BY:轮询时它比任务列表本身还贵。
3131
+ omit_stats: z.boolean().optional().default(false)
3132
+ .describe("Skip the per-status counts (they scan every task in scope). Pollers should set true."),
3125
3133
  },
3126
- async ({ alias, status, from_name, from_node_id, network_id: netId, before_created_at, before_task_id, durable_cursor, durable_terminal_cursor, after_terminal_seq, limit }) => {
3134
+ async ({ alias, status, from_name, from_node_id, network_id: netId, before_created_at, before_task_id, durable_cursor, durable_terminal_cursor, after_terminal_seq, limit, created_since, omit_stats }) => {
3127
3135
  const readScope = resolveReadScope(netId);
3128
3136
  if (readScope.denied) return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: readScope.denied }) }] };
3129
3137
  if (durable_cursor) {
@@ -3180,6 +3188,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
3180
3188
  if (status) { sql += ` AND status = ?${params.length + 1}`; params.push(status); }
3181
3189
  if (from_name) { sql += ` AND from_name = ?${params.length + 1}`; params.push(from_name); }
3182
3190
  if (from_node_id) { sql += ` AND from_node_id = ?${params.length + 1}`; params.push(from_node_id); }
3191
+ if (created_since) { sql += ` AND created_at > ?${params.length + 1}`; params.push(created_since); }
3183
3192
  if (before_created_at && before_task_id) {
3184
3193
  sql += ` AND (created_at < ?${params.length + 1} OR (created_at = ?${params.length + 1} AND task_id < ?${params.length + 2}))`;
3185
3194
  params.push(before_created_at, before_task_id);
@@ -3188,7 +3197,22 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
3188
3197
  params.push(limit);
3189
3198
  const tasks = db.all(sql, ...params);
3190
3199
 
3191
- // Stats
3200
+ // Stats(#3119:轮询时默认仍然返回,调用方可用 omit_stats 显式关掉)
3201
+ if (omit_stats) {
3202
+ return { content: [{ type: "text" as const, text: JSON.stringify({
3203
+ ok: true,
3204
+ ...(durable_cursor ? { capability: "list_tasks.immutable-node-cursor.v1" } : {}),
3205
+ tasks,
3206
+ count: tasks.length,
3207
+ next_cursor: tasks.length === limit ? {
3208
+ before_created_at: tasks[tasks.length - 1]?.created_at,
3209
+ before_task_id: tasks[tasks.length - 1]?.task_id,
3210
+ } : null,
3211
+ // 客户端把这个值原样当下一轮的 created_since,避免两边时钟不一致。
3212
+ server_time: new Date().toISOString(),
3213
+ stats_omitted: true,
3214
+ }) }] };
3215
+ }
3192
3216
  const statsParams: any[] = [];
3193
3217
  let statsSql = "SELECT status, COUNT(*) as count FROM tasks WHERE 1=1";
3194
3218
  statsSql = addAgentTimelineScope(statsSql, statsParams, readScope, { from: "from_name", to: "to_name", fromNodeId: "from_node_id", toNodeId: "to_node_id" });
@@ -3207,6 +3231,8 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
3207
3231
  before_created_at: tasks[tasks.length - 1]?.created_at,
3208
3232
  before_task_id: tasks[tasks.length - 1]?.task_id,
3209
3233
  } : null,
3234
+ // #3119 —— 轮询水位由服务端给,客户端别用本地时钟(两边差几秒就会漏活或重复)。
3235
+ server_time: new Date().toISOString(),
3210
3236
  stats,
3211
3237
  }),
3212
3238
  }],