@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
@@ -0,0 +1,145 @@
1
+ import { afterAll, beforeAll, beforeEach, describe, expect, test } from "bun:test";
2
+ import "./require-explicit-test-db.js";
3
+ import { db } from "./db.js";
4
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
5
+ import { registerTools } from "./tools.js";
6
+ import { finalizeCreateOnFirstRegister } from "./create-node.js";
7
+
8
+ // 2026-11-14 —— 新建节点时选部门(admin:「创建人可能兼多个部门」→ 不猜,让创建人选)。
9
+ // ① create_node 带 department_id:部门不存在 → department_not_found,不建(不留请求行、不铸令牌)
10
+ // ② 请求行存下部门;节点首次注册(finalize)时写进 nodes.department_id
11
+ // ③ 只填空:节点已经有部门就不覆盖;部门在这期间被删了就跳过
12
+ // ④ 不带 department_id = 老行为(节点没有部门)
13
+ const NET = "net_create_dept";
14
+ const USER_ID = "u_create_dept_admin";
15
+ const DAEMON_ID = "node_create_dept_daemon";
16
+ const DAEMON_ALIAS = "create-dept-daemon";
17
+ const DAEMON_TOK = "tok_create_dept_daemon";
18
+ const ROOT = "/home/user";
19
+
20
+ interface ToolHandler { (args: any, extra?: any): Promise<{ content: Array<{ type: "text"; text: string }> }>; }
21
+ interface Reply { ok?: boolean; error?: string; request_id?: string; node_spec?: any; [k: string]: unknown; }
22
+
23
+ function cleanup() {
24
+ for (const t of ["node_create_requests", "audit_log", "nodes", "sessions", "api_tokens", "network_members", "network_departments"]) {
25
+ try { db.run(`DELETE FROM ${t} WHERE network_id = ?1`, [NET]); } catch {}
26
+ }
27
+ try { db.run("DELETE FROM networks WHERE network_id = ?1", [NET]); } catch {}
28
+ try { db.run("DELETE FROM users WHERE user_id = ?1", [USER_ID]); } catch {}
29
+ }
30
+ beforeEach(cleanup);
31
+ afterAll(cleanup);
32
+
33
+ function seed(caps: Record<string, unknown>) {
34
+ db.run(`INSERT INTO users (user_id, username, password_hash, role, created_at) VALUES (?1, ?1, 'x', 'user', datetime('now'))`, [USER_ID]);
35
+ db.run(`INSERT OR REPLACE INTO networks (network_id, network_name, owner_id, created_at) VALUES (?1, ?1, ?2, datetime('now'))`, [NET, USER_ID]);
36
+ db.run(`INSERT INTO network_members (user_id, network_id, role, joined_at) VALUES (?1, ?2, 'admin', datetime('now'))`, [USER_ID, NET]);
37
+ db.run(
38
+ `INSERT INTO nodes (node_id, node_name, alias, network_id, config_snapshot, hostname, created_at, updated_at, lifecycle_state)
39
+ VALUES (?1, ?2, ?2, ?3, ?4, 'host-x', datetime('now'), datetime('now'), 'active')`,
40
+ [DAEMON_ID, DAEMON_ALIAS, NET, JSON.stringify({ role: "host_supervisor", daemon_capabilities: { runtimes_supported: ["claude-agent-sdk"], ...caps } })],
41
+ );
42
+ db.run(
43
+ `INSERT INTO api_tokens (token_id, user_id, network_id, scope, name, token_hash, expires_at, revoked_at)
44
+ VALUES (?1, ?2, ?3, 'network', ?4, ?5, NULL, NULL)`,
45
+ [DAEMON_TOK, USER_ID, NET, `node:${DAEMON_ALIAS}`, `hash_${DAEMON_TOK}`],
46
+ );
47
+ }
48
+
49
+ function tools(callerTokenId: string | null = null): Record<string, ToolHandler> {
50
+ const server = new McpServer({ name: "test", version: "0" }) as any;
51
+ const out: Record<string, ToolHandler> = {};
52
+ const origTool = server.tool.bind(server);
53
+ server.tool = (name: string, d: string, schema: any, handler: ToolHandler) => { out[name] = handler; return origTool(name, d, schema, handler); };
54
+ const origRegisterTool = server.registerTool?.bind(server);
55
+ if (origRegisterTool) {
56
+ server.registerTool = (name: string, cfg: any, handler: ToolHandler) => { out[name] = handler; return origRegisterTool(name, cfg, handler); };
57
+ }
58
+ registerTools(server, undefined, NET, USER_ID, null, true, callerTokenId);
59
+ return out;
60
+ }
61
+
62
+ async function call(h: ToolHandler, args: any): Promise<Reply> {
63
+ return JSON.parse((await h(args)).content[0].text) as Reply;
64
+ }
65
+
66
+ const baseSpec = { name: "dept-child", runtime: "claude-agent-sdk", model: "claude-sonnet-4-5", flags: {} };
67
+
68
+ function rowCount(): number {
69
+ return db.get<{ n: number }>("SELECT COUNT(*) AS n FROM node_create_requests WHERE daemon_node_id = ?1", DAEMON_ID)?.n ?? -1;
70
+ }
71
+
72
+ const DEPT = "dept_create_a";
73
+ function seedDept(id = DEPT) {
74
+ db.run(`INSERT INTO network_departments (network_id, department_id, name, parent_id, leader_user_id, sort, created_by, created_at, updated_at)
75
+ VALUES (?1, ?2, ?2, NULL, NULL, 0, ?3, datetime('now'), datetime('now'))`, [NET, id, USER_ID]);
76
+ }
77
+ function registerChild(alias: string, nodeId: string, dept: string | null = null) {
78
+ db.run(`INSERT INTO nodes (node_id, node_name, alias, network_id, created_at, updated_at, lifecycle_state, department_id)
79
+ VALUES (?1, ?2, ?2, ?3, datetime('now'), datetime('now'), 'active', ?4)`, [nodeId, alias, NET, dept]);
80
+ return finalizeCreateOnFirstRegister({ node_id: nodeId, alias, network_id: NET });
81
+ }
82
+ const nodeDept = (id: string) => db.get<{ d: string | null }>("SELECT department_id AS d FROM nodes WHERE node_id = ?1", id)?.d ?? null;
83
+
84
+ describe("create_node department_id", () => {
85
+ beforeAll(() => {});
86
+ test("🔴 unknown department → department_not_found, nothing queued, no token minted", async () => {
87
+ seed({});
88
+ const tokensBefore = db.get<{ n: number }>("SELECT COUNT(*) AS n FROM api_tokens WHERE network_id = ?1", NET)!.n;
89
+ const r = await call(tools().create_node, { daemon_node_id: DAEMON_ID, node_spec: baseSpec, department_id: "dept_missing" });
90
+ expect(r.ok).toBe(false);
91
+ expect(r.error).toBe("department_not_found");
92
+ expect(rowCount()).toBe(0);
93
+ expect(db.get<{ n: number }>("SELECT COUNT(*) AS n FROM api_tokens WHERE network_id = ?1", NET)!.n).toBe(tokensBefore);
94
+ });
95
+
96
+ test("🔴 chosen department is stored and lands on the node at first register", async () => {
97
+ seed({}); seedDept();
98
+ const r = await call(tools().create_node, { daemon_node_id: DAEMON_ID, node_spec: baseSpec, department_id: DEPT });
99
+ expect(r.ok).toBe(true);
100
+ expect(r.department_id).toBe(DEPT);
101
+ expect(db.get<{ d: string }>("SELECT department_id AS d FROM node_create_requests WHERE request_id = ?1", r.request_id)!.d).toBe(DEPT);
102
+ expect(registerChild("dept-child", "node_dept_child").finalized).toBe(1);
103
+ expect(nodeDept("node_dept_child")).toBe(DEPT);
104
+ });
105
+
106
+ test("no department_id = old behaviour (node stays unassigned, reply has no department_id key)", async () => {
107
+ seed({}); seedDept();
108
+ const r = await call(tools().create_node, { daemon_node_id: DAEMON_ID, node_spec: baseSpec });
109
+ expect(r.ok).toBe(true);
110
+ expect("department_id" in r).toBe(false);
111
+ registerChild("dept-child", "node_dept_child2");
112
+ expect(nodeDept("node_dept_child2")).toBeNull();
113
+ });
114
+
115
+ test("empty string / null are treated as not set", async () => {
116
+ seed({}); seedDept();
117
+ for (const v of ["", " ", null]) {
118
+ const r = await call(tools().create_node, { daemon_node_id: DAEMON_ID, node_spec: { ...baseSpec, name: `dept-child-${String(v).trim() || "x"}${Math.random().toString(36).slice(2, 6)}` }, department_id: v });
119
+ expect(r.ok).toBe(true);
120
+ expect("department_id" in r).toBe(false);
121
+ }
122
+ });
123
+
124
+ test("only fills a blank: a node someone already placed keeps its department", async () => {
125
+ seed({}); seedDept(); seedDept("dept_other");
126
+ await call(tools().create_node, { daemon_node_id: DAEMON_ID, node_spec: baseSpec, department_id: DEPT });
127
+ registerChild("dept-child", "node_dept_child3", "dept_other");
128
+ expect(nodeDept("node_dept_child3")).toBe("dept_other");
129
+ });
130
+
131
+ test("department deleted before the node came online → skipped, no dangling id", async () => {
132
+ seed({}); seedDept();
133
+ await call(tools().create_node, { daemon_node_id: DAEMON_ID, node_spec: baseSpec, department_id: DEPT });
134
+ db.run("DELETE FROM network_departments WHERE network_id = ?1 AND department_id = ?2", [NET, DEPT]);
135
+ registerChild("dept-child", "node_dept_child4");
136
+ expect(nodeDept("node_dept_child4")).toBeNull();
137
+ });
138
+
139
+ test("audit detail records the chosen department", async () => {
140
+ seed({}); seedDept();
141
+ const r = await call(tools().create_node, { daemon_node_id: DAEMON_ID, node_spec: baseSpec, department_id: DEPT });
142
+ const a = db.get<{ detail: string }>("SELECT detail FROM audit_log WHERE action = 'create_node_dispatch_attempted' AND target_id = ?1", r.request_id);
143
+ expect(a?.detail ?? "").toContain(DEPT);
144
+ });
145
+ });
@@ -186,6 +186,39 @@ export function stopBackgroundTimersForTest(): void {
186
186
  // in caller's network, mark it succeeded and stamp the real
187
187
  // child_node_id. Mirrors RFC-024 finalizePendingMatchingUpdates.
188
188
 
189
+ /**
190
+ * 2026-11-14 —— create_node 时创建人选的部门,节点首次注册时落到 nodes.department_id。
191
+ * 只填空:节点已经有部门(别人先放好了)就不覆盖;部门在这期间被删了就跳过。Best effort。
192
+ */
193
+ export function applyRequestedDepartment(requestId: string, childNodeId: string, networkId: string): void {
194
+ try {
195
+ const dept = db.get<{ department_id: string | null }>("SELECT department_id FROM node_create_requests WHERE request_id = ?1", requestId)?.department_id;
196
+ if (!dept) return;
197
+ if (!db.get("SELECT 1 AS x FROM network_departments WHERE network_id = ?1 AND department_id = ?2", networkId, dept)) return;
198
+ db.run(`UPDATE nodes SET department_id = ?2, updated_at = datetime('now')
199
+ WHERE node_id = ?1 AND network_id = ?3 AND (department_id IS NULL OR department_id = '')`,
200
+ [childNodeId, dept, networkId]);
201
+ } catch (e: any) {
202
+ console.warn(`[commhub] requested department apply failed: ${e?.message || e}`);
203
+ }
204
+ }
205
+
206
+ /** A clone (fork to a new folder) lands in its source's department, unless
207
+ * someone already placed it. Same rule as the source fork (#3485). Best effort. */
208
+ export function inheritCloneDepartment(requestId: string, childNodeId: string, networkId: string): void {
209
+ try {
210
+ const raw = db.get<{ clone_json: string | null }>("SELECT clone_json FROM node_create_requests WHERE request_id = ?1", requestId)?.clone_json;
211
+ if (!raw) return;
212
+ const sourceId = (JSON.parse(raw) as { source_node_id?: unknown })?.source_node_id;
213
+ if (typeof sourceId !== "string" || !sourceId) return;
214
+ db.run(`UPDATE nodes SET department_id = (SELECT s.department_id FROM nodes s WHERE s.node_id = ?2 AND s.network_id = ?3)
215
+ WHERE node_id = ?1 AND network_id = ?3 AND (department_id IS NULL OR department_id = '')`,
216
+ [childNodeId, sourceId, networkId]);
217
+ } catch (e: any) {
218
+ console.warn(`[commhub] clone department inherit failed: ${e?.message || e}`);
219
+ }
220
+ }
221
+
189
222
  export function finalizeCreateOnFirstRegister(
190
223
  incoming: { node_id: string; alias: string; network_id: string | null },
191
224
  ): { finalized: number; matchedIds: string[] } {
@@ -208,6 +241,8 @@ export function finalizeCreateOnFirstRegister(
208
241
  [incoming.node_id, Date.now(), row.request_id],
209
242
  );
210
243
  matchedIds.push(row.request_id);
244
+ applyRequestedDepartment(row.request_id, incoming.node_id, net);
245
+ inheritCloneDepartment(row.request_id, incoming.node_id, net);
211
246
  console.log(`[commhub] ✓ create-node finalize: request=${row.request_id} child=${incoming.alias} (${incoming.node_id}) daemon=${row.daemon_node_id}`);
212
247
  auditCreateNode({
213
248
  action: "create_node_succeeded",
package/src/db.ts CHANGED
@@ -504,6 +504,9 @@ for (const ddl of [
504
504
  `ALTER TABLE nodes ADD COLUMN team TEXT`,
505
505
  `ALTER TABLE nodes ADD COLUMN tags TEXT`,
506
506
  `ALTER TABLE nodes ADD COLUMN attrs_revision INTEGER NOT NULL DEFAULT 0`,
507
+ // admin 2026-11-15:节点「职责介绍」—— 给其他节点 / 人看的「我负责什么、能干什么」(AGENTS.md 是给自己看的)。
508
+ // 和 display_name / team 一样走 PUT /api/nodes/:id/attrs,受 attrs_revision 乐观锁保护。
509
+ `ALTER TABLE nodes ADD COLUMN description TEXT`,
507
510
  ]) {
508
511
  try {
509
512
  db.exec(ddl);
@@ -870,6 +873,14 @@ try {
870
873
  if (!/duplicate column|already exists/i.test(e?.message || "")) throw e;
871
874
  }
872
875
 
876
+ // 2026-11-14 —— 新建节点时选部门(admin:「创建人可能兼多个部门」→ 不猜,让创建人选)。
877
+ // NULL = 不指定(老行为)。节点首次注册时写进 nodes.department_id(applyRequestedDepartment)。
878
+ try {
879
+ db.exec(`ALTER TABLE node_create_requests ADD COLUMN department_id TEXT`);
880
+ } catch (e: any) {
881
+ if (!/duplicate column|already exists/i.test(e?.message || "")) throw e;
882
+ }
883
+
873
884
  // Hub #938 — clone_node reuses this table (same token mint, sweeper, and
874
885
  // register finalize) but must not be replayed as a blank create_node.
875
886
  // NULL/empty = ordinary create. Non-empty JSON = clone directives.
@@ -12,6 +12,9 @@
12
12
  // can_edit=1 = 可改)。旧代码不读它,回滚安全。递归在 JS 里算(部门 ≤ 500),不依赖 WITH RECURSIVE 的方言差异。
13
13
 
14
14
  import { db } from "./db.js";
15
+ // 🔴 这一行是加载顺序保证:`network_members.department_id` 的迁移在 departments.ts:19,
16
+ // 而本文件直接 SELECT 它。少了这行,新库(测试 / 新部署)会缺列(2026-11-11 写 board 测试时撞到)。
17
+ import "./departments.js";
15
18
 
16
19
  db.exec(`
17
20
  CREATE TABLE IF NOT EXISTS network_department_project_grants (
@@ -69,7 +69,7 @@ describe("#3271 从未取走过的过期计数", () => {
69
69
  });
70
70
 
71
71
  // ---- 派单侧硬闸(#3271)----
72
- import { neverConsumeGate, NEVER_CONSUME_LIMIT, NEVER_CONSUME_STALE_MS } from "./expiry-counters.js";
72
+ import { neverConsumeGate, NEVER_CONSUME_LIMIT, NEVER_CONSUME_STALE_MS, parseHubTime } from "./expiry-counters.js";
73
73
 
74
74
  describe("#3271 派单侧硬闸:从未取走过的目标", () => {
75
75
  const NOW = Date.parse("2026-10-31T10:00:00.000Z");
@@ -185,3 +185,52 @@ describe("#3271 硬闸的时效:只数不衰减会把恢复了的节点永久
185
185
  expect(c.by_node["ghost"]).toBe(1);
186
186
  });
187
187
  });
188
+
189
+ describe("2026-11-13 内存计数也以「最后一次回复」为界(恢复了的节点不该等 Hub 重启)", () => {
190
+ const NOW = Date.parse("2026-11-13T12:00:00.000Z");
191
+ const sqlite = (ms: number) => new Date(ms).toISOString().replace("T", " ").slice(0, 19);
192
+ const mem = (n: number, lastAtMs: number) => ({
193
+ since: "2026-11-13T00:00:00.000Z", total: n, by_node: { ghost: n }, last_at: { ghost: new Date(lastAtMs).toISOString() },
194
+ });
195
+
196
+ test("🔴 内存 5 次过期(20 分钟前),之后节点回复过(5 分钟前)⇒ 放行", () => {
197
+ const r = neverConsumeGate({
198
+ alias: "ghost", counters: mem(5, NOW - 20 * 60_000), force: false, forceAllowed: true, now: NOW,
199
+ persistent: { expiries: 0, last_at: null, last_reply_at: sqlite(NOW - 5 * 60_000) },
200
+ });
201
+ expect(r.ok).toBe(true);
202
+ });
203
+
204
+ test("负数用例:回复早于最近一次内存过期 ⇒ 仍然拒(它恢复前那一下不算恢复)", () => {
205
+ const r = neverConsumeGate({
206
+ alias: "ghost", counters: mem(5, NOW - 5 * 60_000), force: false, forceAllowed: true, now: NOW,
207
+ persistent: { expiries: 0, last_at: null, last_reply_at: sqlite(NOW - 20 * 60_000) },
208
+ });
209
+ expect(r.ok).toBe(false);
210
+ });
211
+
212
+ test("负数用例:从来没回复过 ⇒ 内存计数照常生效", () => {
213
+ const r = neverConsumeGate({
214
+ alias: "ghost", counters: mem(5, NOW - 5 * 60_000), force: false, forceAllowed: true, now: NOW,
215
+ persistent: { expiries: 0, last_at: null, last_reply_at: null },
216
+ });
217
+ expect(r.ok).toBe(false);
218
+ });
219
+
220
+ test("回复之后 DB 里又攒了 ≥3 条过期 ⇒ 仍然拒(DB 证据自带边界,不受这条修正影响)", () => {
221
+ const r = neverConsumeGate({
222
+ alias: "ghost", counters: mem(5, NOW - 20 * 60_000), force: false, forceAllowed: true, now: NOW,
223
+ persistent: { expiries: 3, last_at: sqlite(NOW - 60_000), last_reply_at: sqlite(NOW - 5 * 60_000) },
224
+ });
225
+ expect(r.ok).toBe(false);
226
+ });
227
+
228
+ test("parseHubTime:SQLite 时间按 UTC 解析,不随宿主时区漂 8 小时", () => {
229
+ expect(parseHubTime("2026-11-13 12:00:00")).toBe(NOW);
230
+ expect(parseHubTime("2026-11-13T12:00:00")).toBe(NOW);
231
+ expect(parseHubTime("2026-11-13T12:00:00.000Z")).toBe(NOW);
232
+ expect(parseHubTime("2026-11-13T20:00:00+08:00")).toBe(NOW);
233
+ expect(parseHubTime(null)).toBeNull();
234
+ expect(parseHubTime("garbage")).toBeNull();
235
+ });
236
+ });
@@ -182,7 +182,15 @@ export function neverConsumeGate(input: {
182
182
  persistent?: PersistentExpiryEvidence;
183
183
  }): NeverConsumeGate {
184
184
  const limit = input.limit ?? NEVER_CONSUME_LIMIT;
185
- const fromMemory = input.counters.by_node[input.alias] ?? 0;
185
+ // 2026-11-13 —— **内存计数也要以「最后一次回复」为界**(与 DB 证据同一条判据)。
186
+ // 现场:TMA客户端欧 卡住期间攒了 ≥3 次内存过期,之后它恢复并正常回复了,DB 证据随即归零,
187
+ // 但内存桶只有 count + lastAt,没有回复边界 ⇒ 闸继续拒发直到 2 小时 TTL 或 Hub 重启。
188
+ // 有人为此重启了 Hub。回复本身就是「它活着」的证据:最后一次回复晚于内存里最近一次过期
189
+ // ⇒ 那些内存计数全部发生在恢复之前,不再算数。
190
+ const memLastAt = parseHubTime(input.counters.last_at?.[input.alias]);
191
+ const lastReplyAt = parseHubTime(input.persistent?.last_reply_at ?? undefined);
192
+ const memorySupersededByReply = memLastAt !== null && lastReplyAt !== null && lastReplyAt >= memLastAt;
193
+ const fromMemory = memorySupersededByReply ? 0 : (input.counters.by_node[input.alias] ?? 0);
186
194
  const fromDb = input.persistent?.expiries ?? 0;
187
195
  const expiries = Math.max(fromMemory, fromDb);
188
196
  if (expiries < limit) return { ok: true };
@@ -199,19 +207,22 @@ export function neverConsumeGate(input: {
199
207
  message:
200
208
  `this target has ${fromDb} expired task(s) with no reply since its last reply`
201
209
  + `${input.persistent?.last_reply_at ? ` (${input.persistent.last_reply_at})` : " (it has never replied)"}; `
202
- + `nothing will queue correctly here until it replies again — pass force:true (user tokens) if you know it recovered`,
210
+ + `nothing will queue correctly here until it replies again — pass force:true (user tokens) if you know it recovered, `
211
+ + `or as a user token cancel the expired rows (cancel_task accepts expired for user tokens) to clear this gate`,
203
212
  };
204
213
  }
205
214
  // 2026-10-31 —— **只数不衰减会把恢复了的节点永久拉黑**。
206
215
  // 实测的教训来自另一台机(TM中转运维):连「抑制了多少」这个数本身都在被环缓冲淘汰,
207
216
  // 所以任何「累计」都只在它的窗口内可引用;这里把窗口写进判据:最近一次过期超过 TTL ⇒ 放行。
208
- const lastAt = [input.counters.last_at?.[input.alias], input.persistent?.last_at ?? undefined]
209
- .filter((x): x is string => typeof x === "string")
210
- .sort()
211
- .pop();
212
- if (lastAt) {
213
- const age = (input.now ?? Date.now()) - Date.parse(lastAt);
214
- if (Number.isFinite(age) && age > (input.staleAfterMs ?? NEVER_CONSUME_STALE_MS)) return { ok: true };
217
+ // 两个来源的时间格式不同(内存是 ISO,tasks 表是 SQLite 的 "YYYY-MM-DD HH:MM:SS" UTC),
218
+ // 原来按字符串排序再 Date.parse —— 后者会把 SQLite 时间当成**本地时间**解析(Hub 机是 UTC+8)。
219
+ const lastAtMs = [input.counters.last_at?.[input.alias], input.persistent?.last_at ?? undefined]
220
+ .map(parseHubTime)
221
+ .filter((x): x is number => x !== null)
222
+ .reduce<number | null>((a, b) => (a === null || b > a ? b : a), null);
223
+ if (lastAtMs !== null) {
224
+ const age = (input.now ?? Date.now()) - lastAtMs;
225
+ if (age > (input.staleAfterMs ?? NEVER_CONSUME_STALE_MS)) return { ok: true };
215
226
  }
216
227
  if (input.force && input.forceAllowed) return { ok: true };
217
228
  return {
@@ -225,3 +236,14 @@ export function neverConsumeGate(input: {
225
236
  + `nothing will queue correctly here until it consumes again — pass force:true (user tokens) if you know it recovered`,
226
237
  };
227
238
  }
239
+
240
+ /**
241
+ * 解析 Hub 里出现的两种时间:ISO(带 Z / 偏移)和 SQLite `datetime('now')` 的
242
+ * "YYYY-MM-DD HH:MM:SS"(UTC、无时区标记)。后者必须按 UTC 解析,不能交给 Date.parse 当本地时间。
243
+ */
244
+ export function parseHubTime(v: string | null | undefined): number | null {
245
+ if (typeof v !== "string" || !v) return null;
246
+ const sqlite = /^(\d{4}-\d{2}-\d{2})[ T](\d{2}:\d{2}:\d{2}(?:\.\d+)?)$/.exec(v);
247
+ const ms = Date.parse(sqlite ? `${sqlite[1]}T${sqlite[2]}Z` : v);
248
+ return Number.isFinite(ms) ? ms : null;
249
+ }
@@ -448,3 +448,39 @@ describe("legacy global-token mode pinned", () => {
448
448
  expect(inboxRow("x517 g5 legacy")?.network_id).toBeNull();
449
449
  });
450
450
  });
451
+
452
+ // ─────────────────────────────────────────────────────────────────────
453
+ // Group 9 — #4307: `expired` 行的清理权限
454
+ // target_never_consumes 的判据是「最后一次回复之后仍 status='expired' 且 result 为空」。
455
+ // 节点令牌不得改写终态(那是别人的历史);但**用户令牌必须能清**,否则那个节点
456
+ // 永远收不到新消息(实测 4 个节点各 14–46 条,只能人工改库)。
457
+ // ─────────────────────────────────────────────────────────────────────
458
+ describe("#4307 cancel_task 对 expired:用户令牌可清、节点令牌不可", () => {
459
+ test("用户令牌:可以取消 expired,且 result 被写上(从而不再被 409 计数)", async () => {
460
+ const { tools } = buildHandlers({ userId: U_SINGLE });
461
+ const t = makeTask(A1, "expired", "x517 g9 expired by user");
462
+ const r = await call(tools["cancel_task"], { task_id: t, reason: "clear backlog" });
463
+ expect(r.ok).toBe(true);
464
+ expect(r.cancelled).toBe(true);
465
+ expect(taskById(t)?.status).toBe("cancelled");
466
+ const row = db.get<{ result: string | null }>("SELECT result FROM tasks WHERE task_id = ?1", t);
467
+ expect(row?.result).toBe("clear backlog");
468
+ });
469
+
470
+ test("节点令牌:expired 仍不可取消(不重写终态历史)", async () => {
471
+ const { tools } = buildHandlers({ netId: NET_A, alias: A1, isNetwork: true });
472
+ const t = makeTask(A1, "expired", "x517 g9 expired by node");
473
+ const r = await call(tools["cancel_task"], { task_id: t });
474
+ expect(r.ok).toBe(false);
475
+ expect(r.cancelled).toBe(false);
476
+ expect(taskById(t)?.status).toBe("expired");
477
+ });
478
+
479
+ test("节点令牌:非终态仍可取消(既有行为不变)", async () => {
480
+ const { tools } = buildHandlers({ netId: NET_A, alias: A1, isNetwork: true });
481
+ const t = makeTask(A1, "delivered", "x517 g9 delivered by node");
482
+ const r = await call(tools["cancel_task"], { task_id: t });
483
+ expect(r.cancelled).toBe(true);
484
+ expect(taskById(t)?.status).toBe("cancelled");
485
+ });
486
+ });
@@ -86,3 +86,37 @@ export function parseStoredTags(stored: unknown): string[] {
86
86
  return [];
87
87
  }
88
88
  }
89
+
90
+ /**
91
+ * 节点「职责介绍」(admin 2026-11-15「每个节点的职责需要让其他节点也能看到;desc 里放介绍而不是 AGENTS.md,
92
+ * AGENTS.md 是给自己看的,需要设计个给其他节点看的自己的职责、能干什么」)。
93
+ *
94
+ * 和 display_name / team 同一种姿态(类型错 → 400,不强转),但它是一段多行文字:
95
+ * - 保留换行和制表(写「能干什么 / 不干什么 / 怎么找我」要分行);其余控制字符换成空格;
96
+ * - 每行去掉行尾空白,连续空行最多留一行;
97
+ * - 上限 MAX_DESCRIPTION_LEN 字符(按 Unicode 码点数),超了拒绝 —— 让人看到,而不是悄悄截掉。
98
+ */
99
+ export const MAX_DESCRIPTION_LEN = 1000;
100
+
101
+ export function validateDescription(raw: unknown): ScalarAttrResult {
102
+ if (raw === undefined || raw === null) return { ok: true, value: null };
103
+ if (typeof raw !== "string") return { ok: false, reason: "description must be a string or null" };
104
+ // eslint-disable-next-line no-control-regex
105
+ const clean = raw.replace(/\r\n?/g, "\n").replace(/[\u0000-\u0008\u000b-\u001f\u007f]+/g, " ")
106
+ .split("\n").map(line => line.replace(/\s+$/u, "")).join("\n")
107
+ .replace(/\n{3,}/g, "\n\n").trim();
108
+ if (clean.length === 0) return { ok: true, value: null };
109
+ if ([...clean].length > MAX_DESCRIPTION_LEN) {
110
+ return { ok: false, reason: `description exceeds ${MAX_DESCRIPTION_LEN} characters` };
111
+ }
112
+ return { ok: true, value: clean };
113
+ }
114
+
115
+ /** 状态列表里只放一行摘要(整段在 get_session_status / GET /api/nodes 里):第一段非空行,最多 n 个字。 */
116
+ export function descriptionSummary(description: string | null | undefined, n = 120): string | null {
117
+ if (!description) return null;
118
+ const first = description.split("\n").map(s => s.trim()).find(Boolean) ?? "";
119
+ if (!first) return null;
120
+ const chars = [...first];
121
+ return chars.length > n ? `${chars.slice(0, n - 1).join("")}…` : first;
122
+ }
@@ -256,3 +256,35 @@ describe("#2293 opencode bits on GET /api/nodes (real HTTP)", () => {
256
256
  expect(row.opencode_catalog ?? null).toBeNull();
257
257
  });
258
258
  });
259
+
260
+ // admin 2026-11-15 —— 节点职责介绍(给别的节点 / 人看的「我负责什么、能干什么」)。
261
+ describe("node description (职责介绍)", () => {
262
+ test("PUT description round-trips through GET /api/nodes, keeps line breaks, bumps attrs_revision", async () => {
263
+ const before = (await listNodes()).find((r) => r.node_id === LEGACY_NODE)!;
264
+ const rev = Number(before.attrs_revision);
265
+ const text = "负责 App 发版:dispatch release、跑 verify。\n\n找我:发版、签名、TestFlight。\n不做:Hub 改动。";
266
+ const w = await putAttrs(LEGACY_ALIAS, { base_attrs_revision: rev, description: ` ${text} ` });
267
+ expect(w.status).toBe(200);
268
+ expect(w.json.description).toBe(text);
269
+ expect(w.json.attrs_revision).toBe(rev + 1);
270
+ const row = (await listNodes()).find((r) => r.node_id === LEGACY_NODE)!;
271
+ expect(row.description).toBe(text);
272
+ // 只改 description 时别的展示字段不动
273
+ expect(row.display_name).toBe(before.display_name ?? null);
274
+ });
275
+
276
+ test("null / blank clears it; wrong type and > 1000 chars are rejected without writing", async () => {
277
+ const rev = Number((await listNodes()).find((r) => r.node_id === LEGACY_NODE)!.attrs_revision);
278
+ const bad = await putAttrs(LEGACY_ALIAS, { base_attrs_revision: rev, description: { x: 1 } });
279
+ expect(bad.status).toBe(400);
280
+ expect(bad.json.error).toBe("invalid_description");
281
+ const long = await putAttrs(LEGACY_ALIAS, { base_attrs_revision: rev, description: "字".repeat(1001) });
282
+ expect(long.status).toBe(400);
283
+ const still = (await listNodes()).find((r) => r.node_id === LEGACY_NODE)!;
284
+ expect(still.attrs_revision).toBe(rev);
285
+ expect(typeof still.description).toBe("string");
286
+ const clear = await putAttrs(LEGACY_ALIAS, { base_attrs_revision: rev, description: " " });
287
+ expect(clear.status).toBe(200);
288
+ expect((await listNodes()).find((r) => r.node_id === LEGACY_NODE)!.description ?? null).toBeNull();
289
+ });
290
+ });
@@ -71,7 +71,8 @@ describe("#3146 上一次配置下发的投影", () => {
71
71
  test("不投影 created_by_token(凭据标识不是界面信息)", () => {
72
72
  const v: any = projectLastConfigUpdate(row() as any);
73
73
  expect(Object.keys(v).sort()).toEqual([
74
- "acked_at", "created_at", "error", "observed_status", "requested_model", "status", "terminal", "update_id",
74
+ "acked_at", "created_at", "error", "observed_status", "requested_model", "requested_variant",
75
+ "resolved_after_queue", "status", "terminal", "update_id",
75
76
  ]);
76
77
  expect(JSON.stringify(v)).not.toContain("created_by_token");
77
78
  });
@@ -124,3 +125,104 @@ describe("#3146 GET /api/nodes/:id/config 的接线", () => {
124
125
  expect(configGetHandler()).not.toContain("created_by_token");
125
126
  });
126
127
  });
128
+
129
+ // ── #4499 ────────────────────────────────────────────────────────────────────
130
+ // 现象(2026-11-10 生产实测,通信欧):档位被拒(busy)→ 节点排队 → 29s 后真的应用上了
131
+ // → 顶层 modelVariant 已变 → 但 last_update 永远停在 rejected/variant_busy,
132
+ // 客户端于是一直显示「被拒绝」,而它其实已经生效。
133
+ //
134
+ // 判据(三条同时成立才算已生效,缺一条都保持 rejected):
135
+ // ① ack 原因是 variant_busy;② patch 里确实要了档位;③ 节点当前回读的档位 == 请求值。
136
+ // 另加 15 分钟时间窗;`applied` 仍然只代表「写入并回读一致」,不用「已排队」冒充。
137
+ describe("#4499 被拒后排队已生效的下发", () => {
138
+ const busyRow = (over: Record<string, unknown> = {}) => ({
139
+ update_id: "cu_busy",
140
+ status: "rejected",
141
+ patch_json: JSON.stringify({ modelVariant: "high" }),
142
+ error: "variant_busy (in_flight=1, turn_age_ms=31421)",
143
+ created_at: "1793519656437",
144
+ acked_at: "1793519656466",
145
+ ...over,
146
+ });
147
+ const now = 1793519656437 + 29_000; // 29 秒后:正是生产里实际应用的时刻
148
+
149
+ test("回读档位 == 请求值 ⇒ 投影成 applied,但保留原始 rejected 与标记", () => {
150
+ const v = projectLastConfigUpdate(busyRow(), { currentVariant: "high", nowMs: now });
151
+ expect(v.status).toBe("applied");
152
+ expect(v.terminal).toBe(true);
153
+ expect(v.error).toBeNull();
154
+ expect(v.resolved_after_queue).toBe(true);
155
+ expect(v.observed_status).toBe("rejected"); // 原始事实不丢
156
+ expect(v.requested_variant).toBe("high");
157
+ });
158
+
159
+ test("回读档位对不上 ⇒ 保持 rejected(不许猜)", () => {
160
+ const v = projectLastConfigUpdate(busyRow(), { currentVariant: "low", nowMs: now });
161
+ expect(v.status).toBe("rejected");
162
+ expect(v.resolved_after_queue).toBe(false);
163
+ expect(v.error).toContain("variant_busy");
164
+ });
165
+
166
+ test("没有回读上下文 ⇒ 保持 rejected(不可能凭 patch 猜)", () => {
167
+ const v = projectLastConfigUpdate(busyRow(), { nowMs: now });
168
+ expect(v.status).toBe("rejected");
169
+ expect(v.resolved_after_queue).toBe(false);
170
+ });
171
+
172
+ test("超过 15 分钟窗口 ⇒ 不假设已生效", () => {
173
+ const late = 1793519656437 + 16 * 60 * 1000;
174
+ const v = projectLastConfigUpdate(busyRow(), { currentVariant: "high", nowMs: late });
175
+ expect(v.status).toBe("rejected");
176
+ expect(v.resolved_after_queue).toBe(false);
177
+ });
178
+
179
+ test("原因不是 variant_busy ⇒ 不参与这个推断(例如 session 没起)", () => {
180
+ const v = projectLastConfigUpdate(
181
+ busyRow({ error: "OpenCode V2 session is not running; model was not changed" }),
182
+ { currentVariant: "high", nowMs: now },
183
+ );
184
+ expect(v.status).toBe("rejected");
185
+ expect(v.resolved_after_queue).toBe(false);
186
+ });
187
+
188
+ test("patch 里没有 modelVariant ⇒ 与档位无关,不推断", () => {
189
+ const v = projectLastConfigUpdate(busyRow({ patch_json: JSON.stringify({ model: "a/b" }) }), {
190
+ currentVariant: "high",
191
+ nowMs: now,
192
+ });
193
+ expect(v.status).toBe("rejected");
194
+ expect(v.resolved_after_queue).toBe(false);
195
+ expect(v.requested_variant).toBeNull();
196
+ });
197
+
198
+ test("要求清空(modelVariant:null / \"default\")⇒ 与回读的 null 相等才算生效", () => {
199
+ for (const patch of [{ modelVariant: null }, { modelVariant: "default" }]) {
200
+ const applied = projectLastConfigUpdate(busyRow({ patch_json: JSON.stringify(patch) }), {
201
+ currentVariant: null,
202
+ nowMs: now,
203
+ });
204
+ expect(applied.status).toBe("applied");
205
+ const notApplied = projectLastConfigUpdate(busyRow({ patch_json: JSON.stringify(patch) }), {
206
+ currentVariant: "high",
207
+ nowMs: now,
208
+ });
209
+ expect(notApplied.status).toBe("rejected");
210
+ }
211
+ });
212
+
213
+ test("真的 applied 行不受影响:resolved_after_queue=false 且 requested_variant 仍然带出", () => {
214
+ const v = projectLastConfigUpdate(busyRow({ status: "applied", error: null }), {
215
+ currentVariant: "high",
216
+ nowMs: now,
217
+ });
218
+ expect(v.status).toBe("applied");
219
+ expect(v.resolved_after_queue).toBe(false);
220
+ expect(v.requested_variant).toBe("high");
221
+ });
222
+
223
+ test("接线:GET /api/nodes/:id/config 把当前档位传给投影", () => {
224
+ const block = configGetHandler();
225
+ expect(block).toContain("currentVariant:");
226
+ expect(block).toContain("modelVariant");
227
+ });
228
+ });