@sleep2agi/commhub-server 0.9.0-preview.281 → 0.9.0-preview.283

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.
Files changed (43) hide show
  1. package/build-info.json +2 -2
  2. package/package.json +1 -1
  3. package/src/agent-acl-slice3-http.test.ts +3 -2
  4. package/src/api-host-supervisors-source-capabilities.test.ts +107 -0
  5. package/src/auth_login_guard.test.ts +15 -0
  6. package/src/auth_login_guard.ts +20 -1
  7. package/src/board-grants.test.ts +134 -0
  8. package/src/broadcast-attribution.test.ts +93 -0
  9. package/src/build-commit-report-http.test.ts +10 -0
  10. package/src/clone-node-adopted-db.test.ts +78 -0
  11. package/src/clone-node.ts +5 -1
  12. package/src/create-node-department.test.ts +145 -0
  13. package/src/create-node.ts +35 -0
  14. package/src/db.ts +11 -0
  15. package/src/department-heads.ts +3 -0
  16. package/src/expiry-counters.test.ts +50 -1
  17. package/src/expiry-counters.ts +31 -9
  18. package/src/mcp-write-network-resolution.test.ts +36 -0
  19. package/src/node-attrs-validate.ts +34 -0
  20. package/src/node-attrs.test.ts +32 -0
  21. package/src/node-config-last-update.test.ts +103 -1
  22. package/src/node-config-last-update.ts +70 -5
  23. package/src/node-daemon-bindings.ts +9 -0
  24. package/src/node-description-http.test.ts +121 -0
  25. package/src/node-description.test.ts +34 -0
  26. package/src/node-grants-http.test.ts +239 -0
  27. package/src/node-grants.ts +234 -0
  28. package/src/node-inbox-allowlist-http.test.ts +35 -0
  29. package/src/node-permissions.ts +37 -2
  30. package/src/opencode-v2-catalog.test.ts +22 -1
  31. package/src/opencode-v2-catalog.ts +36 -3
  32. package/src/peer-allowlist.test.ts +29 -0
  33. package/src/registration-switch-http.test.ts +60 -0
  34. package/src/reply-bare-infer-4315.test.ts +86 -0
  35. package/src/requirements.ts +29 -4
  36. package/src/schedule-agent.ts +45 -10
  37. package/src/scheduled-tasks-http.test.ts +25 -0
  38. package/src/scheduled-tasks.ts +46 -2
  39. package/src/server.ts +132 -11
  40. package/src/steer-send-message.test.ts +121 -0
  41. package/src/task-access.ts +21 -1
  42. package/src/tool-audience-http.test.ts +5 -0
  43. package/src/tools.ts +147 -42
@@ -41,6 +41,15 @@ export interface LastConfigUpdate {
41
41
  terminal: boolean;
42
42
  /** 这次下发要的模型(来自 patch_json.model);patch 里没有就是 null。 */
43
43
  requested_model: string | null;
44
+ /** 这次下发要的思考档位(来自 patch_json.modelVariant);patch 里没有就是 null。 */
45
+ requested_variant: string | null;
46
+ /**
47
+ * #4499 —— 「排队后被应用」是**推断**出来的,不是节点回报的:
48
+ * 原来 ack 是 rejected/variant_busy,之后节点把排队的档位应用上了,回读档位 == 请求值。
49
+ * 这种情况下 status 投影成 applied(因为它确实生效且回读一致),但这里留 true 便于排查;
50
+ * observed_status 仍然保留原始的 rejected。应用窗口外的、或回读对不上的,一律 false。
51
+ */
52
+ resolved_after_queue: boolean;
44
53
  /** 节点自报的失败原因(rejected/timeout 才有;applied 是 null)。 */
45
54
  error: string | null;
46
55
  /** ISO;TEXT 存的是 ms epoch,转不出来就是 null。 */
@@ -76,17 +85,72 @@ function requestedModel(patchJson: string | null): string | null {
76
85
  }
77
86
  }
78
87
 
88
+ /**
89
+ * patch_json 里的思考档位(`modelVariant`)。
90
+ *
91
+ * 三种「没要档位」必须分开,不能都折叠成 null:
92
+ * · patch 里**没有** modelVariant 这个键 ⇒ undefined(这次下发与档位无关)
93
+ * · patch 里是 `null` / `"default"` ⇒ null(**明确要求清空**回默认)
94
+ * · patch 里是字符串 ⇒ 原样
95
+ */
96
+ function requestedVariant(patchJson: string | null): string | null | undefined {
97
+ if (!patchJson) return undefined;
98
+ try {
99
+ const parsed = JSON.parse(patchJson) as { modelVariant?: unknown };
100
+ if (!Object.prototype.hasOwnProperty.call(parsed, "modelVariant")) return undefined;
101
+ const v = (parsed as { modelVariant?: unknown }).modelVariant;
102
+ if (v === null || v === undefined) return null;
103
+ if (typeof v === "string") return v === "default" ? null : v;
104
+ return undefined;
105
+ } catch {
106
+ return undefined;
107
+ }
108
+ }
109
+
110
+ /** #4499 —— 排队应用的时间窗。超过这个窗口就不再假设「它后来生效了」。 */
111
+ export const QUEUED_VARIANT_WINDOW_MS = 15 * 60 * 1000;
112
+
113
+ /** ack 的原因是「档位忙」吗?只认节点自己写的 `variant_busy`(后面可能带细节)。 */
114
+ function isVariantBusy(error: string | null): boolean {
115
+ return typeof error === "string" && /^variant_busy\b/.test(error);
116
+ }
117
+
79
118
  /** 纯函数:一行 → 对外形状。抽出来是为了能单独钉住「闭集外不折叠」那条。 */
80
- export function projectLastConfigUpdate(row: Row): LastConfigUpdate {
119
+ export function projectLastConfigUpdate(
120
+ row: Row,
121
+ ctx: { currentVariant?: string | null; nowMs?: number } = {},
122
+ ): LastConfigUpdate {
81
123
  const observed = typeof row.status === "string" ? row.status : "";
82
124
  const known = (CONFIG_UPDATE_STATUSES as readonly string[]).includes(observed);
125
+ const reqVariant = requestedVariant(row.patch_json);
126
+
127
+ // #4499:rejected/variant_busy 之后,节点把排队的档位应用上了。
128
+ // 判据三条同时成立才算(缺一条都保持 rejected,绝不把「排队中」冒充 applied):
129
+ // ① ack 原因是 variant_busy;② patch 里确实要了档位;③ 节点当前回读的档位 == 请求值。
130
+ // 另外加一条时间窗:太久以前的下发即使值巧合相等也不算(那是另一件事)。
131
+ let resolvedAfterQueue = false;
132
+ if (known && observed === "rejected" && isVariantBusy(row.error) && reqVariant !== undefined) {
133
+ const nowMs = ctx.nowMs ?? Date.now();
134
+ const createdMs = Number(row.created_at);
135
+ const inWindow =
136
+ Number.isFinite(createdMs) && createdMs > 0 &&
137
+ nowMs >= createdMs && nowMs - createdMs <= QUEUED_VARIANT_WINDOW_MS;
138
+ const current = ctx.currentVariant === undefined ? undefined : ctx.currentVariant === "default" ? null : ctx.currentVariant;
139
+ const requested = reqVariant === null ? null : reqVariant;
140
+ if (inWindow && current !== undefined && current === requested) resolvedAfterQueue = true;
141
+ }
142
+
143
+ const effectiveStatus = resolvedAfterQueue ? "applied" : known ? (observed as ConfigUpdateStatus) : "unknown";
144
+
83
145
  return {
84
146
  update_id: row.update_id,
85
- status: known ? (observed as ConfigUpdateStatus) : "unknown",
147
+ status: effectiveStatus,
86
148
  observed_status: observed,
87
- terminal: known ? TERMINAL[observed as ConfigUpdateStatus] : false,
149
+ terminal: resolvedAfterQueue ? true : known ? TERMINAL[observed as ConfigUpdateStatus] : false,
88
150
  requested_model: requestedModel(row.patch_json),
89
- error: typeof row.error === "string" && row.error ? row.error : null,
151
+ requested_variant: reqVariant === undefined ? null : reqVariant,
152
+ resolved_after_queue: resolvedAfterQueue,
153
+ error: resolvedAfterQueue ? null : typeof row.error === "string" && row.error ? row.error : null,
90
154
  created_at: msToIso(row.created_at),
91
155
  acked_at: msToIso(row.acked_at),
92
156
  };
@@ -101,7 +165,8 @@ export const LAST_CONFIG_UPDATE_SQL =
101
165
  export function readLastConfigUpdate(
102
166
  get: (sql: string, ...params: any[]) => Row | null,
103
167
  nodeId: string,
168
+ ctx: { currentVariant?: string | null; nowMs?: number } = {},
104
169
  ): LastConfigUpdate | null {
105
170
  const row = get(LAST_CONFIG_UPDATE_SQL, nodeId);
106
- return row ? projectLastConfigUpdate(row) : null;
171
+ return row ? projectLastConfigUpdate(row, ctx) : null;
107
172
  }
@@ -22,6 +22,15 @@ export function createdDaemon(nodeId: string): string | null {
22
22
  export function activeBinding(nodeId: string): Binding | null {
23
23
  return db.get<Binding>("SELECT * FROM node_daemon_bindings WHERE node_id=?1 AND status='active'", nodeId);
24
24
  }
25
+ /** clone_node source facts for an ADOPTED node (no succeeded create row).
26
+ * Same shape as the create row clone_node reads; flags stay empty (the
27
+ * daemon reads the real config from disk), runtime/model come from the node row. */
28
+ export function adoptedCloneSourceRow(nodeId: string, networkId: string, runtime: string | null, alias: string):
29
+ { daemon_node_id: string; runtime: string; model: string | null; flags_json: string; child_name: string } | undefined {
30
+ const b = db.get<Binding>("SELECT * FROM node_daemon_bindings WHERE node_id=?1 AND network_id=?2 AND status='active'", nodeId, networkId);
31
+ if (!b) return undefined;
32
+ return { daemon_node_id: b.daemon_node_id, runtime: runtime || "", model: null, flags_json: "{}", child_name: alias };
33
+ }
25
34
  export function resolveManagedDaemon(nodeId: string): string | null {
26
35
  return createdDaemon(nodeId) ?? activeBinding(nodeId)?.daemon_node_id ?? null;
27
36
  }
@@ -0,0 +1,121 @@
1
+ // admin 2026-11-15 —— 节点职责介绍要让「其他节点」也看得到。HTTP 集成(真实 Bun.serve,私有端口,临时库)。
2
+ //
3
+ // 钉住:
4
+ // 1. 网络 owner 经 PUT /api/nodes/:id/attrs 写 description(和 display_name 同一把 attrs_revision 锁);
5
+ // 2. 另一个节点用自己的节点令牌调 MCP get_all_status:目标那一行带 description(一行摘要,≤ 120 字);
6
+ // 没写的节点行里没有这个键(不给全网每行加一个 null);
7
+ // 3. MCP get_session_status:profile.description 是整段(含换行),另带 display_name / team / tags。
8
+ // 4. 自助:节点用**自己的**节点令牌能写**自己的** description(谁最清楚自己干什么);写别的节点 → 403(只有人能改别人)。
9
+ //
10
+ // 跑法:cd server && bun test src/node-description-http.test.ts
11
+ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
12
+ import { mkdtempSync, rmSync } from "node:fs";
13
+ import { tmpdir } from "node:os";
14
+ import { join } from "node:path";
15
+
16
+ const DIR = mkdtempSync(join(tmpdir(), "anet-node-desc-"));
17
+ process.env.COMMHUB_DB ||= join(DIR, "hub.db");
18
+ process.env.COMMHUB_UPLOADS_DIR = join(DIR, "uploads");
19
+ process.env.HOST = "127.0.0.1";
20
+ const stamp = Date.now();
21
+
22
+ let db: any;
23
+ let hub: any = null;
24
+ let BASE = "";
25
+ let NET = "";
26
+ let bossToken = "";
27
+ type Node = { alias: string; nodeId: string; token: string };
28
+ const nodes: Record<"reader" | "target" | "blank", Node> = {} as any;
29
+
30
+ async function tool(token: string, name: string, args: Record<string, unknown>) {
31
+ const res = await fetch(`${BASE}/mcp`, {
32
+ method: "POST",
33
+ headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json", Accept: "application/json, text/event-stream", "MCP-Protocol-Version": "2025-03-26" },
34
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } }),
35
+ });
36
+ const raw = await res.text();
37
+ const data = raw.split("\n").filter((x) => x.startsWith("data:"));
38
+ const payload = data.length ? JSON.parse(data.at(-1)!.slice(5).trim()) : JSON.parse(raw);
39
+ return JSON.parse(payload.result.content[0].text);
40
+ }
41
+
42
+ beforeAll(async () => {
43
+ ({ db } = await import("./db.js"));
44
+ const { createNetworkTokenForNode, register } = await import("./auth.js");
45
+ const boss = register(`desc_boss_${stamp}`, "NodeDesc123!x");
46
+ expect(boss.ok).toBe(true);
47
+ bossToken = boss.token!; NET = boss.network_id!;
48
+ for (const key of ["reader", "target", "blank"] as const) {
49
+ const alias = `desc-${key}-${stamp}`;
50
+ const nodeId = `n_desc_${key}_${stamp}`;
51
+ const minted = createNetworkTokenForNode(boss.user!.user_id, NET, alias, nodeId);
52
+ expect(minted.ok).toBe(true);
53
+ nodes[key] = { alias, nodeId, token: minted.token! };
54
+ db.run(`INSERT OR IGNORE INTO nodes (node_id, node_name, alias, runtime, network_id) VALUES (?1, ?2, ?2, 'claude-agent-sdk', ?3)`, [nodeId, alias, NET]);
55
+ }
56
+ const mod: any = await import("./server.js");
57
+ hub = mod.bootServer({ port: 0, hostname: "127.0.0.1" });
58
+ BASE = `http://127.0.0.1:${hub.port}`;
59
+ for (const n of Object.values(nodes)) {
60
+ expect((await tool(n.token, "report_status", { resume_id: `sdk-${n.nodeId}`, alias: n.alias, status: "idle", node_id: n.nodeId, network_id: NET })).ok).toBe(true);
61
+ }
62
+ }, 30_000);
63
+
64
+ afterAll(() => {
65
+ try { hub?.stop?.(true); } catch {}
66
+ try { rmSync(DIR, { recursive: true, force: true }); } catch {}
67
+ });
68
+
69
+ const DESC = `负责 App 发版:派发 release-desktop / ios-build,跑 finish-release 与 verify。${"细节".repeat(80)}\n\n找我:发版、签名、TestFlight。\n不做:Hub 改动。`;
70
+
71
+ describe("node description is visible to other nodes", () => {
72
+ test("owner writes it through PUT /api/nodes/:id/attrs", async () => {
73
+ const res = await fetch(`${BASE}/api/nodes/${encodeURIComponent(nodes.target.nodeId)}/attrs?network_id=${NET}`, {
74
+ method: "PUT",
75
+ headers: { Authorization: `Bearer ${bossToken}`, "Content-Type": "application/json" },
76
+ body: JSON.stringify({ base_attrs_revision: 0, description: DESC, team: "发版" }),
77
+ });
78
+ const body = await res.json() as any;
79
+ expect(res.status).toBe(200);
80
+ expect(body.description).toBe(DESC);
81
+ });
82
+
83
+ test("get_all_status (another node's token): target row carries a one-line summary; unwritten nodes carry no key", async () => {
84
+ const r = await tool(nodes.reader.token, "get_all_status", {});
85
+ expect(r.ok).toBe(true);
86
+ const target = r.sessions.find((s: any) => s.alias === nodes.target.alias);
87
+ const blank = r.sessions.find((s: any) => s.alias === nodes.blank.alias);
88
+ expect(target).toBeDefined();
89
+ expect(typeof target.description).toBe("string");
90
+ expect(target.description.startsWith("负责 App 发版")).toBe(true);
91
+ expect([...target.description].length).toBeLessThanOrEqual(120);
92
+ expect(target.description.endsWith("…")).toBe(true);
93
+ expect(target.description).not.toContain("\n");
94
+ expect(blank).toBeDefined();
95
+ expect("description" in blank).toBe(false);
96
+ });
97
+
98
+ test("self-service: a node writes its OWN description with its node token; writing another node is refused", async () => {
99
+ const put = (token: string, ref: string, rev: number, description: string) => fetch(`${BASE}/api/nodes/${encodeURIComponent(ref)}/attrs?network_id=${NET}`, {
100
+ method: "PUT", headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
101
+ body: JSON.stringify({ base_attrs_revision: rev, description }),
102
+ });
103
+ const own = await put(nodes.reader.token, nodes.reader.nodeId, 0, "负责读别人的名片。");
104
+ expect(own.status).toBe(200);
105
+ expect(((await own.json()) as any).description).toBe("负责读别人的名片。");
106
+ const other = await put(nodes.reader.token, nodes.blank.nodeId, 0, "冒名顶替");
107
+ expect(other.status).toBe(403);
108
+ expect(((await other.json()) as any).error).toBe("description_self_only");
109
+ expect(db.get("SELECT description FROM nodes WHERE node_id = ?1", nodes.blank.nodeId)?.description ?? null).toBeNull();
110
+ });
111
+
112
+ test("get_session_status: profile carries the full text plus team", async () => {
113
+ const r = await tool(nodes.reader.token, "get_session_status", { alias: nodes.target.alias });
114
+ expect(r.ok).toBe(true);
115
+ expect(r.profile.description).toBe(DESC);
116
+ expect(r.profile.team).toBe("发版");
117
+ expect(Array.isArray(r.profile.tags)).toBe(true);
118
+ const blank = await tool(nodes.reader.token, "get_session_status", { alias: nodes.blank.alias });
119
+ expect(blank.profile.description).toBeNull();
120
+ });
121
+ });
@@ -0,0 +1,34 @@
1
+ // admin 2026-11-15 —— 节点职责介绍:边界校验 + 状态列表里的一行摘要。纯函数,不起服务。
2
+ import { describe, expect, test } from "bun:test";
3
+ import { MAX_DESCRIPTION_LEN, descriptionSummary, validateDescription } from "./node-attrs-validate.js";
4
+
5
+ describe("validateDescription", () => {
6
+ test("undefined / null / blank → clear (null)", () => {
7
+ expect(validateDescription(undefined)).toEqual({ ok: true, value: null });
8
+ expect(validateDescription(null)).toEqual({ ok: true, value: null });
9
+ expect(validateDescription(" \n\t ")).toEqual({ ok: true, value: null });
10
+ });
11
+ test("non-string is rejected, never coerced", () => {
12
+ expect(validateDescription(42).ok).toBe(false);
13
+ expect(validateDescription(["a"]).ok).toBe(false);
14
+ });
15
+ test("keeps newlines, normalises CRLF, strips other control chars, trims line ends, folds 3+ blank lines", () => {
16
+ const r = validateDescription("第一行 \r\n第二\u0007行\n\n\n\n第三行");
17
+ expect(r).toEqual({ ok: true, value: "第一行\n第二 行\n\n第三行" });
18
+ });
19
+ test("length cap counts code points, not UTF-16 units", () => {
20
+ expect(validateDescription("😀".repeat(MAX_DESCRIPTION_LEN)).ok).toBe(true);
21
+ expect(validateDescription("😀".repeat(MAX_DESCRIPTION_LEN + 1)).ok).toBe(false);
22
+ });
23
+ });
24
+
25
+ describe("descriptionSummary", () => {
26
+ test("first non-empty line, capped with an ellipsis", () => {
27
+ expect(descriptionSummary("\n\n 负责发版 \n其余")).toBe("负责发版");
28
+ expect(descriptionSummary("字".repeat(200), 10)).toBe(`${"字".repeat(9)}…`);
29
+ });
30
+ test("nothing written → null (the key is omitted from get_all_status rows)", () => {
31
+ expect(descriptionSummary(null)).toBeNull();
32
+ expect(descriptionSummary(" \n ")).toBeNull();
33
+ });
34
+ });
@@ -0,0 +1,239 @@
1
+ // 节点管理授权(node-grants.ts)—— 全部经真实 HTTP 入口(bootServer + REST / /mcp)。
2
+ //
3
+ // 钉住:
4
+ // 1. PUT /api/nodes/:id/grants:网络 owner 可授全网;节点主人(普通成员)不行;部门负责人只能授自己子树里的部门范围,
5
+ // 授 network 403;未知能力 / 计划中的 board 能力 400;GET 读回;/health 带 node_grants。
6
+ // 2. 定时任务:没授权时节点看不到别人的计划;schedules·network·read ⇒ 看得到、改不了(not_schedule_creator);
7
+ // edit ⇒ 能改、能取消,审计一行 schedule_changed_via_node_grant;department 范围只覆盖目标节点在子树里的计划;
8
+ // 只读模式的节点 edit 降为 read;撤销([])当场生效。
9
+ //
10
+ // 跑法:COMMHUB_DB=/tmp/x.db bun test server/src/node-grants-http.test.ts
11
+ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
12
+ import { addNetworkMember, createNetworkTokenForNode, register } from "./auth.js";
13
+ import { db } from "./db.js";
14
+
15
+ const activeDbPath = process.env.COMMHUB_DB ?? (process.env.COMMHUB_TEST_PG_URL ? "postgres" : undefined);
16
+ if (!activeDbPath) throw new Error("node-grants requires COMMHUB_DB (or COMMHUB_TEST_PG_URL) before module import");
17
+
18
+ const stamp = Date.now();
19
+ const PW = "NodeGrants123!";
20
+ let server: any, base = "", net = "";
21
+ const user: Record<string, { id: string; name: string; token: string }> = {};
22
+ const node: Record<string, { id: string; alias: string; token: string }> = {};
23
+ const deptA = `dept_ga_${stamp}`, deptB = `dept_gb_${stamp}`;
24
+
25
+ async function call(token: string, method: string, path: string, body?: unknown) {
26
+ const r = await fetch(`${base}${path}`, {
27
+ method, headers: { Authorization: `Bearer ${token}`, ...(body === undefined ? {} : { "Content-Type": "application/json" }) },
28
+ body: body === undefined ? undefined : JSON.stringify(body),
29
+ });
30
+ const text = await r.text();
31
+ let json: any = null; try { json = JSON.parse(text); } catch {}
32
+ return { status: r.status, body: json };
33
+ }
34
+ async function mcp(token: string, name: string, args: Record<string, unknown>): Promise<any> {
35
+ const r = await fetch(`${base}/mcp`, {
36
+ method: "POST",
37
+ headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json", Accept: "application/json, text/event-stream" },
38
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } }),
39
+ });
40
+ const text = await r.text();
41
+ const data = text.split("\n").find((l) => l.startsWith("data: "));
42
+ const msg = JSON.parse(data ? data.slice(6) : text);
43
+ const inner = msg.result?.content?.[0]?.text;
44
+ try { return JSON.parse(inner); } catch { return { raw: inner ?? msg }; }
45
+ }
46
+ const putGrants = (token: string, nodeId: string, grants: unknown) => call(token, "PUT", `/api/nodes/${nodeId}/grants`, { grants });
47
+ async function scheduleFor(target: string, name: string): Promise<string> {
48
+ const r = await call(user.boss.token, "POST", "/api/scheduled-tasks", {
49
+ network_id: net, name, target_node_id: target, task: `${name} task`, timezone: "UTC", schedule: { type: "interval", every_seconds: 86400 },
50
+ });
51
+ expect(r.status).toBe(201);
52
+ return r.body.schedule.schedule_id;
53
+ }
54
+ const listIds = async (token: string) => ((await mcp(token, "schedule_list", {})).schedules ?? []).map((s: any) => s.schedule_id);
55
+
56
+ let schedA = "", schedB = "";
57
+
58
+ beforeAll(async () => {
59
+ const boss = register(`ng_boss_${stamp}`, PW);
60
+ net = boss.network_id!;
61
+ user.boss = { id: boss.user!.user_id, name: `ng_boss_${stamp}`, token: boss.token! };
62
+ for (const k of ["own", "lead"] as const) {
63
+ const name = `ng_${k}_${stamp}`;
64
+ const u = register(name, PW);
65
+ user[k] = { id: u.user!.user_id, name, token: u.token! };
66
+ expect(addNetworkMember(net, user[k].id, "member", user.boss.id, { agentAccess: "all" }).ok).toBe(true);
67
+ }
68
+ // mgr 是被授权的节点(主人 own);a 在部门 A,b 在部门 B。
69
+ for (const [key, owner] of [["mgr", "own"], ["a", "boss"], ["b", "boss"]] as const) {
70
+ const alias = `ng-${key}-${stamp}`, id = `n_ng_${key}_${stamp}`;
71
+ const t = createNetworkTokenForNode(user[owner].id, net, alias, id);
72
+ expect(t.ok).toBe(true);
73
+ node[key] = { id, alias, token: t.token! };
74
+ db.run("INSERT INTO sessions (resume_id, alias, status, node_id, network_id) VALUES (?1, ?2, 'idle', ?3, ?4)", [`r_${id}`, alias, id, net]);
75
+ }
76
+ db.run("INSERT INTO network_departments (network_id, department_id, name, parent_id, sort, created_by, leader_user_id) VALUES (?1, ?2, 'A', NULL, 0, ?3, ?4)", [net, deptA, user.boss.id, user.lead.id]);
77
+ db.run("INSERT INTO network_departments (network_id, department_id, name, parent_id, sort, created_by) VALUES (?1, ?2, 'B', NULL, 1, ?3)", [net, deptB, user.boss.id]);
78
+ // board 判「卡的负责人所在部门」⇒ 成员要先有部门。
79
+ db.run("UPDATE network_members SET department_id = ?1 WHERE network_id = ?2 AND user_id IN (?3, ?4)", [deptA, net, user.own.id, user.lead.id]);
80
+ db.run("UPDATE network_members SET department_id = ?1 WHERE network_id = ?2 AND user_id = ?3", [deptB, net, user.boss.id]);
81
+ db.run("UPDATE nodes SET department_id = ?1 WHERE node_id = ?2", [deptA, node.a.id]);
82
+ db.run("UPDATE nodes SET department_id = ?1 WHERE node_id = ?2", [deptB, node.b.id]);
83
+ const mod: any = await import("./server.js");
84
+ server = mod.bootServer({ port: 0, hostname: "127.0.0.1" });
85
+ base = `http://127.0.0.1:${server.port}`;
86
+ schedA = await scheduleFor(node.a.id, "for-a");
87
+ schedB = await scheduleFor(node.b.id, "for-b");
88
+ }, 60_000);
89
+ afterAll(() => { server?.stop?.(true); });
90
+
91
+ describe("PUT /api/nodes/:id/grants —— 谁能授", () => {
92
+ test("/health 报 node_grants", async () => {
93
+ const h = await (await fetch(`${base}/health`)).json() as any;
94
+ expect(h.capabilities).toContain("node_grants");
95
+ });
96
+ test("网络 owner 可授全网;GET 读回;[] 清空", async () => {
97
+ const r = await putGrants(user.boss.token, node.mgr.id, [{ capability: "schedules", scope_kind: "network", level: "read" }]);
98
+ expect(r.status).toBe(200);
99
+ expect(r.body.grants).toEqual([expect.objectContaining({ capability: "schedules", scope_kind: "network", scope_id: "", level: "read" })]);
100
+ expect((await call(user.own.token, "GET", `/api/nodes/${node.mgr.id}/grants`)).body.grants.length).toBe(1);
101
+ expect((await putGrants(user.boss.token, node.mgr.id, [])).body.grants).toEqual([]);
102
+ });
103
+ test("节点主人(普通成员)不能给自己的节点授权", async () => {
104
+ const r = await putGrants(user.own.token, node.mgr.id, [{ capability: "schedules", scope_kind: "network", level: "edit" }]);
105
+ expect(r.status).toBe(403);
106
+ });
107
+ test("部门负责人:授自己部门 OK,授全网 / 别的部门 403", async () => {
108
+ expect((await putGrants(user.lead.token, node.mgr.id, [{ capability: "schedules", scope_kind: "department", scope_id: deptA, level: "edit" }])).status).toBe(200);
109
+ expect((await putGrants(user.lead.token, node.mgr.id, [{ capability: "schedules", scope_kind: "network", level: "edit" }])).status).toBe(403);
110
+ expect((await putGrants(user.lead.token, node.mgr.id, [{ capability: "schedules", scope_kind: "department", scope_id: deptB, level: "edit" }])).status).toBe(403);
111
+ await putGrants(user.boss.token, node.mgr.id, []);
112
+ });
113
+ test("未知能力 400;board(第二期已开闸)200 且可读回;不存在的部门 404", async () => {
114
+ expect((await putGrants(user.boss.token, node.mgr.id, [{ capability: "nope", scope_kind: "network" }])).body.error).toBe("invalid_capability");
115
+ // 第二期:board 与 requirements 读写判定同批上线 ⇒ 写入不再被拒。
116
+ expect((await putGrants(user.boss.token, node.mgr.id, [{ capability: "board", scope_kind: "network", level: "read" }])).status).toBe(200);
117
+ const readBack = await call(user.boss.token, "GET", `/api/nodes/${node.mgr.id}/grants?network_id=${net}`);
118
+ expect((readBack.body.grants || []).some((g: any) => g.capability === "board" && g.level === "read")).toBe(true);
119
+ await putGrants(user.boss.token, node.mgr.id, []);
120
+ expect((await putGrants(user.boss.token, node.mgr.id, [{ capability: "schedules", scope_kind: "department", scope_id: "dept_missing" }])).status).toBe(404);
121
+ });
122
+
123
+ test("部门负责人只能授本部门的 board(跨部门 403)", async () => {
124
+ expect((await putGrants(user.lead.token, node.mgr.id, [{ capability: "board", scope_kind: "department", scope_id: deptA, level: "read" }])).status).toBe(200);
125
+ expect((await putGrants(user.lead.token, node.mgr.id, [{ capability: "board", scope_kind: "department", scope_id: deptB, level: "read" }])).status).toBe(403);
126
+ await putGrants(user.boss.token, node.mgr.id, []);
127
+ });
128
+ });
129
+
130
+ describe("定时任务 —— 授权让节点看得到 / 改得了", () => {
131
+ test("没授权:看不到别人的计划", async () => {
132
+ await putGrants(user.boss.token, node.mgr.id, []);
133
+ const ids = await listIds(node.mgr.token);
134
+ expect(ids).not.toContain(schedA);
135
+ expect((await mcp(node.mgr.token, "schedule_get", { schedule_id: schedA })).error).toBe("schedule_not_found");
136
+ });
137
+ test("network·read:看得到、改不了", async () => {
138
+ await putGrants(user.boss.token, node.mgr.id, [{ capability: "schedules", scope_kind: "network", level: "read" }]);
139
+ const ids = await listIds(node.mgr.token);
140
+ expect(ids).toContain(schedA); expect(ids).toContain(schedB);
141
+ expect((await mcp(node.mgr.token, "schedule_update", { schedule_id: schedA, name: "x" })).error).toBe("not_schedule_creator");
142
+ });
143
+ test("department(A)·edit:只覆盖目标在 A 的;能改能取消;审计一行", async () => {
144
+ await putGrants(user.boss.token, node.mgr.id, [{ capability: "schedules", scope_kind: "department", scope_id: deptA, level: "edit" }]);
145
+ const ids = await listIds(node.mgr.token);
146
+ expect(ids).toContain(schedA); expect(ids).not.toContain(schedB);
147
+ const upd = await mcp(node.mgr.token, "schedule_update", { schedule_id: schedA, name: "renamed by grant" });
148
+ expect(upd.ok).toBe(true);
149
+ expect(upd.schedule.name).toBe("renamed by grant");
150
+ expect((await mcp(node.mgr.token, "schedule_update", { schedule_id: schedB, name: "nope" })).error).toBe("schedule_not_found");
151
+ const audit = db.get<{ n: number | string }>("SELECT COUNT(*) AS n FROM audit_log WHERE action = 'schedule_changed_via_node_grant' AND target_id = ?1", schedA);
152
+ expect(Number(audit!.n)).toBeGreaterThanOrEqual(1);
153
+ });
154
+ test("只读模式的节点:edit 降为 read", async () => {
155
+ db.run("UPDATE nodes SET permission_mode = 'readonly' WHERE node_id = ?1", [node.mgr.id]);
156
+ try {
157
+ const r = await mcp(node.mgr.token, "schedule_update", { schedule_id: schedA, name: "should fail" });
158
+ expect(r.ok).toBe(false);
159
+ } finally {
160
+ db.run("UPDATE nodes SET permission_mode = 'normal' WHERE node_id = ?1", [node.mgr.id]);
161
+ }
162
+ });
163
+ test("撤销([])当场生效", async () => {
164
+ await putGrants(user.boss.token, node.mgr.id, []);
165
+ expect(await listIds(node.mgr.token)).not.toContain(schedA);
166
+ });
167
+ });
168
+
169
+ // ── 第二期:任务看板(board)───────────────────────────────────────────────
170
+ // 判「卡的负责人所在部门」,与定时任务按「目标节点所在部门」不是一回事。
171
+ // 卡:A 的负责人在 deptA(部门负责人 lead 本人),B 的负责人在 deptB(网络 owner boss)。
172
+ // 被授权的节点 mgr 的主人是 own(deptA),但它看不到别人的卡 —— 所以下面看到 A 一定是授权带来的。
173
+ describe("任务看板 —— 授权让节点看得到 / 改得了", () => {
174
+ let cardA = "", cardB = "";
175
+ const cardIds = async (token: string) => ((await mcp(token, "requirements_list", { network_id: net })).requirements ?? []).map((r: any) => r.id);
176
+
177
+ beforeAll(async () => {
178
+ // 🔴 必须在 enforce 下测:默认 "log" 时节点根本不做范围收窄(nodeTaskCaller 返回 null),
179
+ // 那样「授权后才看得到」和「撤销后看不到」都测不出来(无论有没有授权都看得见)。
180
+ process.env.COMMHUB_NODE_PERMISSIONS = "enforce";
181
+ const mk = async (name: string, ownerId: string) => {
182
+ const r = await mcp(user.boss.token, "requirements_create", { network_id: net, name, owner: { kind: "user", id: ownerId } });
183
+ const id = r.requirement?.id;
184
+ expect(typeof id).toBe("string");
185
+ return id as string;
186
+ };
187
+ cardA = await mk(`board A ${stamp}`, user.lead.id);
188
+ cardB = await mk(`board B ${stamp}`, user.boss.id);
189
+ });
190
+ afterAll(() => { delete process.env.COMMHUB_NODE_PERMISSIONS; });
191
+
192
+ test("没授权:别人的卡看不到,也改不了", async () => {
193
+ await putGrants(user.boss.token, node.mgr.id, []);
194
+ const ids = await cardIds(node.mgr.token);
195
+ expect(ids).not.toContain(cardA); expect(ids).not.toContain(cardB);
196
+ const upd = await mcp(node.mgr.token, "requirements_update", { network_id: net, id: cardA, description: "nope" });
197
+ expect(upd.ok).not.toBe(true);
198
+ });
199
+
200
+ test("department(A)·read:看得到 A、看不到 B;B 是 not_found;改不了", async () => {
201
+ await putGrants(user.boss.token, node.mgr.id, [{ capability: "board", scope_kind: "department", scope_id: deptA, level: "read" }]);
202
+ const ids = await cardIds(node.mgr.token);
203
+ expect(ids).toContain(cardA); expect(ids).not.toContain(cardB);
204
+ expect((await mcp(node.mgr.token, "requirements_get", { network_id: net, id: cardB })).error).toBe("requirement_not_found");
205
+ expect((await mcp(node.mgr.token, "requirements_update", { network_id: net, id: cardA, description: "read only" })).ok).not.toBe(true);
206
+ });
207
+
208
+ test("department(A)·edit:能改 A,审计 requirement_changed_via_node_grant;B 仍 not_found", async () => {
209
+ await putGrants(user.boss.token, node.mgr.id, [{ capability: "board", scope_kind: "department", scope_id: deptA, level: "edit" }]);
210
+ const upd = await mcp(node.mgr.token, "requirements_update", { network_id: net, id: cardA, description: "changed by grant" });
211
+ expect(upd.ok).toBe(true);
212
+ const audit = db.get<{ n: number | string }>("SELECT COUNT(*) AS n FROM audit_log WHERE action = 'requirement_changed_via_node_grant' AND target_id = ?1", cardA);
213
+ expect(Number(audit!.n)).toBeGreaterThanOrEqual(1);
214
+ expect((await mcp(node.mgr.token, "requirements_update", { network_id: net, id: cardB, description: "nope" })).error).toBe("requirement_not_found");
215
+ });
216
+
217
+ test("network·read:两张卡都能看到(不拼巨大 IN 列表)", async () => {
218
+ await putGrants(user.boss.token, node.mgr.id, [{ capability: "board", scope_kind: "network", level: "read" }]);
219
+ const ids = await cardIds(node.mgr.token);
220
+ expect(ids).toContain(cardA); expect(ids).toContain(cardB);
221
+ });
222
+
223
+ test("只读模式的节点:edit 降为 read,改不动", async () => {
224
+ await putGrants(user.boss.token, node.mgr.id, [{ capability: "board", scope_kind: "department", scope_id: deptA, level: "edit" }]);
225
+ db.run("UPDATE nodes SET permission_mode = 'readonly' WHERE node_id = ?1", [node.mgr.id]);
226
+ try {
227
+ expect((await mcp(node.mgr.token, "requirements_update", { network_id: net, id: cardA, description: "should fail" })).ok).not.toBe(true);
228
+ // 但看还是能看
229
+ expect(await cardIds(node.mgr.token)).toContain(cardA);
230
+ } finally {
231
+ db.run("UPDATE nodes SET permission_mode = 'normal' WHERE node_id = ?1", [node.mgr.id]);
232
+ }
233
+ });
234
+
235
+ test("撤销([])当场生效", async () => {
236
+ await putGrants(user.boss.token, node.mgr.id, []);
237
+ expect(await cardIds(node.mgr.token)).not.toContain(cardA);
238
+ });
239
+ });