@sleep2agi/commhub-server 0.9.0-preview.179 → 0.9.0-preview.181

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.179",
3
+ "version": "0.9.0-preview.181",
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",
@@ -0,0 +1,49 @@
1
+ // #2756 —— `/health` 必须能看见 Hub 自己所在磁盘的水位。
2
+ //
3
+ // 起因:2026-10-28 04:05 我「偶尔巡检」才发现根分区 95%(剩 28G)。
4
+ // 上一轮清理(85%)之后它只用了一天多就涨回 10 个点 —— 靠人记得看,必然会漏;
5
+ // 而 Hub 的 DB / 日志 / 运行时目录都写在这块盘上,写满即生产停摆。
6
+ //
7
+ // 这条测试钉三件事:
8
+ // 1. 形状稳定(path / total_gb / used_gb / avail_gb / used_pct 都有);
9
+ // 2. 数值自洽(used + avail ≈ total,used_pct 与两者一致);
10
+ // 3. 探针打在 DB 目录上,不是写死 `/`。
11
+ //
12
+ // Run: COMMHUB_DB=/tmp/2756-health-disk.db bun test src/health-host-disk-2756.test.ts
13
+
14
+ import { describe, expect, test } from "bun:test";
15
+ import { hostDiskState } from "./server.js";
16
+
17
+ describe("#2756 /health.host_disk", () => {
18
+ test("形状完整且数值自洽", () => {
19
+ const d = hostDiskState();
20
+ expect(d).not.toBeNull();
21
+ const v = d!;
22
+ expect(typeof v.path).toBe("string");
23
+ expect(v.path.startsWith("/")).toBe(true);
24
+ expect(v.total_gb).toBeGreaterThan(0);
25
+ expect(v.avail_gb).toBeGreaterThanOrEqual(0);
26
+ expect(v.used_gb).toBeGreaterThanOrEqual(0);
27
+ expect(v.used_gb + v.avail_gb).toBeCloseTo(v.total_gb, 0);
28
+ expect(v.used_pct).toBeGreaterThanOrEqual(0);
29
+ expect(v.used_pct).toBeLessThanOrEqual(100);
30
+ });
31
+
32
+ test("探针目录来自 COMMHUB_DB 所在目录(不是写死 /)", () => {
33
+ const d = hostDiskState();
34
+ const db = process.env.COMMHUB_DB || "";
35
+ if (db.includes("/")) {
36
+ const dir = db.replace(/[^/]*$/, "");
37
+ expect(d!.path).toBe(dir);
38
+ }
39
+ });
40
+
41
+ test("水位与 df 同量级(10% 以内偏差,防止把字节单位算错)", () => {
42
+ const d = hostDiskState()!;
43
+ // 用 statfs 自身再算一遍独立值作对照
44
+ const fs = require("node:fs");
45
+ const st = fs.statfsSync(d.path);
46
+ const pct = Math.round((1 - Number(st.bavail) / Number(st.blocks)) * 1000) / 10;
47
+ expect(Math.abs(d.used_pct - pct)).toBeLessThan(10);
48
+ });
49
+ });
@@ -0,0 +1,50 @@
1
+ // 探针:target_offline 连续跳过后,next_run_at 到底被推到哪里?
2
+ // 生产现象(2026-10-28 08:45):backoff_effective_seconds=5760,但实际间隔 360s。
3
+ // 这里用真实调度入口 dispatchScheduledOccurrence 复现,看 next_run_at 与实际 cadence。
4
+ // Run: COMMHUB_DB=/tmp/target-offline-backoff.db bun test src/scheduled-offline-backoff-probe.test.ts
5
+ import { describe, expect, test, beforeAll } from 'bun:test';
6
+ import { register } from './auth.js';
7
+ import { db } from './db.js';
8
+ import { dispatchScheduledOccurrence, getScheduleRow } from './scheduled-tasks.js';
9
+
10
+ const stamp = Date.now();
11
+ const TARGET_ID = `n_offb_${stamp}`, TARGET = `offb-${stamp}`;
12
+ let NET = '', USER = '';
13
+
14
+ function seed() {
15
+ const id = `sched_offb_${crypto.randomUUID()}`;
16
+ db.run(`INSERT INTO scheduled_tasks (schedule_id, network_id, created_by, name, target_node_id, target_alias,
17
+ task_content, priority, schedule_type, schedule_json, timezone, status, next_run_at, overlap_policy)
18
+ VALUES (?1,?2,?3,'offb',?4,?5,'x','normal','interval','{"type":"interval","every_seconds":180}','Asia/Shanghai','active',datetime('now','+3 minutes'),'skip')`,
19
+ [id, NET, USER, TARGET_ID, TARGET]);
20
+ return getScheduleRow(id)!;
21
+ }
22
+
23
+ beforeAll(() => {
24
+ const owner = register(`offb_owner_${stamp}`, 'OffbOwnerPassw0rd!', undefined, 'seed');
25
+ expect(owner.ok).toBe(true);
26
+ NET = owner.network_id!; USER = owner.user!.user_id;
27
+ db.run("INSERT INTO nodes (node_id, node_name, alias, runtime, network_id, owner_user_id) VALUES (?1,?2,?2,'codex',?3,?4)", [TARGET_ID, TARGET, NET, USER]);
28
+ // 目标会话:10 分钟没心跳 ⇒ offline
29
+ db.run("INSERT INTO sessions (resume_id, alias, status, node_id, network_id, last_seen_at) VALUES (?1,?2,'idle',?3,?4,datetime('now','-10 minutes'))",
30
+ [`r_offb_${stamp}`, TARGET, TARGET_ID, NET]);
31
+ });
32
+
33
+ describe('target_offline backoff 是否真的推后 next_run_at', () => {
34
+ test('连续 4 次离线跳过后,next_run_at 应 ≈ now + effective(而不是 base 的倍数)', () => {
35
+ const s = seed();
36
+ const rows: any[] = [];
37
+ for (let i = 0; i < 4; i++) {
38
+ const at = new Date(Date.now() + i * 10).toISOString();
39
+ const r = dispatchScheduledOccurrence(getScheduleRow(s.schedule_id)!, at, true, new Date());
40
+ const after = db.get<any>("SELECT backoff_effective_seconds, backoff_streak, next_run_at FROM scheduled_tasks WHERE schedule_id = ?1", s.schedule_id);
41
+ const nextMs = after.next_run_at ? Date.parse(String(after.next_run_at).replace(' ', 'T') + (String(after.next_run_at).endsWith('Z') ? '' : 'Z')) : NaN;
42
+ rows.push({ i, status: r.status, eff: after.backoff_effective_seconds, streak: after.backoff_streak, next_raw: after.next_run_at, gap_s: Number.isFinite(nextMs) ? Math.round((nextMs - Date.parse(at))/1000) : 'NaN' });
43
+ }
44
+ console.log('每次 fire 后:', JSON.stringify(rows));
45
+ const last = rows[rows.length - 1];
46
+ // 断言:最后一次的 next_run_at 与 effective 同量级(允许 ±2 个 base 的容差)
47
+ if (!last.eff) throw new Error('backoff_effective_seconds 始终为空:退避没有生效');
48
+ if (last.gap_s < last.eff) throw new Error(`next_run_at 只推后 ${last.gap_s}s,但 effective=${last.eff}s`);
49
+ });
50
+ });
@@ -456,7 +456,13 @@ export function dispatchScheduledOccurrence(row: ScheduledRow, scheduledFor: str
456
456
  if (bo && bo.effective_seconds) {
457
457
  const sched = db.get<{ next_run_at: string | null }>("SELECT next_run_at FROM scheduled_tasks WHERE schedule_id = ?1", row.schedule_id);
458
458
  const at = parseHubTimestamp(sched?.next_run_at);
459
+ // 可观测性(不是装饰):生产出现「backoff_effective_seconds=5760 但实际每 6 分钟跳一次」,
460
+ // 只看列分不清是哪一步把 next_run_at 写回去了。这行把「算出的 eff」与「此刻落库的 next」
461
+ // 打在一起;再配上本函数返回前的最终值,就能对上账。
462
+ console.error(`[commhub scheduled-tasks] offline-backoff schedule=${row.schedule_id} cause=${bo.cause} streak=${bo.streak} effective=${bo.effective_seconds}s next_before=${sched?.next_run_at ?? 'null'}`);
459
463
  if (at !== null) advance({ ...row, target_alias: targetNode.alias }, scheduledFor, new Date(at));
464
+ const after = db.get<{ next_run_at: string | null }>("SELECT next_run_at FROM scheduled_tasks WHERE schedule_id = ?1", row.schedule_id);
465
+ console.error(`[commhub scheduled-tasks] offline-backoff-final schedule=${row.schedule_id} next_after=${after?.next_run_at ?? 'null'}`);
460
466
  }
461
467
  } catch (e: any) {
462
468
  console.error(`[scheduled-tasks] no-progress backoff failed schedule=${row.schedule_id}: ${e?.message || e}`);
package/src/server.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import { statfsSync } from "node:fs";
2
+ import { homedir } from "node:os";
1
3
  import { hostSupervisorIdentityRows } from "./host-supervisor-identity.js";
2
4
  import { buildServeErrorResponse } from "./serve-error.js";
3
5
  import { sanitizeRuntimeReadiness } from "./runtime-readiness.js";
@@ -2818,6 +2820,13 @@ return Bun.serve({
2818
2820
  // #2721 —— 最近一次广播(时间/收件人数/批数/耗时)。广播是唯一能一次性唤醒
2819
2821
  // 几百个 agent 的动作;没有这一格,事后只能把停顿记录和聊天记录对时间。
2820
2822
  broadcast: broadcastRecentState(),
2823
+ // #2756 —— Hub 自己所在磁盘的水位。
2824
+ //
2825
+ // 为什么要进 /health:2026-10-28 04:05 我做巡检时才发现根分区已经 95%(剩 28G)——
2826
+ // 上一轮清理(85%)之后它只用了一天多就涨回去 10 个点,靠人「偶尔看一眼」
2827
+ // 必然会漏。Hub 的 DB、日志、运行时目录都写在这块盘上,写满即生产停摆,
2828
+ // 所以这个数字应该和 sessions/stalls 一样随手可见。
2829
+ host_disk: hostDiskState(),
2821
2830
  auth: DEV_OPEN ? "dev-open" : "user-token",
2822
2831
  security: DEV_OPEN ? "dev-open" : "secured",
2823
2832
  tmux: TMUX_ENABLED ? "enabled" : "disabled",
@@ -5808,3 +5817,31 @@ export function startHub(opts?: { port?: number; hostname?: string }): ReturnTyp
5808
5817
  startedHub = { server, startedAt: new Date().toISOString() };
5809
5818
  return server;
5810
5819
  }
5820
+ /**
5821
+ * #2756 —— Hub 所在文件系统的水位。
5822
+ *
5823
+ * 只报「一块盘」:数据库目录所在的那块。多挂载点的主机(比如把 DB 放到单独卷)
5824
+ * 也能对得上,因为我们 statfs 的是 DB 的实际路径,不是写死 `/`。
5825
+ *
5826
+ * 为什么不在这里做告警:告警需要阈值与通知渠道,属于运维策略;这里只提供**可观测**。
5827
+ * 客户端/巡检脚本按 `used_pct > 90` 自己决定要不要叫。
5828
+ */
5829
+ export function hostDiskState(): { path: string; total_gb: number; used_gb: number; avail_gb: number; used_pct: number } | null {
5830
+ try {
5831
+ // 探针打在**数据库实际所在目录**上,而不是写死 `/`:多挂载点主机也能对得上。
5832
+ const dbFile = process.env.COMMHUB_DB || `${process.env.HOME || homedir()}/.commhub/commhub.db`;
5833
+ const probe = dbFile.includes("/") ? dbFile.replace(/[^/]*$/, "") || "/" : "/";
5834
+ const st = statfsSync(probe);
5835
+ const total = Number(st.blocks) * Number(st.bsize);
5836
+ const avail = Number(st.bavail) * Number(st.bsize);
5837
+ if (!Number.isFinite(total) || total <= 0) return null;
5838
+ const used = total - avail;
5839
+ const gb = (n: number) => Math.round((n / 1024 ** 3) * 10) / 10;
5840
+ return { path: probe, total_gb: gb(total), used_gb: gb(used), avail_gb: gb(avail), used_pct: Math.round((used / total) * 1000) / 10 };
5841
+ } catch {
5842
+ return null;
5843
+ }
5844
+ }
5845
+
5846
+
5847
+