@sleep2agi/commhub-server 0.9.0-preview.241 → 0.9.0-preview.243

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sleep2agi/commhub-server",
3
- "version": "0.9.0-preview.241",
3
+ "version": "0.9.0-preview.243",
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",
@@ -434,6 +434,11 @@ describe("update_node_config 响应键集(exact key set)", () => {
434
434
  expect(Array.isArray(plain.messages)).toBe(true);
435
435
 
436
436
  const human = await tool(ntok, "get_inbox", { alias: I.alias, limit: 5, human_first: true });
437
+
438
+ // 2026-10-31 —— **先证两份夹具彼此不同,再各自断言**(外部复核 (c):
439
+ // 「若四份夹具序列化出的字节相同,它只有一种形状 —— 后面的『各自断言』就是四次自拍」)。
440
+ // 这里两态也一样:若 human_first 其实没生效,下面两条键集断言会变成「同一个形状断两次」。
441
+ expect(JSON.stringify(Object.keys(plain).sort())).not.toBe(JSON.stringify(Object.keys(human).sort()));
437
442
  expect(Object.keys(human).sort()).toEqual(["human_inbox", "messages", "ok"]);
438
443
  expect(Object.keys(human.human_inbox).sort()).toEqual(["examined", "mode", "version"]);
439
444
  expect(human.human_inbox.mode).toBe("metadata-keyset");
@@ -100,7 +100,13 @@ for (const [name, arguments_] of endpoints) {
100
100
  test(`daemon identity boundary: ${name}`, async () => {
101
101
  const args = name.includes("adopt_request") ? { ...arguments_, request_id: requestId } : arguments_;
102
102
  for (const token of [mismatched, wrongBound, ownerless, owner.token, member.token]) {
103
- expect(await call(token, name, args)).toMatchObject({ ok: false, error: "caller_not_a_daemon" });
103
+ const denied = await call(token, name, args);
104
+ expect(denied).toMatchObject({ ok: false, error: "caller_not_a_daemon" });
105
+ // 2026-10-31 —— #3275:**错误信封也是契约**。
106
+ // 这八个 ack/get 工具此前只被断言过 error 的**值**,没有一条钉住键集:
107
+ // 谁顺手在某个出口多塞一个字段(例如 hint / request_id),客户端的分支就多一个没人知道的键。
108
+ // ⇒ 在同一个循环里把形状钉住,成本几乎为零。
109
+ expect(Object.keys(denied).sort()).toEqual(["error", "ok"]);
104
110
  }
105
111
  expect(db.get("SELECT status FROM node_daemon_bindings WHERE request_id=?1", requestId).status).toBe("pending");
106
112
  });
@@ -110,24 +116,42 @@ test("legacy owner and exact bound identity remain supported", async () => {
110
116
  expect(db.get("SELECT bound_node_id FROM api_tokens WHERE token_id='owner678_legacy'").bound_node_id).toBeNull();
111
117
  for (const token of [legacy, bound]) {
112
118
  expect((await call(token, "list_my_children")).ok).toBe(true);
113
- expect((await call(token, "list_my_pending_create_requests")).ok).toBe(true);
114
- expect((await call(token, "list_my_pending_lifecycle_requests")).ok).toBe(true);
119
+ // 2026-10-31 —— #3275 批次 2:这两条是 **SSE 重连补偿**的入口(漏了门铃节点会卡死),
120
+ // 客户端按字段名读;键集从未被钉住。改为 `const` 赋值,顺便让严格口径能数到它们。
121
+ const pendCreate = await call(token, "list_my_pending_create_requests");
122
+ expect(pendCreate.ok).toBe(true);
123
+ expect(Object.keys(pendCreate).sort()).toEqual(["clone_count", "clone_requests", "count", "ok", "requests"]);
124
+
125
+ const pendLife = await call(token, "list_my_pending_lifecycle_requests");
126
+ expect(pendLife.ok).toBe(true);
127
+ expect(Object.keys(pendLife).sort()).toEqual(["ok", "start_count", "start_requests", "stop_count", "stop_requests"]);
128
+ // 计数与数组同源:两个 count 必须等于各自数组长度(否则「有 N 条」与「列出来」会分叉)
129
+ expect(pendLife.stop_count).toBe(pendLife.stop_requests.length);
130
+ expect(pendLife.start_count).toBe(pendLife.start_requests.length);
115
131
  expect((await call(token, "get_adopt_request", { request_id: requestId })).ok).toBe(true);
116
132
  }
117
133
  // An explicit binding does not bypass the network or revocation boundaries.
118
134
  expect(await call(crossNetwork, "list_my_children")).toMatchObject({ ok: false, error: "caller_not_a_daemon" });
119
135
  const denied = await fetch(`${base}/mcp`, { method: "POST", headers: { Authorization: `Bearer ${revoked}` } });
120
136
  expect(denied.status).toBe(401);
121
- expect(await call(legacy, "ack_adopt_request", { request_id: requestId, status: "adopted" })).toMatchObject({ ok: true, status: "active" });
137
+ // 2026-10-31 —— #3275:**成功体也要钉键集**(上面那个循环钉的是错误信封)。
138
+ // 这四条是 daemon 侧最常被按字段名读的回执;多一个键不会让谁报错,但会改变解析分支。
139
+ const adopted = await call(legacy, "ack_adopt_request", { request_id: requestId, status: "adopted" });
140
+ expect(adopted).toMatchObject({ ok: true, status: "active" });
141
+ expect(Object.keys(adopted).sort()).toEqual(["ok", "status"]);
122
142
  expect((await call(legacy, "list_my_children")).children).toContainEqual({ child_node_id: child, alias: child, lifecycle_state: "active", managed: "adopted", binding_request_id: requestId });
123
143
  const stop = await call(owner.token, "stop_node", { node_id: child, network_id: owner.network_id });
124
144
  expect(stop.ok).toBe(true);
125
145
  expect((await call(legacy, "get_stop_request", { request_id: stop.request_id })).ok).toBe(true);
126
- expect((await call(legacy, "ack_stop_request", { request_id: stop.request_id, status: "stopped" })).ok).toBe(true);
146
+ const stoppedAck = await call(legacy, "ack_stop_request", { request_id: stop.request_id, status: "stopped" });
147
+ expect(stoppedAck.ok).toBe(true);
148
+ expect(Object.keys(stoppedAck).sort()).toEqual(["ok", "status"]); // #3275:成功体键集
127
149
  const start = await call(owner.token, "start_node", { node_id: child, network_id: owner.network_id });
128
150
  expect(start.ok).toBe(true);
129
151
  expect((await call(legacy, "get_start_request", { request_id: start.request_id })).ok).toBe(true);
130
- expect(await call(legacy, "ack_start_request", { request_id: start.request_id, status: "started", child_pid: 4321 })).toMatchObject({ ok: true, status: "started" });
152
+ const startedAck = await call(legacy, "ack_start_request", { request_id: start.request_id, status: "started", child_pid: 4321 });
153
+ expect(startedAck).toMatchObject({ ok: true, status: "started" });
154
+ expect(Object.keys(startedAck).sort()).toEqual(["ok", "status"]); // #3275:成功体键集
131
155
  });
132
156
 
133
157
  test("ownerless legacy daemon remains supported without rewriting its owner", async () => {
@@ -1338,6 +1338,46 @@ describe("#473 anonymous /health — watchdog contract intact, no topology leak"
1338
1338
  expect(/git|commit|build[-_]?(sha|id)?/.test("x-commhub")).toBe(false);
1339
1339
  });
1340
1340
 
1341
+ // 2026-10-31 —— **计数之间的守恒式**(外部复核:「human + worker + unassigned == 待办行数;
1342
+ // 不等 ⇒ RuntimeError。它防的是将来改坏分桶:漏一类左边小、重复计一类左边大」)。
1343
+ // 本仓这里的两个数是同一个量的两个名字:mcp_inflight(当前)与 mcp_inflight_peak(峰值)。
1344
+ // 守恒式:peak ≥ inflight(任何时刻都成立,与采样时机无关);
1345
+ // 反过来若有人把 peak 写成"本次采样值",两者会相等而看不出——所以还要一条
1346
+ // 「peak 只增不减」:在窗口内取三次,peak 序列必须单调不减。
1347
+ test("mcp_inflight_peak dominates the current value and never decreases", async () => {
1348
+ const samples: Array<{ now: number; peak: number }> = [];
1349
+ for (let i = 0; i < 3; i++) {
1350
+ const d = await (await fetch(`${BASE}/health`)).json() as any;
1351
+ samples.push({ now: Number(d.mcp_inflight), peak: Number(d.mcp_inflight_peak) });
1352
+ await new Promise((r) => setTimeout(r, 120));
1353
+ }
1354
+ for (const s of samples) {
1355
+ expect(Number.isFinite(s.now)).toBe(true);
1356
+ expect(Number.isFinite(s.peak)).toBe(true);
1357
+ expect(s.peak).toBeGreaterThanOrEqual(s.now); // 守恒式
1358
+ expect(s.now).toBeGreaterThanOrEqual(0);
1359
+ }
1360
+ // 单调:峰值不许下降(它不是一个采样值)
1361
+ for (let i = 1; i < samples.length; i++) {
1362
+ expect(samples[i].peak).toBeGreaterThanOrEqual(samples[i - 1].peak);
1363
+ }
1364
+ });
1365
+
1366
+ // 2026-10-31 —— **一致时零证据**(外部复核:「status / db / mineruProxy 三个字段是同一个位,
1367
+ // 一致时零证据」)。本仓的 status 与 status_reasons 由构造保证一致 ⇒
1368
+ // 「status=='ok' ⟺ reasons 为空」是恒真断言,保护不了任何东西。
1369
+ // ⇒ 改成断言**映射本身**:给一个理由就必须 degraded;且映射是纯函数、可被单独喂输入。
1370
+ test("status mapping is a pure function of the reasons list (one reason is enough to degrade)", async () => {
1371
+ const { statusFromReasons } = await import("./server.js");
1372
+ expect(statusFromReasons([])).toBe("ok");
1373
+ expect(statusFromReasons(["db_unreadable"])).toBe("degraded");
1374
+ expect(statusFromReasons(["license_unreadable"])).toBe("degraded");
1375
+ expect(statusFromReasons(["anything_at_all"])).toBe("degraded"); // 不认识的理由也不许吞
1376
+ // 且线上载荷与函数一致(不是两套逻辑)
1377
+ const live = await (await fetch(`${BASE}/health`)).json() as any;
1378
+ expect(live.status).toBe(statusFromReasons(live.status_reasons ?? []));
1379
+ });
1380
+
1341
1381
  test("no dead entries: every allow-listed key is actually served to anonymous callers", async () => {
1342
1382
  const { PUBLIC_HEALTH_KEYS } = await import("./server.js");
1343
1383
  const plain = await (await fetch(`${BASE}/health`)).json() as any;
@@ -375,6 +375,27 @@ describe("GET /api/providers", () => {
375
375
  // ⇒ A、B 两条向量改变的是同一个出口量」)。
376
376
  // 对应到本路由:五个 state 如果**去掉 state 字段**就分不出来,那 state 就是唯一信息源,
377
377
  // 载荷只是标签的复读 —— 秩 = 1。判据:把 state 删掉之后,五个载荷仍两两可区分。
378
+ // 2026-10-31 —— **从属字段在主条件为假时不得有值**(外部复核 (d):
379
+ // 「从属字段在主字段为假时不得有值;不校验就会存下不可能的状态,
380
+ // 后来者无法区分它与历史遗留,只会当成有效读数。」)
381
+ // 本路由的三个从属键:
382
+ // error ⟺ state === "failed"
383
+ // observed_status ⟺ state === "unknown"
384
+ // hint ⟺ state ∈ {never_switched, unknown}(pending/applied 不该有 hint)
385
+ const has = (o: any, k: string) => Object.prototype.hasOwnProperty.call(o, k);
386
+ const cases: Array<[string, any, { error: boolean; observed_status: boolean; hint: boolean }]> = [
387
+ ["never_switched", a.body, { error: false, observed_status: false, hint: true }],
388
+ ["pending", b.body, { error: false, observed_status: false, hint: false }],
389
+ ["applied", c.body, { error: false, observed_status: false, hint: false }],
390
+ ["failed", d.body, { error: true, observed_status: false, hint: false }],
391
+ ["unknown", e.body, { error: false, observed_status: true, hint: true }],
392
+ ];
393
+ for (const [label, body, want] of cases) {
394
+ expect({ label, error: has(body, "error") }).toEqual({ label, error: want.error });
395
+ expect({ label, observed: has(body, "observed_status") }).toEqual({ label, observed: want.observed_status });
396
+ expect({ label, hint: has(body, "hint") }).toEqual({ label, hint: want.hint });
397
+ }
398
+
378
399
  const strip = (b: any) => { const { state: _s, ...rest } = b; return JSON.stringify(rest); };
379
400
  const five = [a, b, c, d, e].map((r) => strip(r.body));
380
401
  expect(new Set(five).size).toBe(5); // 两两不同 ⇒ 秩 ≥ 2,state 不是唯一维度
@@ -60,7 +60,9 @@ afterAll(() => { try { hub?.stop?.(); } catch {} rmSync(DIR, { recursive: true,
60
60
 
61
61
  describe("assignee never contradicts a validated owner/agent_owner reference", () => {
62
62
  test("陈旧自由文本被引用覆盖(agent_owner 优先 > owner > 文本)", async () => {
63
- const { displayAssignee } = await import("./requirements.js").catch(() => ({ displayAssignee: null as any })) as any;
63
+ const { displayAssignee, refDisplayName } = await import("./requirements.js").catch(
64
+ () => ({ displayAssignee: null as any, refDisplayName: null as any })) as any;
65
+ if (typeof refDisplayName !== "function") throw new Error("refDisplayName 未导出");
64
66
  if (typeof displayAssignee !== "function") {
65
67
  // 函数未导出时的退路:直接验证读取路径(下面两条 HTTP 用例已经覆盖),
66
68
  // 这里不静默通过 —— 明确记录「没有读数」的边界。
@@ -71,8 +73,13 @@ describe("assignee never contradicts a validated owner/agent_owner reference", (
71
73
  owner_json: JSON.stringify({ kind: "user", username: "王工" }),
72
74
  agent_owner_json: JSON.stringify({ kind: "node", id: "n_x", alias: "通信欧" }),
73
75
  };
74
- expect(displayAssignee(row)).toBe("通信欧");
75
- expect(displayAssignee({ ...row, agent_owner_json: null })).toBe("王工");
76
+ // 读侧:只回显存下来的自由文本(不从引用推导 —— 无法区分「没设过」与「显式清空」)
77
+ expect(displayAssignee({ assignee: "ANet基建" })).toBe("ANet基建");
78
+ expect(displayAssignee({ assignee: "" })).toBe("");
79
+ // 写侧回填用的名字解析:引用 → 人名(node 用 alias,user 用 username)
80
+ expect(refDisplayName(JSON.stringify({ kind: "node", id: "n_x", alias: "通信欧" }))).toBe("通信欧");
81
+ expect(refDisplayName(JSON.stringify({ kind: "user", username: "王工" }))).toBe("王工");
82
+ expect(refDisplayName("")).toBe("");
76
83
  // 没有引用时保留自由文本(系统外的人,删掉等于丢信息)
77
84
  expect(displayAssignee({ assignee: " 王工 ", owner_json: null, agent_owner_json: null })).toBe("王工");
78
85
  // 全是空 ⇒ 空串,不是 "undefined"/"null"
@@ -113,10 +120,35 @@ describe("assignee never contradicts a validated owner/agent_owner reference", (
113
120
  expect(renamed.body.requirement.name).toBe("改个名字而已");
114
121
  expect(renamed.body.requirement.assignee).toBe("asg-probe"); // 与上面那条同一张卡
115
122
 
116
- // 两者**同时存在**时读侧以引用为准(这是有意的取舍:引用写入时被校验过,自由文本没有)。
117
- // 记录在这里,免得下一个人把它当成 bug 再改回去。
123
+ // 两者**同时存在**时,读侧以**显式自由文本**为准(既有契约:调用方给的 assignee 不被覆盖)。
124
+ // 漂移的修法在写侧:设引用而**没显式给** assignee 时回填 —— 上面那条已经证明了这一点。
118
125
  const both = await send("PATCH", `/api/requirements/${id}?network_id=${NET}`, { assignee: "王工" });
119
126
  expect(both.status).toBe(200);
120
- expect(both.body.requirement.assignee).toBe("asg-probe");
127
+ expect(both.body.requirement.assignee).toBe("王工");
128
+ });
129
+ });
130
+
131
+ describe("#3277 — deleting a node clears the cards that referenced it", () => {
132
+ test("agent_owner 被置空、participants 被摘掉,卡本身保留", async () => {
133
+ const { clearNodeFromRequirements } = await import("./requirements.js");
134
+ const created = await send("POST", `/api/requirements?network_id=${NET}`, {
135
+ name: "引用一个即将被删的节点",
136
+ column: "pool",
137
+ agent_owner: { kind: "node", alias: "asg-probe" },
138
+ participants: [{ kind: "node", alias: "asg-probe" }],
139
+ });
140
+ expect(created.status).toBe(201);
141
+ const id = created.body.requirement.id as string;
142
+
143
+ const res = clearNodeFromRequirements("n_asg_probe");
144
+ expect(res.agentOwnerCleared).toBeGreaterThan(0);
145
+ expect(res.participantsTouched).toBeGreaterThan(0);
146
+
147
+ const after = await send("GET", `/api/requirements/${id}?network_id=${NET}`);
148
+ expect(after.status).toBe(200);
149
+ // 卡还在,但不再指向一个不存在的节点
150
+ expect(after.body.requirement.agent_owner ?? null).toBeNull();
151
+ const parts = after.body.requirement.participants ?? [];
152
+ expect(parts.some((p: any) => p?.kind === "node" && p?.id === "n_asg_probe")).toBe(false);
121
153
  });
122
154
  });
@@ -1263,11 +1263,9 @@ function patchRequirement(ctx: RequirementsRequestContext, row: Row, body: Recor
1263
1263
  // 规则:调用方**没有显式给 assignee** 时,用本次写入后的引用回填;显式给了就以调用方为准
1264
1264
  // (那可能是系统外的人,例如「王工」—— 用引用覆盖它等于丢信息)。
1265
1265
  if (!has("assignee") && (has("owner") || has("agent_owner"))) {
1266
- const fromRef = displayAssignee({
1267
- assignee: "",
1268
- owner_json: people.ownerJson,
1269
- agent_owner_json: people.agentOwnerJson,
1270
- });
1266
+ // 用 refDisplayName(把 {kind,id} 换回人名),**不是** displayAssignee
1267
+ // (后者只回显存下来的自由文本 —— 这里正是要从引用推)。
1268
+ const fromRef = refDisplayName(people.agentOwnerJson) || refDisplayName(people.ownerJson);
1271
1269
  if (fromRef) assignee = fromRef.slice(0, 80);
1272
1270
  }
1273
1271
  // RFC-040:只凭负责人身份改这张卡时,负责人 / 负责 Agent 只能交给本部门的人(或自己)/ 本部门成员的 Agent,
@@ -1483,30 +1481,76 @@ type LightRow = { requirement_id: string; seq?: number | null; network_id: strin
1483
1481
  * agent_owner 必须是本网络 node),而 assignee 是自由文本。两者冲突时,读一侧应以引用为准。
1484
1482
  * 没有引用时保留自由文本 —— 它可能是系统外的人(例如「王工」),删掉就等于丢信息。
1485
1483
  */
1486
- export function displayAssignee(row: { assignee?: string | null; owner_json?: string | null; agent_owner_json?: string | null }): string {
1487
- const parse = (json: string | null | undefined): { kind?: string; id?: string; alias?: string; username?: string } | null => {
1488
- if (!json) return null;
1489
- try { return JSON.parse(json); } catch { return null; }
1490
- };
1491
- // 引用存的是 {kind, id}(名字在写入时已被解析成 id)⇒ 读侧要把 id 换回**给人看的名字**,
1492
- // 否则 assignee 会变成 "n_xxxx",那比停在旧值更糟(至少旧值是句话)。
1493
- const name = (ref: { kind?: string; id?: string; alias?: string; username?: string } | null): string => {
1494
- if (!ref) return "";
1495
- const inline = String(ref.alias || ref.username || "").trim();
1496
- if (inline) return inline;
1497
- if (!ref.id) return "";
1498
- try {
1499
- if (ref.kind === "node") {
1500
- const r = db.get<{ alias: string | null }>("SELECT alias FROM nodes WHERE node_id = ?1", ref.id);
1501
- if (r?.alias) return String(r.alias);
1502
- } else if (ref.kind === "user") {
1503
- const r = db.get<{ username: string | null }>("SELECT username FROM users WHERE user_id = ?1", ref.id);
1504
- if (r?.username) return String(r.username);
1505
- }
1506
- } catch { /* 读不到就退回 id:比空更好,且不会崩 */ }
1507
- return String(ref.id);
1508
- };
1509
- return name(parse(row.agent_owner_json)) || name(parse(row.owner_json)) || String(row.assignee || "").trim();
1484
+ /**
1485
+ * 2026-10-31 —— **删节点时要清掉指向它的卡引用**(#3277,实测 31 条悬空)。
1486
+ *
1487
+ * 实测:三个已删除的 node id 仍被 27 张卡引用,其中两个 id 在 api_tokens 里还有绑定行
1488
+ * ⇒ 悬空不是录入错误,是**删除路径的缺口**;而读侧把它显示成「负责人是 n_xxxx」。
1489
+ *
1490
+ * 处理:
1491
+ * · agent_owner 指向该节点 ⇒ 置空(卡本身不动,它是正确的)
1492
+ * · participants 含该节点 ⇒ 从列表里摘掉
1493
+ * · owner 是**人**,删节点不影响它 ⇒ 不动
1494
+ * 返回 { agentOwnerCleared, participantsTouched },供删除路径写进审计。
1495
+ */
1496
+ export function clearNodeFromRequirements(nodeId: string): { agentOwnerCleared: number; participantsTouched: number } {
1497
+ const needle = `"id":"${nodeId}"`;
1498
+ let agentOwnerCleared = 0;
1499
+ const owners = db.all<{ requirement_id: string }>(
1500
+ "SELECT requirement_id FROM requirements WHERE agent_owner_json LIKE ?1", `%${needle}%`);
1501
+ for (const row of owners) {
1502
+ db.run("UPDATE requirements SET agent_owner_json = NULL, updated_at = ?2 WHERE requirement_id = ?1",
1503
+ [row.requirement_id, new Date().toISOString()]);
1504
+ agentOwnerCleared += 1;
1505
+ }
1506
+ let participantsTouched = 0;
1507
+ const parts = db.all<{ requirement_id: string; participants_json: string | null }>(
1508
+ "SELECT requirement_id, participants_json FROM requirements WHERE participants_json LIKE ?1", `%${needle}%`);
1509
+ for (const row of parts) {
1510
+ let list: Array<{ kind?: string; id?: string }> = [];
1511
+ try { list = JSON.parse(row.participants_json || "[]") as any[]; } catch { continue; }
1512
+ const next = (list || []).filter((ref) => !(ref?.kind === "node" && ref?.id === nodeId));
1513
+ if (next.length !== (list || []).length) {
1514
+ db.run("UPDATE requirements SET participants_json = ?2, updated_at = ?3 WHERE requirement_id = ?1",
1515
+ [row.requirement_id, JSON.stringify(next), new Date().toISOString()]);
1516
+ participantsTouched += 1;
1517
+ }
1518
+ }
1519
+ return { agentOwnerCleared, participantsTouched };
1520
+ }
1521
+
1522
+ export function refDisplayName(json: string | null | undefined): string {
1523
+ /**
1524
+ * 把写入侧的引用 `{kind,id}` 换回**给人看的名字**(node → nodes.alias,user → users.username)。
1525
+ * 只给**写侧回填**用:读侧不再由它推导 assignee(见 displayAssignee 的注释)。
1526
+ */
1527
+ let ref: { kind?: string; id?: string; alias?: string; username?: string } | null = null;
1528
+ try { ref = json ? JSON.parse(json) : null; } catch { return ""; }
1529
+ if (!ref) return "";
1530
+ const inline = String(ref.alias || ref.username || "").trim();
1531
+ if (inline) return inline;
1532
+ if (!ref.id) return "";
1533
+ try {
1534
+ if (ref.kind === "node") {
1535
+ const r = db.get<{ alias: string | null }>("SELECT alias FROM nodes WHERE node_id = ?1", ref.id);
1536
+ if (r?.alias) return String(r.alias);
1537
+ } else if (ref.kind === "user") {
1538
+ const r = db.get<{ username: string | null }>("SELECT username FROM users WHERE user_id = ?1", ref.id);
1539
+ if (r?.username) return String(r.username);
1540
+ }
1541
+ } catch { /* 读不到就退回 id */ }
1542
+ return String(ref.id);
1543
+ }
1544
+
1545
+ export function displayAssignee(row: { assignee?: string | null }): string {
1546
+ /**
1547
+ * 2026-10-31 —— **只回显存下来的值,不从引用推导**(两次实测把方向改对了):
1548
+ * · 契约要求「显式 assignee 不被引用覆盖」(requirements-http 老测试)
1549
+ * · 契约也要求「显式清空后就是空」(同文件的 cleared 用例)
1550
+ * 两者合起来意味着:读侧无法区分「从没设过」与「显式清空」⇒ 推导就会猜错其中一边。
1551
+ * ⇒ 漂移的修法放在**写侧回填**(设引用且没显式给 assignee 时),读侧只负责如实显示。
1552
+ */
1553
+ return String(row.assignee || "").trim();
1510
1554
  }
1511
1555
 
1512
1556
  const parseRef = (json: string | null) => { try { return json ? JSON.parse(json) : null; } catch { return null; } };
package/src/server.ts CHANGED
@@ -105,7 +105,7 @@ import { diagnoseTask } from "./task-diagnostic.js";
105
105
  import { listTaskLateReplies } from "./task-late-replies.js";
106
106
  import { assertScheduledTaskBackendSupported, handleScheduledTaskRequest, startScheduledTaskScheduler } from "./scheduled-tasks.js";
107
107
  import { startDueReminderTimer } from "./requirement-due-reminders.js";
108
- import { handleRequirementsRequest } from "./requirements.js";
108
+ import { clearNodeFromRequirements, handleRequirementsRequest } from "./requirements.js";
109
109
  import { readHubProviders, putHubProvider, providerWriteStatus } from "./hub-provider-config.js";
110
110
  import { requestProviderApplication } from "./daemon-provider-snapshots.js";
111
111
  import { requestNodeSecrets, getScopedSecrets } from "./scoped-secrets.js";
@@ -1212,6 +1212,17 @@ export const SELECTION_STATE_BY_STATUS: Record<string, "pending" | "applied" | "
1212
1212
  expired: "failed", // 过期=没生效;对使用者与失败同一档
1213
1213
  };
1214
1214
 
1215
+ /**
1216
+ * 2026-10-31 —— `status` 与 `status_reasons` **是同一个位的两种说法**(外部复核:
1217
+ * 「三字段一致时零证据」)。既然它们由构造保证一致,那么「status=='ok' ⟺ reasons 为空」
1218
+ * 这条断言**恒真**,它保护不了任何东西。
1219
+ * ⇒ 把映射抽成一个纯函数,测试改为断言**映射本身**(给一个理由就必须 degraded),
1220
+ * 这样「有人把映射改成忽略 reasons」会红,而「两者一致」这种同义反复不会写成测试。
1221
+ */
1222
+ export function statusFromReasons(reasons: readonly string[]): "ok" | "degraded" {
1223
+ return reasons.length === 0 ? "ok" : "degraded";
1224
+ }
1225
+
1215
1226
  export const HEALTH_FIELD_META: Readonly<Record<string, HealthFieldMeta>> = {
1216
1227
  // ── gauge:聚合 / 粗标签 ─────────────────────────────────────────────
1217
1228
  ok: {
@@ -3680,7 +3691,7 @@ return Bun.serve({
3680
3691
  const body: Record<string, unknown> = {
3681
3692
  ok: true,
3682
3693
  // 200 是**承诺**(watchdog 契约),不等于「健康」。健康与否放在 body 里:
3683
- status: statusReasons.length === 0 ? "ok" : "degraded",
3694
+ status: statusFromReasons(statusReasons),
3684
3695
  status_reasons: statusReasons,
3685
3696
  version: SERVER_VERSION,
3686
3697
  version_source: SERVER_VERSION_SOURCE,
@@ -6227,6 +6238,7 @@ return Bun.serve({
6227
6238
  db.transaction(() => {
6228
6239
  db.run("DELETE FROM nodes WHERE node_id = ?1", [node.node_id]);
6229
6240
  clearNodeFromAgentTeams(node.node_id); // #764
6241
+ clearNodeFromRequirements(node.node_id); // #3277:卡上指向它的引用一并清掉
6230
6242
  if (node.alias) {
6231
6243
  db.run(
6232
6244
  "DELETE FROM sessions WHERE alias = ?1 AND (network_id = ?2 OR (CAST(?2 AS TEXT) IS NULL AND network_id IS NULL))",
package/src/tools.ts CHANGED
@@ -39,7 +39,7 @@ import { broadcastVerdict, dispatchVerdict, humanOnlyVerdict, NODE_TOOL_CLASS, n
39
39
  import { countInFlightTasks } from "./node-in-flight-tasks.js";
40
40
  import { restrictedMemberAttachmentsDenied } from "./restricted-files.js";
41
41
  import { errorBody } from "./requirements-errors.js";
42
- import { handleRequirementsRequest } from "./requirements.js";
42
+ import { handleRequirementsRequest, clearNodeFromRequirements } from "./requirements.js";
43
43
  import {
44
44
  buildAnetArgs as _unused_buildAnetArgs, // ensure module is loaded
45
45
  validateName as validateChildName,
@@ -6003,6 +6003,9 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
6003
6003
  // By node_id, not alias — a same-alias rebuild keeps its session.
6004
6004
  db.run(`DELETE FROM sessions WHERE node_id = ?1`, [row.child_node_id]);
6005
6005
  clearNodeFromAgentTeams(row.child_node_id); // #764
6006
+ // 2026-10-31 —— #3277:卡上的引用也要清(实测 3 个已删节点仍被 27 张卡引用,
6007
+ // 其中 2 个 id 在 api_tokens 里还有绑定行 ⇒ 这是删除路径的缺口,不是录入错误)。
6008
+ clearNodeFromRequirements(row.child_node_id);
6006
6009
  auditCreateNodeStrict({
6007
6010
  action: "delete_node_completed",
6008
6011
  user_id: null, network_id: row.network_id, target_id: request_id,