@sleep2agi/commhub-server 0.9.0-preview.65 → 0.9.0-preview.67

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.
@@ -0,0 +1,51 @@
1
+ // 需求卡的启动迁移。requirements.ts 载入时调用一次(列由 db.ts 的加列循环加上)。
2
+ import type { DbAdapter } from "./db-adapter";
3
+
4
+ /**
5
+ * 负责人 = 人类(owner, kind user);负责 Agent = 节点(agent_owner, kind node)。
6
+ * 之前 owner 可以是节点:这些卡把节点挪到 agent_owner、owner 置空。只动 agent_owner 还空着的行,
7
+ * 所以重复执行不会再改任何东西;不删行,不碰别的列。在 JS 里判 kind(不依赖 SQLite 的 json_extract)。
8
+ */
9
+ export function migrateRequirementAgentOwners(database: DbAdapter): { moved: number } {
10
+ const rows = database.all<{ requirement_id: string; owner_json: string | null }>(
11
+ "SELECT requirement_id, owner_json FROM requirements WHERE owner_json IS NOT NULL AND agent_owner_json IS NULL",
12
+ );
13
+ let moved = 0;
14
+ for (const row of rows) {
15
+ let owner: { kind?: unknown; id?: unknown } | null = null;
16
+ try { owner = JSON.parse(row.owner_json || "null"); } catch { continue; }
17
+ if (!owner || owner.kind !== "node" || typeof owner.id !== "string" || !owner.id) continue;
18
+ database.run(
19
+ "UPDATE requirements SET agent_owner_json = ?1, owner_json = NULL WHERE requirement_id = ?2 AND agent_owner_json IS NULL",
20
+ [JSON.stringify({ kind: "node", id: owner.id }), row.requirement_id],
21
+ );
22
+ moved += 1;
23
+ }
24
+ return { moved };
25
+ }
26
+
27
+ /**
28
+ * 项目表(需求卡的「项目」)。只建表、建索引,不塞任何项目 —— 军团项目 / TMAI 由 owner 在界面里建。
29
+ * CREATE ... IF NOT EXISTS:重复执行无副作用。放在这里而不是 db.ts,db.ts 的行号被文档钉着。
30
+ */
31
+ export function ensureRequirementProjects(database: DbAdapter): void {
32
+ database.exec(`
33
+ CREATE TABLE IF NOT EXISTS requirement_projects (
34
+ project_id TEXT PRIMARY KEY,
35
+ network_id TEXT NOT NULL,
36
+ name TEXT NOT NULL,
37
+ color TEXT NOT NULL,
38
+ sort INTEGER NOT NULL DEFAULT 0,
39
+ archived INTEGER NOT NULL DEFAULT 0,
40
+ created_at TEXT NOT NULL
41
+ );
42
+ CREATE INDEX IF NOT EXISTS idx_requirement_projects_network ON requirement_projects(network_id, sort);
43
+ `);
44
+ }
45
+
46
+ /** external_ref 在同一网络里唯一(只管有值的行)。IF NOT EXISTS:重复执行无副作用。 */
47
+ export function ensureRequirementIndexes(database: DbAdapter): void {
48
+ database.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_requirements_external_ref ON requirements(network_id, external_ref) WHERE external_ref IS NOT NULL");
49
+ database.exec("CREATE INDEX IF NOT EXISTS idx_requirements_network_updated ON requirements(network_id, updated_at)");
50
+ database.exec("CREATE INDEX IF NOT EXISTS idx_requirements_parent ON requirements(parent_id) WHERE parent_id IS NOT NULL");
51
+ }
@@ -0,0 +1,126 @@
1
+ // 负责人 / 负责 Agent 拆分:一次性 Hub 进程的升级端到端。
2
+ // 真起两次 `bun run src/index.ts`(HOME=临时目录、随机端口、绝不是 9200、独立库):
3
+ // 第一次:注册、建节点、建一张「旧式」卡(owner 是节点 —— 用 SQL 写进去,因为新 Hub 已不接受);
4
+ // 再把 agent_owner_json 列删掉,库回到 #2065 时代的样子。
5
+ // 第二次:同一个库启动 = 升级。启动迁移把节点挪到 agent_owner,HTTP 读回;然后走一遍新规则。
6
+ import { afterAll, expect, test } from "bun:test";
7
+ import { Database } from "bun:sqlite";
8
+ import { mkdtempSync, rmSync } from "node:fs";
9
+ import { tmpdir } from "node:os";
10
+ import { join, resolve } from "node:path";
11
+ import { spawn, type ChildProcess } from "node:child_process";
12
+
13
+ const home = mkdtempSync(join(tmpdir(), "anet-req-agent-owner-e2e-"));
14
+ const dbFile = join(home, "hub.db");
15
+ const port = 20000 + Math.floor(Math.random() * 20000);
16
+ if (port === 9200) throw new Error("9200 is the production hub port");
17
+ const base = `http://127.0.0.1:${port}`;
18
+ const serverDir = resolve(import.meta.dir, "..");
19
+ let proc: ChildProcess | null = null;
20
+
21
+ async function startHub() {
22
+ proc = spawn("bun", ["run", "src/index.ts"], {
23
+ cwd: serverDir,
24
+ env: { PATH: process.env.PATH || "", HOME: home, COMMHUB_DB: dbFile, COMMHUB_SERVER: "1", PORT: String(port), HOST: "127.0.0.1" },
25
+ stdio: ["ignore", "ignore", "pipe"],
26
+ });
27
+ let err = "";
28
+ proc.stderr?.on("data", d => { err += String(d); });
29
+ for (let i = 0; i < 100; i++) {
30
+ try { if ((await fetch(`${base}/health`)).ok) return; } catch {}
31
+ await new Promise(r => setTimeout(r, 150));
32
+ }
33
+ throw new Error(`hub did not start on ${port}: ${err.slice(-600)}`);
34
+ }
35
+ async function stopHub() {
36
+ if (!proc) return;
37
+ const p = proc;
38
+ proc = null;
39
+ await new Promise<void>(res => { p.once("exit", () => res()); p.kill("SIGTERM"); setTimeout(() => { p.kill("SIGKILL"); res(); }, 5000); });
40
+ }
41
+ afterAll(async () => { await stopHub(); try { rmSync(home, { recursive: true, force: true }); } catch {} });
42
+
43
+ async function api(token: string, path: string, init?: RequestInit) {
44
+ const res = await fetch(`${base}${path}`, { ...init, headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" } });
45
+ return { status: res.status, body: await res.json() as any };
46
+ }
47
+
48
+ test("an upgraded hub moves node owners to agent_owner and then enforces human owner / agent executor", async () => {
49
+ await startHub();
50
+ const reg = await (await fetch(`${base}/api/auth/register`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ username: "e2e_owner", password: "E2eOwner123!pass" }) })).json() as any;
51
+ expect(reg.ok).toBe(true);
52
+ const token = reg.token as string, net = reg.network_id as string, uid = reg.user.user_id as string;
53
+ const human = { kind: "user", id: uid }, agent = { kind: "node", id: "node_e2e_exec" };
54
+ {
55
+ const db = new Database(dbFile);
56
+ db.run("INSERT INTO nodes (node_id,node_name,alias,network_id) VALUES (?1,'e2e-exec','e2e-exec',?2)", [agent.id, net]);
57
+ db.close();
58
+ }
59
+ const card = await api(token, "/api/requirements", { method: "POST", body: JSON.stringify({ name: "旧式卡", network_id: net, participants: [human] }) });
60
+ expect(card.status).toBe(201);
61
+ const keep = await api(token, "/api/requirements", { method: "POST", body: JSON.stringify({ name: "人类负责人卡", network_id: net, owner: human }) });
62
+ expect(keep.status).toBe(201);
63
+ await stopHub();
64
+ {
65
+ // 退回旧库:节点当负责人,且没有 agent_owner_json 列
66
+ const db = new Database(dbFile);
67
+ db.run("UPDATE requirements SET owner_json = ?1 WHERE requirement_id = ?2", [JSON.stringify(agent), card.body.requirement.id]);
68
+ db.exec("ALTER TABLE requirements DROP COLUMN agent_owner_json");
69
+ const cols = (db.query("PRAGMA table_info(requirements)").all() as { name: string }[]).map(c => c.name);
70
+ expect(cols.includes("agent_owner_json")).toBe(false);
71
+ db.close();
72
+ }
73
+ await startHub();
74
+ const listed = await api(token, `/api/requirements?network_id=${net}`);
75
+ expect(listed.status).toBe(200);
76
+ expect(listed.body.requirements.length).toBe(2);
77
+ const upgraded = listed.body.requirements.find((r: any) => r.id === card.body.requirement.id);
78
+ expect(upgraded.owner).toBeNull();
79
+ expect(upgraded.agent_owner).toEqual(agent);
80
+ expect(upgraded.participants).toEqual([human]);
81
+ expect(upgraded.name).toBe("旧式卡");
82
+ const untouched = listed.body.requirements.find((r: any) => r.id === keep.body.requirement.id);
83
+ expect(untouched.owner).toEqual(human);
84
+ expect(untouched.agent_owner).toBeNull();
85
+
86
+ const path = `/api/requirements/${upgraded.id}?network_id=${net}`;
87
+ const both = await api(token, path, { method: "PATCH", body: JSON.stringify({ owner: human }) });
88
+ expect(both.status).toBe(200);
89
+ expect(both.body.requirement.owner).toEqual(human);
90
+ expect(both.body.requirement.agent_owner).toEqual(agent);
91
+ expect((await api(token, path, { method: "PATCH", body: JSON.stringify({ owner: agent, agent_owner: agent }) })).body.error).toBe("owner_must_be_human");
92
+ expect((await api(token, path, { method: "PATCH", body: JSON.stringify({ agent_owner: human }) })).body.error).toBe("agent_owner_must_be_agent");
93
+
94
+ // 预计完成:旧卡的全天值(升级前写的)原样读回;改成带时刻的,存 UTC
95
+ const dated = await api(token, path, { method: "PATCH", body: JSON.stringify({ due: "2026-10-01" }) });
96
+ expect(dated.body.requirement.due).toBe("2026-10-01");
97
+ // 描述 / 子任务:升级后的旧卡可写,单项勾选只动那一项
98
+ expect(upgraded.description).toBe("");
99
+ expect(upgraded.checklist).toEqual([]);
100
+ const withList = await api(token, path, { method: "PATCH", body: JSON.stringify({ description: "# 验收\n- 能用", checklist: [{ id: "one", text: "第一步" }, { id: "two", text: "第二步" }] }) });
101
+ expect(withList.status).toBe(200);
102
+ const ticked = await api(token, `/api/requirements/${upgraded.id}/checklist/two?network_id=${net}`, { method: "PATCH", body: JSON.stringify({ done: true }) });
103
+ expect(ticked.body.requirement.checklist).toEqual([{ id: "one", text: "第一步", done: false }, { id: "two", text: "第二步", done: true }]);
104
+
105
+ // 项目:升级后没有任何项目(不预置),建一个、给旧卡挂上
106
+ expect((await api(token, `/api/requirements/projects?network_id=${net}`)).body.projects).toEqual([]);
107
+ const proj = await api(token, `/api/requirements/projects?network_id=${net}`, { method: "POST", body: JSON.stringify({ name: "军团项目" }) });
108
+ expect(proj.status).toBe(201);
109
+ expect((await api(token, path, { method: "PATCH", body: JSON.stringify({ project_id: proj.body.project.id }) })).body.requirement.project_id).toBe(proj.body.project.id);
110
+
111
+ // 第三次启动(同一个库):迁移不再改任何东西
112
+ await stopHub();
113
+ await startHub();
114
+ const again = (await api(token, `/api/requirements?network_id=${net}`)).body.requirements;
115
+ expect(again.length).toBe(2);
116
+ const same = again.find((r: any) => r.id === upgraded.id);
117
+ expect(same.owner).toEqual(human);
118
+ expect(same.agent_owner).toEqual(agent);
119
+ expect(same.description).toBe("# 验收\n- 能用");
120
+ expect(same.checklist.map((i: any) => i.done)).toEqual([false, true]);
121
+ expect(same.project_id).toBe(proj.body.project.id);
122
+ expect(same.due).toBe("2026-10-01");
123
+ const timed = await api(token, `/api/requirements/${upgraded.id}?network_id=${net}`, { method: "PATCH", body: JSON.stringify({ due: "2026-10-01T18:30:45+08:00" }) });
124
+ expect(timed.body.requirement.due).toBe("2026-10-01T10:30:45Z");
125
+ expect((await api(token, `/api/requirements/projects?network_id=${net}`)).body.projects.map((p: any) => p.name)).toEqual(["军团项目"]);
126
+ }, 60_000);
@@ -0,0 +1,85 @@
1
+ // 负责人 / 负责 Agent 拆分的启动迁移:旧库里 owner 是节点的卡,节点挪到 agent_owner、owner 置空。
2
+ // 用 #2065 时代的表结构(没有 agent_owner_json 列)先建库、塞行,再 import db.ts + requirements.ts(真实启动路径)。
3
+ import { afterAll, expect, test } from "bun:test";
4
+ import { Database } from "bun:sqlite";
5
+ import { mkdtempSync, rmSync } from "node:fs";
6
+ import { tmpdir } from "node:os";
7
+ import { join } from "node:path";
8
+
9
+ const dir = mkdtempSync(join(tmpdir(), "anet-req-agent-owner-"));
10
+ const file = join(dir, "hub.db");
11
+ process.env.COMMHUB_DB = file;
12
+
13
+ const legacy = new Database(file);
14
+ legacy.exec(`CREATE TABLE requirements (
15
+ requirement_id TEXT PRIMARY KEY, network_id TEXT NOT NULL, title TEXT NOT NULL,
16
+ column_name TEXT NOT NULL DEFAULT 'pool', priority TEXT NOT NULL DEFAULT 'normal', due_on TEXT, assignee TEXT,
17
+ client_id TEXT, issues_json TEXT, created_by TEXT,
18
+ created_at TEXT NOT NULL DEFAULT (datetime('now')), updated_at TEXT NOT NULL DEFAULT (datetime('now')),
19
+ owner_json TEXT, participants_json TEXT NOT NULL DEFAULT '[]')`);
20
+ const rows: [string, string | null, string][] = [
21
+ ["r_node_owner", JSON.stringify({ kind: "node", id: "node_x" }), JSON.stringify([{ kind: "user", id: "u1" }])],
22
+ ["r_user_owner", JSON.stringify({ kind: "user", id: "u1" }), "[]"],
23
+ ["r_no_owner", null, "[]"],
24
+ ["r_bad_json", "{not json", "[]"],
25
+ ["r_node_no_id", JSON.stringify({ kind: "node" }), "[]"],
26
+ ["r_node_owner_2", JSON.stringify({ kind: "node", id: "node_y" }), "[]"],
27
+ ];
28
+ for (const [id, owner, participants] of rows) {
29
+ legacy.run("INSERT INTO requirements (requirement_id, network_id, title, due_on, assignee, owner_json, participants_json) VALUES (?1, 'net', ?2, '2026-10-01', 'legacy', ?3, ?4)", [id, `卡 ${id}`, owner, participants]);
30
+ }
31
+ legacy.close();
32
+
33
+ afterAll(() => { try { rmSync(dir, { recursive: true, force: true }); } catch {} });
34
+
35
+ const snapshot = (db: any) => db.all("SELECT requirement_id, network_id, title, due_on, assignee, participants_json, owner_json, agent_owner_json, project_id FROM requirements ORDER BY requirement_id") as any[];
36
+
37
+ test("startup migration moves node owners to agent_owner, keeps every row, and is idempotent", async () => {
38
+ const { db } = await import("./db.js");
39
+ await import("./requirements.js"); // 真实启动路径:server.ts 载入 requirements.ts 时迁移
40
+ const { migrateRequirementAgentOwners } = await import("./requirements-migrate.js");
41
+ const after = snapshot(db);
42
+ expect(after.length).toBe(rows.length);
43
+ const by = Object.fromEntries(after.map(r => [r.requirement_id, r]));
44
+ expect(by.r_node_owner.owner_json).toBeNull();
45
+ expect(JSON.parse(by.r_node_owner.agent_owner_json)).toEqual({ kind: "node", id: "node_x" });
46
+ expect(by.r_node_owner.participants_json).toBe(JSON.stringify([{ kind: "user", id: "u1" }]));
47
+ expect(JSON.parse(by.r_node_owner_2.agent_owner_json)).toEqual({ kind: "node", id: "node_y" });
48
+ expect(JSON.parse(by.r_user_owner.owner_json)).toEqual({ kind: "user", id: "u1" });
49
+ expect(by.r_user_owner.agent_owner_json).toBeNull();
50
+ expect(by.r_no_owner.owner_json).toBeNull();
51
+ // 读不懂的旧值原样留着,不猜、不删
52
+ expect(by.r_bad_json.owner_json).toBe("{not json");
53
+ expect(by.r_node_no_id.owner_json).toBe(JSON.stringify({ kind: "node" }));
54
+ for (const r of after) {
55
+ expect(r.title).toBe(`卡 ${r.requirement_id}`);
56
+ expect(r.network_id).toBe("net");
57
+ expect(r.due_on).toBe("2026-10-01");
58
+ expect(r.assignee).toBe("legacy");
59
+ }
60
+ // 加列只加不改:旧行的描述 / 子任务是空
61
+ const cols = (db.all("PRAGMA table_info(requirements)") as { name: string }[]).map(c => c.name);
62
+ expect(cols.includes("description") && cols.includes("checklist_json") && cols.includes("agent_owner_json")).toBe(true);
63
+ const extra = db.all("SELECT description, checklist_json FROM requirements") as any[];
64
+ expect(extra.every(r => r.description === null && r.checklist_json === null)).toBe(true);
65
+ // 项目表:建了、是空的(不预置),重复执行不报错;卡片的 project_id 列只加不改
66
+ expect(cols.includes("project_id")).toBe(true);
67
+ // PR B:外部引用 / 归档 / 谁做的 —— 只加不改;旧行 archived = 0、其余 NULL;external_ref 的部分唯一索引建了
68
+ for (const c of ["external_ref", "external_url", "archived", "created_by_json", "updated_by_json", "parent_id"]) expect(cols.includes(c)).toBe(true);
69
+ expect((db.all("SELECT parent_id FROM requirements WHERE parent_id IS NOT NULL") as any[]).length).toBe(0);
70
+ expect((db.all("PRAGMA index_list(requirements)") as { name: string }[]).some(i => i.name === "idx_requirements_parent")).toBe(true);
71
+ expect((db.all("SELECT archived, external_ref FROM requirements") as any[]).every(r => r.archived === 0 && r.external_ref === null)).toBe(true);
72
+ const idx = (db.all("PRAGMA index_list(requirements)") as { name: string; unique: number }[]).find(i => i.name === "idx_requirements_external_ref");
73
+ expect(idx?.unique).toBe(1);
74
+ const { ensureRequirementIndexes } = await import("./requirements-migrate.js");
75
+ ensureRequirementIndexes(db);
76
+ expect((db.all("SELECT project_id FROM requirements WHERE project_id IS NOT NULL") as any[]).length).toBe(0);
77
+ expect((db.get("SELECT COUNT(*) AS n FROM requirement_projects") as any).n).toBe(0);
78
+ const { ensureRequirementProjects } = await import("./requirements-migrate.js");
79
+ ensureRequirementProjects(db);
80
+ ensureRequirementProjects(db);
81
+ expect((db.get("SELECT COUNT(*) AS n FROM requirement_projects") as any).n).toBe(0);
82
+ // 再跑一次(= 下次启动):什么都不动
83
+ expect(migrateRequirementAgentOwners(db).moved).toBe(0);
84
+ expect(snapshot(db)).toEqual(after);
85
+ });