@sleep2agi/commhub-server 0.9.0-preview.13 → 0.9.0-preview.131
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/README.md +130 -10
- package/bin/commhub.ts +99 -11
- package/package.json +7 -7
- package/src/ack-create-request-transport.test.ts +182 -0
- package/src/ack-create-request.test.ts +50 -7
- package/src/admin-delete-network-http.test.ts +228 -0
- package/src/admin-networks-http.test.ts +88 -0
- package/src/adoption-candidates-http.test.ts +137 -0
- package/src/adoption-candidates.ts +158 -0
- package/src/agent-access-batch.test.ts +210 -0
- package/src/agent-access.ts +487 -0
- package/src/agent-acl-groups-http.test.ts +247 -0
- package/src/agent-acl-http.test.ts +659 -0
- package/src/agent-acl-slice3-http.test.ts +267 -0
- package/src/agent-groups-perf.test.ts +223 -0
- package/src/agent-notice.ts +48 -0
- package/src/agent-team-whoami-http.test.ts +98 -0
- package/src/agent-teams-http.test.ts +323 -0
- package/src/agent-teams.ts +244 -0
- package/src/alias-filter.test.ts +72 -0
- package/src/alias-filter.ts +42 -0
- package/src/api-host-supervisors-can-create-nodes.test.ts +350 -0
- package/src/api-host-supervisors-fallback.test.ts +271 -0
- package/src/api-host-supervisors-runtime-readiness.test.ts +195 -0
- package/src/api-nodes-shape.test.ts +26 -10
- package/src/auth-password-change-cli-tokens-http.test.ts +294 -0
- package/src/auth-sessions-http.test.ts +250 -0
- package/src/auth-validate.test.ts +5 -1
- package/src/auth-weak-password-login.test.ts +176 -0
- package/src/auth.ts +598 -49
- package/src/avatar-validate.test.ts +163 -0
- package/src/avatar-validate.ts +103 -0
- package/src/binding-generation-http.test.ts +121 -0
- package/src/blocked-exit-on-reply.test.ts +122 -0
- package/src/boot-side-effect.test.ts +124 -0
- package/src/clone-node.test.ts +248 -0
- package/src/clone-node.ts +289 -0
- package/src/codex-config-flags.ts +77 -0
- package/src/codex-fork-contract.ts +23 -0
- package/src/codex-fork-migration.test.ts +38 -0
- package/src/commhub-bin-args.test.ts +85 -0
- package/src/config-apply-sec1.test.ts +107 -0
- package/src/config-apply-validate.test.ts +134 -1
- package/src/config-apply-validate.ts +111 -5
- package/src/create-node-blocked-gate.test.ts +356 -0
- package/src/create-node-network-id.test.ts +79 -0
- package/src/create-node-tool-schema.test.ts +48 -0
- package/src/create-node-unicode-name.test.ts +120 -0
- package/src/create-node-validate.test.ts +193 -7
- package/src/create-node-validate.ts +227 -15
- package/src/create-node-workdir.test.ts +289 -0
- package/src/create-node.ts +77 -23
- package/src/daemon-provider-snapshots.test.ts +421 -0
- package/src/daemon-provider-snapshots.ts +327 -0
- package/src/daemon-token-owner-http.test.ts +236 -0
- package/src/dashboard-slash-routing-http.test.ts +107 -0
- package/src/db-adapter-guard.test.ts +148 -0
- package/src/db-adapter-translate.test.ts +128 -0
- package/src/db-adapter.ts +323 -87
- package/src/db-timestamp.test.ts +38 -0
- package/src/db-timestamp.ts +15 -0
- package/src/db.ts +933 -36
- package/src/delivered-without-push.test.ts +140 -0
- package/src/department-groups-http.test.ts +209 -0
- package/src/department-groups-sync-http.test.ts +328 -0
- package/src/department-groups.ts +434 -0
- package/src/department-heads-http.test.ts +330 -0
- package/src/department-heads.ts +226 -0
- package/src/departments-http.test.ts +185 -0
- package/src/departments.ts +260 -0
- package/src/desktop-message-seam.test.ts +150 -0
- package/src/desktop-message.test.ts +368 -0
- package/src/dm-file-scope-http.test.ts +178 -0
- package/src/ext-token-shared.test.ts +60 -0
- package/src/ext-validation-regression.test.ts +131 -0
- package/src/external-schedule-edits-http.test.ts +321 -0
- package/src/external-schedule-edits-timestamps.test.ts +64 -0
- package/src/external-schedule-edits.ts +327 -0
- package/src/file-download-authz-dev-open.test.ts +135 -0
- package/src/file-download-authz.test.ts +404 -0
- package/src/file-download-date-bucket.test.ts +436 -0
- package/src/file-network-scope-dev-open.test.ts +97 -0
- package/src/file-network-scope.test.ts +732 -0
- package/src/group-membership-events-http.test.ts +264 -0
- package/src/group-messages-http.test.ts +482 -0
- package/src/group-messages.ts +297 -0
- package/src/health-redaction.test.ts +642 -0
- package/src/http-gzip.test.ts +94 -0
- package/src/http-gzip.ts +112 -0
- package/src/hub-provider-config.test.ts +139 -0
- package/src/hub-provider-config.ts +105 -0
- package/src/hub-timestamp.test.ts +38 -0
- package/src/hub-timestamp.ts +27 -0
- package/src/human-dm.ts +215 -0
- package/src/inbox-caller.ts +49 -0
- package/src/inbox-count-sse.test.ts +310 -0
- package/src/inbox-count.ts +29 -0
- package/src/index.ts +15 -2362
- package/src/lifecycle-guard.ts +1 -1
- package/src/mcp-context-cost-http.test.ts +123 -0
- package/src/mcp-projects-events-http.test.ts +162 -0
- package/src/mcp-route-label-http.test.ts +120 -0
- package/src/mcp-write-network-resolution.test.ts +432 -0
- package/src/member-audit-network-id-http.test.ts +93 -0
- package/src/member-presence-http.test.ts +210 -0
- package/src/messages-ack-by-agent-http.test.ts +142 -0
- package/src/migrate-sqlite-to-pg.test.ts +47 -0
- package/src/migrate-sqlite-to-pg.ts +263 -0
- package/src/model-auth-notify-http.test.ts +181 -0
- package/src/model-auth-notify.ts +116 -0
- package/src/network-name-http.test.ts +75 -0
- package/src/network-scope.ts +276 -0
- package/src/network-token-membership-http.test.ts +139 -0
- package/src/node-alias-control.ts +12 -0
- package/src/node-attrs-validate.ts +88 -0
- package/src/node-attrs.test.ts +217 -0
- package/src/node-caller-identity-http.test.ts +781 -0
- package/src/node-create-request-status-http.test.ts +105 -0
- package/src/node-daemon-bindings.test.ts +132 -0
- package/src/node-daemon-bindings.ts +130 -0
- package/src/node-files-transport.test.ts +344 -0
- package/src/node-health-codex-login.test.ts +120 -0
- package/src/node-health-dispatch-http.test.ts +279 -0
- package/src/node-health-guard.ts +105 -0
- package/src/node-health-passthrough.test.ts +115 -0
- package/src/node-health-store.ts +101 -0
- package/src/node-id-alias.test.ts +190 -0
- package/src/node-identity-conflict-http.test.ts +269 -0
- package/src/node-identity-conflict.ts +142 -0
- package/src/node-identity-mismatch.test.ts +74 -0
- package/src/node-lifecycle-controllable.test.ts +64 -0
- package/src/node-lifecycle-controllable.ts +53 -0
- package/src/node-lifecycle-read-http.test.ts +245 -0
- package/src/node-lifecycle-read.ts +121 -0
- package/src/node-logs-transport.test.ts +263 -0
- package/src/node-permissions-http.test.ts +276 -0
- package/src/node-permissions.ts +285 -0
- package/src/node-request-retention.test.ts +281 -0
- package/src/node-request-retention.ts +120 -0
- package/src/node-skills-transport.test.ts +209 -0
- package/src/node-token-ownership.ts +51 -0
- package/src/node-token-privilege-http.test.ts +158 -0
- package/src/observer-avatar-http.test.ts +431 -0
- package/src/observer-push.test.ts +252 -0
- package/src/opencode-v2-catalog.test.ts +268 -0
- package/src/opencode-v2-catalog.ts +352 -0
- package/src/package-version-consistency.test.ts +25 -0
- package/src/peer-reply-atomic.test.ts +455 -0
- package/src/peer-reply-capability.test.ts +70 -0
- package/src/pg-worker.ts +87 -0
- package/src/project-dir-warn-clear-http.test.ts +132 -0
- package/src/project-viewer-can-http.test.ts +114 -0
- package/src/push.ts +429 -10
- package/src/redact-tokens.test.ts +65 -0
- package/src/redact-tokens.ts +40 -0
- package/src/rename.ts +22 -2
- package/src/reply-target-derivation.test.ts +96 -0
- package/src/report-status-handover-capabilities-http.test.ts +124 -0
- package/src/report-status-host-schema.test.ts +235 -0
- package/src/report-status-resume-id-handover.test.ts +150 -0
- package/src/require-explicit-test-db.ts +9 -0
- package/src/requirement-due-reminders-http.test.ts +620 -0
- package/src/requirement-due-reminders.ts +416 -0
- package/src/requirement-events-http.test.ts +268 -0
- package/src/requirement-events.test.ts +45 -0
- package/src/requirement-events.ts +144 -0
- package/src/requirement-notify.ts +165 -0
- package/src/requirement-participant-notify-http.test.ts +309 -0
- package/src/requirement-tag-ops-http.test.ts +266 -0
- package/src/requirement-tags.ts +89 -0
- package/src/requirements-abandoned-http.test.ts +236 -0
- package/src/requirements-comment-http.test.ts +167 -0
- package/src/requirements-completed-at-migration.test.ts +70 -0
- package/src/requirements-errors-mcp-http.test.ts +164 -0
- package/src/requirements-errors.ts +143 -0
- package/src/requirements-etag-http.test.ts +91 -0
- package/src/requirements-http.test.ts +709 -0
- package/src/requirements-last-event-http.test.ts +349 -0
- package/src/requirements-list-mcp-slim-http.test.ts +155 -0
- package/src/requirements-list-slim-http.test.ts +319 -0
- package/src/requirements-mcp.test.ts +163 -0
- package/src/requirements-migrate.ts +259 -0
- package/src/requirements-owner-strict-mcp-http.test.ts +145 -0
- package/src/requirements-people-http.test.ts +114 -0
- package/src/requirements-people-mcp-http.test.ts +225 -0
- package/src/requirements-people.ts +127 -0
- package/src/requirements-priority-lowest.test.ts +114 -0
- package/src/requirements-search-http.test.ts +182 -0
- package/src/requirements-search.test.ts +32 -0
- package/src/requirements-search.ts +145 -0
- package/src/requirements-seq-http.test.ts +193 -0
- package/src/requirements-seq-migration.test.ts +63 -0
- package/src/requirements-start-date.test.ts +125 -0
- package/src/requirements-stats-http.test.ts +288 -0
- package/src/requirements-stats.ts +167 -0
- package/src/requirements-status-participants-http.test.ts +222 -0
- package/src/requirements-upgrade-e2e.test.ts +126 -0
- package/src/requirements-upgrade-migration.test.ts +98 -0
- package/src/requirements.ts +1806 -0
- package/src/resolve-port.test.ts +57 -0
- package/src/resolve-port.ts +44 -0
- package/src/response-charset.test.ts +130 -0
- package/src/rest-explicit-columns-http.test.ts +222 -0
- package/src/rest-identity.test.ts +130 -0
- package/src/rest-identity.ts +139 -0
- package/src/rest-projections.ts +68 -0
- package/src/rest-write-network-resolution.test.ts +133 -0
- package/src/restricted-files.ts +76 -0
- package/src/retention.ts +15 -3
- package/src/route-callers-http.test.ts +120 -0
- package/src/route-timing.test.ts +211 -0
- package/src/route-timing.ts +258 -0
- package/src/rules-file-duplicate-alias.test.ts +234 -0
- package/src/rules-file-session-target.test.ts +207 -0
- package/src/rules-file-transport.test.ts +237 -0
- package/src/runtime-label.test.ts +22 -0
- package/src/runtime-label.ts +21 -0
- package/src/runtime-readiness.ts +90 -0
- package/src/schedule-agent-mcp-http.test.ts +381 -0
- package/src/schedule-agent.ts +192 -0
- package/src/scheduled-doorbell-nodeless-session.test.ts +134 -0
- package/src/scheduled-failures-http.test.ts +233 -0
- package/src/scheduled-failures.ts +179 -0
- package/src/scheduled-offline.test.ts +131 -0
- package/src/scheduled-offline.ts +66 -0
- package/src/scheduled-reply-unread-http.test.ts +212 -0
- package/src/scheduled-run-terminal.test.ts +268 -0
- package/src/scheduled-skip-blocking-task.test.ts +120 -0
- package/src/scheduled-stuck-http.test.ts +238 -0
- package/src/scheduled-stuck.ts +153 -0
- package/src/scheduled-tasks-http.test.ts +638 -0
- package/src/scheduled-tasks.ts +766 -0
- package/src/scoped-secrets.ts +124 -0
- package/src/send-dedup-request-id.test.ts +229 -0
- package/src/send-reply-agent-warning.test.ts +202 -0
- package/src/send-reply-alias-optional.test.ts +131 -0
- package/src/send-reply-attachments.test.ts +458 -0
- package/src/send_dedup.test.ts +54 -0
- package/src/send_dedup.ts +52 -6
- package/src/serve-error.test.ts +38 -0
- package/src/serve-error.ts +27 -0
- package/src/server.ts +5257 -0
- package/src/session-task-on-dispatch.ts +14 -0
- package/src/session-token-ownership-http.test.ts +122 -0
- package/src/shared/codex-inventory.ts +41 -0
- package/src/shared/daemon-provider-login.ts +31 -0
- package/src/shared/daemon-provider-snapshot.ts +52 -0
- package/src/shared/external-schedule-contract.ts +60 -0
- package/src/shared/node-name.test.ts +62 -0
- package/src/shared/node-name.ts +161 -0
- package/src/shared/provider-application.ts +29 -0
- package/src/shared/provider-collection.ts +14 -0
- package/src/shared/provider-initialization.ts +8 -0
- package/src/shared/reserved-env-drift.test.ts +10 -0
- package/src/shared/scoped-secret-contract.ts +5 -0
- package/src/shared/task-content-limit-drift.test.ts +28 -0
- package/src/shared/task-content-limit.ts +25 -0
- package/src/side-thread-command-transport.test.ts +312 -0
- package/src/side-thread-command-transport.ts +318 -0
- package/src/side-thread-http-integration.test.ts +233 -0
- package/src/side-thread-http.ts +504 -0
- package/src/side-thread-production.test.ts +72 -0
- package/src/side-thread-production.ts +118 -0
- package/src/side-thread.test.ts +1067 -0
- package/src/side-thread.ts +2499 -0
- package/src/skillhub-http.test.ts +108 -0
- package/src/sqlite-close-checkpoint.test.ts +78 -0
- package/src/start-node.test.ts +264 -0
- package/src/status-alias-filter-http.test.ts +106 -0
- package/src/status-alias-resolver-http.test.ts +163 -0
- package/src/status-alias-resolver.ts +19 -0
- package/src/status-node-id-filter-http.test.ts +161 -0
- package/src/status-read-cache-http.test.ts +229 -0
- package/src/status-read-cache.ts +122 -0
- package/src/stop-delete-node.test.ts +509 -1
- package/src/task-access-http.test.ts +402 -0
- package/src/task-access.ts +420 -0
- package/src/task-auth-origin-http.test.ts +93 -0
- package/src/task-auth-origin.test.ts +24 -0
- package/src/task-auth-origin.ts +7 -0
- package/src/task-consumption.test.ts +482 -0
- package/src/task-diagnostic-http.test.ts +149 -0
- package/src/task-diagnostic.test.ts +115 -0
- package/src/task-diagnostic.ts +118 -0
- package/src/task-expiry-notice-http.test.ts +287 -0
- package/src/task-expiry-notice.ts +315 -0
- package/src/task-idempotency-mcp.test.ts +142 -0
- package/src/task-idempotency.test.ts +60 -0
- package/src/task-idempotency.ts +75 -0
- package/src/task-late-replies.ts +54 -0
- package/src/task-late-reply-http.test.ts +152 -0
- package/src/task-lifecycle-watcher.test.ts +204 -0
- package/src/task-lifecycle-watcher.ts +49 -0
- package/src/task-network-resolution-http.test.ts +140 -0
- package/src/task-orphan-http.test.ts +287 -0
- package/src/task-orphan.ts +119 -0
- package/src/task-queue-ahead-http.test.ts +309 -0
- package/src/task-queue-ahead-scale.test.ts +236 -0
- package/src/task-queue-ahead.ts +186 -0
- package/src/task-rejection-log-http.test.ts +160 -0
- package/src/task-rejection-log.ts +49 -0
- package/src/task-sender-http.test.ts +143 -0
- package/src/task-stale-open-http.test.ts +290 -0
- package/src/task-stale-open.ts +103 -0
- package/src/tasks-pagination-http.test.ts +141 -0
- package/src/tool-audience-http.test.ts +220 -0
- package/src/tool-audience.ts +118 -0
- package/src/tools-list-json-schema.test.ts +67 -0
- package/src/tools.ts +3940 -325
- package/src/upload-early-reject-guard.test.ts +155 -0
- package/src/uploads-http.test.ts +97 -15
- package/src/uploads.ts +103 -6
- package/src/user-avatar-http.test.ts +74 -0
- package/src/user-avatar-migration.test.ts +25 -0
- package/src/user-inbox-by-agent-http.test.ts +161 -0
- package/src/user-inbox-netid-notnull.test.ts +122 -0
- package/src/user-inbox-read-http.test.ts +223 -0
- package/src/user-inbox-schema.test.ts +54 -0
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
// 任务动态(#429)—— HTTP 集成测试(真实 Bun.serve,临时库;PG 梯子上用 COMMHUB_TEST_PG_URL 原样再跑一遍)。
|
|
2
|
+
// 写路径 —— 新建 / PATCH 的每个字段 / 勾子任务 / 标签改名 / 删项目 / 删卡,各记字段级流水:谁、旧值 → 新值
|
|
3
|
+
// 同一事务 —— 流水写不进去,那次改动也不生效
|
|
4
|
+
// 可见范围 —— 与列表相同:scoped 成员只看到看得见的卡(删掉的按墓碑);Agent 受限成员看不见的节点被隐去
|
|
5
|
+
// 翻页 —— limit / next_cursor / since / requirement_id;参数不合法 400;capability `events`
|
|
6
|
+
import { afterAll, beforeAll, describe, expect, test } from "bun:test";
|
|
7
|
+
import { mkdtempSync, rmSync } from "node:fs";
|
|
8
|
+
import { tmpdir } from "node:os";
|
|
9
|
+
import { join } from "node:path";
|
|
10
|
+
|
|
11
|
+
const DIR = mkdtempSync(join(tmpdir(), "anet-requirement-events-"));
|
|
12
|
+
process.env.COMMHUB_DB ||= join(DIR, "hub.db");
|
|
13
|
+
process.env.COMMHUB_UPLOADS_DIR = join(DIR, "uploads");
|
|
14
|
+
|
|
15
|
+
const PW = "EventsPassw0rd!x";
|
|
16
|
+
let BASE = "";
|
|
17
|
+
let hub: any = null;
|
|
18
|
+
let NET = "";
|
|
19
|
+
let admin = { token: "", id: "" };
|
|
20
|
+
let member = { token: "", id: "" };
|
|
21
|
+
let scoped = { token: "", id: "" };
|
|
22
|
+
let restricted = { token: "", id: "" };
|
|
23
|
+
let nodeToken = "";
|
|
24
|
+
let NODE = "";
|
|
25
|
+
|
|
26
|
+
type R = { status: number; body: any };
|
|
27
|
+
async function send(token: string, method: string, path: string, payload?: unknown): Promise<R> {
|
|
28
|
+
const res = await fetch(`${BASE}${path}`, {
|
|
29
|
+
method,
|
|
30
|
+
headers: { ...(token ? { Authorization: `Bearer ${token}` } : {}), "Content-Type": "application/json" },
|
|
31
|
+
body: payload === undefined ? undefined : JSON.stringify(payload),
|
|
32
|
+
});
|
|
33
|
+
const text = await res.text();
|
|
34
|
+
let body: any = null;
|
|
35
|
+
try { body = JSON.parse(text); } catch {}
|
|
36
|
+
return { status: res.status, body };
|
|
37
|
+
}
|
|
38
|
+
const create = async (t: string, card: Record<string, unknown>) => {
|
|
39
|
+
const r = await send(t, "POST", "/api/requirements", { network_id: NET, ...card });
|
|
40
|
+
expect(r.status).toBe(201);
|
|
41
|
+
return r.body.requirement as { id: string; seq: number };
|
|
42
|
+
};
|
|
43
|
+
const patch = (t: string, id: string, p: Record<string, unknown>) => send(t, "PATCH", `/api/requirements/${id}?network_id=${NET}`, p);
|
|
44
|
+
const events = (t: string, qs = "") => send(t, "GET", `/api/requirements/events?network_id=${NET}${qs}`);
|
|
45
|
+
const of = (list: any[], id: string) => list.filter(e => e.requirement_id === id);
|
|
46
|
+
const user = (id: string) => ({ kind: "user", id });
|
|
47
|
+
|
|
48
|
+
beforeAll(async () => {
|
|
49
|
+
process.env.HOST = "127.0.0.1";
|
|
50
|
+
const { register, createNetworkTokenForNode } = await import("./auth.js");
|
|
51
|
+
const { db } = await import("./db.js");
|
|
52
|
+
const a = register(`ev_admin_${Date.now()}`, PW, undefined, "Admin");
|
|
53
|
+
expect(a.ok).toBe(true);
|
|
54
|
+
admin = { token: a.token!, id: a.user!.user_id };
|
|
55
|
+
NET = a.network_id!;
|
|
56
|
+
db.run("UPDATE users SET role = 'admin' WHERE user_id = ?1", [admin.id]);
|
|
57
|
+
const mod: any = await import("./server.js");
|
|
58
|
+
hub = mod.bootServer({ port: 0, hostname: "127.0.0.1" });
|
|
59
|
+
BASE = `http://127.0.0.1:${hub.port}`;
|
|
60
|
+
const mk = async (username: string) => {
|
|
61
|
+
const r = await send(admin.token, "POST", "/api/admin/users", { username, password: PW, network_id: NET, role: "member" });
|
|
62
|
+
expect(r.status).toBe(200);
|
|
63
|
+
const login = await send("", "POST", "/api/auth/login", { username, password: PW });
|
|
64
|
+
expect(login.status).toBe(200);
|
|
65
|
+
return { token: login.body.token as string, id: login.body.user.user_id as string };
|
|
66
|
+
};
|
|
67
|
+
const stamp = Date.now();
|
|
68
|
+
member = await mk(`ev_member_${stamp}`);
|
|
69
|
+
scoped = await mk(`ev_scoped_${stamp}`);
|
|
70
|
+
restricted = await mk(`ev_restricted_${stamp}`);
|
|
71
|
+
db.run("UPDATE network_members SET task_access = 'all', agent_access = 'all' WHERE network_id = ?1 AND user_id = ?2", [NET, member.id]);
|
|
72
|
+
db.run("UPDATE network_members SET task_access = 'scoped' WHERE network_id = ?1 AND user_id = ?2", [NET, scoped.id]);
|
|
73
|
+
// 看全部任务,但一个 Agent 都没授权:所有节点对他隐去
|
|
74
|
+
db.run("UPDATE network_members SET task_access = 'all', agent_access = 'granted' WHERE network_id = ?1 AND user_id = ?2", [NET, restricted.id]);
|
|
75
|
+
NODE = `n_ev_${stamp}`;
|
|
76
|
+
const ntok = createNetworkTokenForNode(admin.id, NET, "ev-node");
|
|
77
|
+
expect(ntok.ok).toBe(true);
|
|
78
|
+
nodeToken = ntok.token!;
|
|
79
|
+
// Real legacy-client order: mint by name, then register; never fill owner.
|
|
80
|
+
const registration = await fetch(`${BASE}/mcp`, {
|
|
81
|
+
method: "POST",
|
|
82
|
+
headers: { Authorization: `Bearer ${nodeToken}`, "Content-Type": "application/json", Accept: "application/json, text/event-stream" },
|
|
83
|
+
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "report_status", arguments: {
|
|
84
|
+
resume_id: `ev-session-${stamp}`, alias: "ev-node", status: "idle", node_id: NODE,
|
|
85
|
+
} } }),
|
|
86
|
+
});
|
|
87
|
+
expect(registration.status).toBe(200);
|
|
88
|
+
await registration.text();
|
|
89
|
+
expect(db.get<{owner_user_id: string | null}>("SELECT owner_user_id FROM nodes WHERE node_id=?1", NODE)?.owner_user_id).toBeNull();
|
|
90
|
+
expect(db.get<{bound_node_id: string | null}>("SELECT bound_node_id FROM api_tokens WHERE token_id=?1", ntok.token_id!)?.bound_node_id).toBe(NODE);
|
|
91
|
+
}, 30_000);
|
|
92
|
+
|
|
93
|
+
afterAll(() => {
|
|
94
|
+
try { hub?.stop?.(true); } catch {}
|
|
95
|
+
try { rmSync(DIR, { recursive: true, force: true }); } catch {}
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
describe("requirement events", () => {
|
|
99
|
+
test("capability `events` is advertised", async () => {
|
|
100
|
+
const r = await send(admin.token, "GET", `/api/requirements?network_id=${NET}`);
|
|
101
|
+
expect(r.body.capabilities).toContain("events");
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
test("create records one `created` event with the actor, title and seq", async () => {
|
|
105
|
+
const card = await create(member.token, { name: "动态示例一" });
|
|
106
|
+
const r = await events(admin.token, `&requirement_id=${card.id}`);
|
|
107
|
+
expect(r.status).toBe(200);
|
|
108
|
+
expect(r.body.events.length).toBe(1);
|
|
109
|
+
const [e] = r.body.events;
|
|
110
|
+
expect(e).toMatchObject({ kind: "created", field: null, actor: user(member.id), title: "动态示例一", seq: card.seq, new: { title: "动态示例一", column: "pool" } });
|
|
111
|
+
expect(typeof e.id).toBe("string");
|
|
112
|
+
expect(Date.parse(e.at)).toBeGreaterThan(0);
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
test("a PATCH records one event per changed field, old → new; unchanged fields and no-op PATCHes record nothing", async () => {
|
|
116
|
+
const card = await create(admin.token, { name: "动态示例二", priority: "normal", tags: ["UI"] });
|
|
117
|
+
const r1 = await patch(member.token, card.id, {
|
|
118
|
+
column: "doing", priority: "high", due: "2026-10-03", name: "动态示例二(改)", tags: ["UI", "后端"],
|
|
119
|
+
agent_owner: { kind: "node", id: NODE }, participants: [user(admin.id)], assignee: "",
|
|
120
|
+
});
|
|
121
|
+
expect(r1.status).toBe(200);
|
|
122
|
+
const list = of((await events(admin.token)).body.events, card.id);
|
|
123
|
+
const byField = Object.fromEntries(list.filter((e: any) => e.kind === "changed").map((e: any) => [e.field, e]));
|
|
124
|
+
expect(Object.keys(byField).sort()).toEqual(["agent_owner", "column", "due", "participants", "priority", "tags", "title"]);
|
|
125
|
+
expect(byField.column).toMatchObject({ old: "pool", new: "doing", actor: user(member.id) });
|
|
126
|
+
expect(byField.priority).toMatchObject({ old: "normal", new: "high" });
|
|
127
|
+
expect(byField.due).toMatchObject({ old: null, new: "2026-10-03" });
|
|
128
|
+
expect(byField.title).toMatchObject({ old: "动态示例二", new: "动态示例二(改)" });
|
|
129
|
+
expect(byField.tags).toMatchObject({ old: ["UI"], new: ["UI", "后端"] });
|
|
130
|
+
expect(byField.agent_owner).toMatchObject({ old: null, new: { kind: "node", id: NODE } });
|
|
131
|
+
expect(byField.participants).toMatchObject({ old: [], new: [user(admin.id)] });
|
|
132
|
+
// every event of that PATCH carries the card's title after the change
|
|
133
|
+
expect(new Set(list.filter((e: any) => e.kind === "changed").map((e: any) => e.title))).toEqual(new Set(["动态示例二(改)"]));
|
|
134
|
+
const before = list.length;
|
|
135
|
+
expect((await patch(member.token, card.id, { priority: "high", column: "doing" })).status).toBe(200);
|
|
136
|
+
expect(of((await events(admin.token)).body.events, card.id).length).toBe(before);
|
|
137
|
+
// archive / unarchive, description (length only, never the text), move to done
|
|
138
|
+
await patch(member.token, card.id, { description: "一段描述" });
|
|
139
|
+
await patch(member.token, card.id, { column: "done" });
|
|
140
|
+
await patch(member.token, card.id, { archived: true });
|
|
141
|
+
const later = of((await events(admin.token)).body.events, card.id).slice(0, 3);
|
|
142
|
+
expect(later.map((e: any) => e.field)).toEqual(["archived", "column", "description"]);
|
|
143
|
+
expect(later[0]).toMatchObject({ old: false, new: true });
|
|
144
|
+
expect(later[1]).toMatchObject({ old: "doing", new: "done" });
|
|
145
|
+
expect(later[2]).toMatchObject({ old: { chars: 0 }, new: { chars: 4 } });
|
|
146
|
+
expect(JSON.stringify(later[2])).not.toContain("一段描述");
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
test("checklist: ticking an item is `checklist_item` (repeat is a no-op); adding items is `checklist`", async () => {
|
|
150
|
+
const card = await create(admin.token, { name: "动态示例三", checklist: [{ id: "a", text: "第一项" }, { id: "b", text: "第二项" }] });
|
|
151
|
+
const tick = (done: boolean) => send(member.token, "PATCH", `/api/requirements/${card.id}/checklist/a?network_id=${NET}`, { done });
|
|
152
|
+
expect((await tick(true)).status).toBe(200);
|
|
153
|
+
expect((await tick(true)).status).toBe(200);
|
|
154
|
+
let list = of((await events(admin.token)).body.events, card.id);
|
|
155
|
+
const ticks = list.filter((e: any) => e.field === "checklist_item");
|
|
156
|
+
expect(ticks.length).toBe(1);
|
|
157
|
+
expect(ticks[0]).toMatchObject({ old: { id: "a", text: "第一项", done: false }, new: { id: "a", text: "第一项", done: true }, actor: user(member.id) });
|
|
158
|
+
// a PATCH that only flips one item's done is also `checklist_item`
|
|
159
|
+
await patch(member.token, card.id, { checklist: [{ id: "a", text: "第一项", done: true }, { id: "b", text: "第二项", done: true }] });
|
|
160
|
+
await patch(member.token, card.id, { checklist: [{ id: "a", text: "第一项", done: true }, { id: "b", text: "第二项", done: true }, { id: "c", text: "第三项" }] });
|
|
161
|
+
list = of((await events(admin.token)).body.events, card.id);
|
|
162
|
+
expect(list[0]).toMatchObject({ field: "checklist", old: { total: 2, done: 2 }, new: { total: 3, done: 2 } });
|
|
163
|
+
expect(list[1]).toMatchObject({ field: "checklist_item", new: { id: "b", done: true } });
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
test("the actor of a node token is the node", async () => {
|
|
167
|
+
const card = await create(admin.token, { name: "动态示例四" });
|
|
168
|
+
expect((await patch(nodeToken, card.id, { column: "doing" })).status).toBe(200);
|
|
169
|
+
const [e] = of((await events(nodeToken)).body.events, card.id);
|
|
170
|
+
expect(e).toMatchObject({ field: "column", actor: { kind: "node", id: NODE } });
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
test("tag rename, project delete and card delete each record per-card events", async () => {
|
|
174
|
+
const p = await send(admin.token, "POST", `/api/requirements/projects?network_id=${NET}`, { name: `动态项目-${Date.now()}` });
|
|
175
|
+
expect(p.status).toBe(201);
|
|
176
|
+
const card = await create(admin.token, { name: "动态示例五", tags: ["旧标签"], project_id: p.body.project.id });
|
|
177
|
+
expect((await send(admin.token, "POST", `/api/requirements/tags/ops?network_id=${NET}`, { op: "rename", from: "旧标签", to: "新标签" })).status).toBe(200);
|
|
178
|
+
expect((await send(admin.token, "DELETE", `/api/requirements/projects/${p.body.project.id}?network_id=${NET}`)).status).toBe(200);
|
|
179
|
+
expect((await send(admin.token, "DELETE", `/api/requirements/${card.id}?network_id=${NET}`)).status).toBe(200);
|
|
180
|
+
const list = of((await events(admin.token)).body.events, card.id);
|
|
181
|
+
expect(list.slice(0, 3).map((e: any) => [e.kind, e.field])).toEqual([["deleted", null], ["changed", "project"], ["changed", "tags"]]);
|
|
182
|
+
expect(list[0]).toMatchObject({ title: "动态示例五", seq: expect.any(Number), actor: user(admin.id) });
|
|
183
|
+
expect(list[1]).toMatchObject({ old: p.body.project.id, new: null });
|
|
184
|
+
expect(list[2]).toMatchObject({ old: ["旧标签"], new: ["新标签"] });
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
test("the write and its events are one transaction: no events table → the PATCH fails and the card is unchanged", async () => {
|
|
188
|
+
const { db } = await import("./db.js");
|
|
189
|
+
const card = await create(admin.token, { name: "动态示例六", priority: "low" });
|
|
190
|
+
db.exec("ALTER TABLE requirement_events RENAME TO requirement_events_away");
|
|
191
|
+
try {
|
|
192
|
+
const r = await patch(admin.token, card.id, { priority: "high" });
|
|
193
|
+
expect(r.status).toBeGreaterThanOrEqual(500);
|
|
194
|
+
} finally {
|
|
195
|
+
db.exec("ALTER TABLE requirement_events_away RENAME TO requirement_events");
|
|
196
|
+
}
|
|
197
|
+
const now = await send(admin.token, "GET", `/api/requirements/${card.id}?network_id=${NET}`);
|
|
198
|
+
expect(now.body.requirement.priority).toBe("low");
|
|
199
|
+
});
|
|
200
|
+
|
|
201
|
+
test("a scoped member sees events only for cards they can see — deleted ones by their tombstone", async () => {
|
|
202
|
+
const mine = await create(scoped.token, { name: "动态示例七(scoped 自己建的)" });
|
|
203
|
+
const theirs = await create(admin.token, { name: "动态示例八(scoped 看不见)" });
|
|
204
|
+
const joined = await create(admin.token, { name: "动态示例九(scoped 是参与人)", participants: [user(scoped.id)] });
|
|
205
|
+
await patch(admin.token, mine.id, { priority: "high" });
|
|
206
|
+
await patch(admin.token, theirs.id, { priority: "high" });
|
|
207
|
+
await send(admin.token, "DELETE", `/api/requirements/${joined.id}?network_id=${NET}`);
|
|
208
|
+
const seen = (await events(scoped.token, "&limit=500")).body.events;
|
|
209
|
+
expect(of(seen, mine.id).length).toBe(2);
|
|
210
|
+
expect(of(seen, theirs.id).length).toBe(0);
|
|
211
|
+
expect(of(seen, joined.id).map((e: any) => e.kind)).toEqual(["deleted", "created"]);
|
|
212
|
+
// a filter on a card they cannot see answers like a card with no events
|
|
213
|
+
expect((await events(scoped.token, `&requirement_id=${theirs.id}`)).body.events).toEqual([]);
|
|
214
|
+
});
|
|
215
|
+
|
|
216
|
+
test("an agent-restricted member: hidden nodes are masked, and an event that only differs by a hidden node is dropped", async () => {
|
|
217
|
+
const card = await create(admin.token, { name: "动态示例十" });
|
|
218
|
+
await patch(nodeToken, card.id, { priority: "high" });
|
|
219
|
+
await patch(admin.token, card.id, { agent_owner: { kind: "node", id: NODE } });
|
|
220
|
+
await patch(admin.token, card.id, { participants: [user(admin.id), { kind: "node", id: NODE }] });
|
|
221
|
+
const seen = of((await events(restricted.token)).body.events, card.id);
|
|
222
|
+
const all = of((await events(admin.token)).body.events, card.id);
|
|
223
|
+
expect(all.map((e: any) => e.field)).toEqual(["participants", "agent_owner", "priority", null]);
|
|
224
|
+
expect(seen.map((e: any) => e.field)).toEqual(["participants", "priority", null]);
|
|
225
|
+
expect(seen[0]).toMatchObject({ old: [], new: [user(admin.id)] });
|
|
226
|
+
expect(seen[1]).toMatchObject({ field: "priority", actor: null });
|
|
227
|
+
expect(JSON.stringify(seen)).not.toContain(NODE);
|
|
228
|
+
});
|
|
229
|
+
|
|
230
|
+
test("paging: newest first, limit + next_cursor without overlap; since; bad params 400", async () => {
|
|
231
|
+
const card = await create(admin.token, { name: "动态示例十一" });
|
|
232
|
+
for (const priority of ["high", "low", "lowest", "normal"]) await patch(admin.token, card.id, { priority });
|
|
233
|
+
const q = `&requirement_id=${card.id}`;
|
|
234
|
+
const p1 = await events(admin.token, `${q}&limit=2`);
|
|
235
|
+
expect(p1.body.events.length).toBe(2);
|
|
236
|
+
expect(p1.body.has_more).toBe(true);
|
|
237
|
+
expect(p1.body.events[0].new).toBe("normal");
|
|
238
|
+
const p2 = await events(admin.token, `${q}&limit=2&cursor=${p1.body.next_cursor}`);
|
|
239
|
+
const p3 = await events(admin.token, `${q}&limit=2&cursor=${p2.body.next_cursor}`);
|
|
240
|
+
const ids = [...p1.body.events, ...p2.body.events, ...p3.body.events].map((e: any) => e.id);
|
|
241
|
+
expect(new Set(ids).size).toBe(5);
|
|
242
|
+
expect(p3.body.has_more).toBe(false);
|
|
243
|
+
expect(p3.body.next_cursor).toBe(null);
|
|
244
|
+
expect(ids.map(Number)).toEqual([...ids.map(Number)].sort((a, b) => b - a));
|
|
245
|
+
// since = server_time of an earlier read → only what came after
|
|
246
|
+
const t = p1.body.server_time;
|
|
247
|
+
await patch(admin.token, card.id, { priority: "high" });
|
|
248
|
+
const after = await events(admin.token, `${q}&since=${encodeURIComponent(t)}`);
|
|
249
|
+
// since is inclusive (>=): an event written in the same millisecond as server_time comes back again,
|
|
250
|
+
// and clients dedupe by id. Only the events not already seen must be exactly the new one.
|
|
251
|
+
expect(after.body.events.every((e: any) => Date.parse(e.at) >= Date.parse(t))).toBe(true);
|
|
252
|
+
const seen = new Set(ids);
|
|
253
|
+
expect(after.body.events.filter((e: any) => !seen.has(e.id)).map((e: any) => e.new)).toEqual(["high"]);
|
|
254
|
+
for (const bad of ["&limit=0", "&limit=501", "&limit=x", "&since=nope", "&cursor=abc", "&cursor=0"]) {
|
|
255
|
+
expect((await events(admin.token, bad)).status).toBe(400);
|
|
256
|
+
}
|
|
257
|
+
});
|
|
258
|
+
|
|
259
|
+
test("migration is idempotent and leaves the rows alone", async () => {
|
|
260
|
+
const { db } = await import("./db.js");
|
|
261
|
+
const { ensureRequirementEvents } = await import("./requirement-events.js");
|
|
262
|
+
const n = Number(db.get<{ n: number }>("SELECT COUNT(*) AS n FROM requirement_events")!.n);
|
|
263
|
+
ensureRequirementEvents(db);
|
|
264
|
+
ensureRequirementEvents(db);
|
|
265
|
+
expect(Number(db.get<{ n: number }>("SELECT COUNT(*) AS n FROM requirement_events")!.n)).toBe(n);
|
|
266
|
+
expect(n).toBeGreaterThan(0);
|
|
267
|
+
});
|
|
268
|
+
});
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
// diffRequirement 的边角(HTTP 层的写路径在 requirement-events-http.test.ts)。
|
|
2
|
+
import { describe, expect, test } from "bun:test";
|
|
3
|
+
import { diffRequirement, eventPublic, type EventCard } from "./requirement-events.js";
|
|
4
|
+
|
|
5
|
+
const base: EventCard = {
|
|
6
|
+
requirement_id: "req_1", network_id: "net_1", seq: 7, title: "示例", column_name: "pool", priority: "normal", due_on: null, start_on: null,
|
|
7
|
+
assignee: null, owner_json: null, agent_owner_json: null, participants_json: "[]", tags_json: "[]", checklist_json: "[]", description: null,
|
|
8
|
+
project_id: null, parent_id: null, archived: 0,
|
|
9
|
+
};
|
|
10
|
+
const ck = (items: { id: string; text: string; done?: boolean }[]) => JSON.stringify(items.map(i => ({ done: false, ...i })));
|
|
11
|
+
|
|
12
|
+
describe("diffRequirement", () => {
|
|
13
|
+
test("no change → no events; null vs empty string are the same", () => {
|
|
14
|
+
expect(diffRequirement(base, { ...base })).toEqual([]);
|
|
15
|
+
expect(diffRequirement(base, { ...base, due_on: "", assignee: "", description: "" })).toEqual([]);
|
|
16
|
+
});
|
|
17
|
+
test("created carries title and column only", () => {
|
|
18
|
+
expect(diffRequirement(null, base)).toEqual([{ kind: "created", field: null, old: null, new: { title: "示例", column: "pool" } }]);
|
|
19
|
+
});
|
|
20
|
+
test("checklist: reorder, rename, add or remove is one `checklist` event with counts", () => {
|
|
21
|
+
const a = { ...base, checklist_json: ck([{ id: "a", text: "一" }, { id: "b", text: "二", done: true }]) };
|
|
22
|
+
for (const next of [ck([{ id: "b", text: "二", done: true }, { id: "a", text: "一" }]), ck([{ id: "a", text: "一改" }, { id: "b", text: "二", done: true }]), ck([{ id: "a", text: "一" }])]) {
|
|
23
|
+
const out = diffRequirement(a, { ...a, checklist_json: next });
|
|
24
|
+
expect(out.length).toBe(1);
|
|
25
|
+
expect(out[0].field).toBe("checklist");
|
|
26
|
+
}
|
|
27
|
+
expect(diffRequirement(a, { ...a, checklist_json: ck([{ id: "a", text: "一" }]) })[0]).toMatchObject({ old: { total: 2, done: 1 }, new: { total: 1, done: 0 } });
|
|
28
|
+
});
|
|
29
|
+
test("checklist: two items ticked in one write are two `checklist_item` events", () => {
|
|
30
|
+
const a = { ...base, checklist_json: ck([{ id: "a", text: "一" }, { id: "b", text: "二" }]) };
|
|
31
|
+
const out = diffRequirement(a, { ...a, checklist_json: ck([{ id: "a", text: "一", done: true }, { id: "b", text: "二", done: true }]) });
|
|
32
|
+
expect(out.map(e => [e.field, (e.new as { id: string }).id])).toEqual([["checklist_item", "a"], ["checklist_item", "b"]]);
|
|
33
|
+
});
|
|
34
|
+
test("malformed stored JSON reads as empty rather than throwing", () => {
|
|
35
|
+
expect(() => diffRequirement({ ...base, tags_json: "{nope", participants_json: "x" }, base)).not.toThrow();
|
|
36
|
+
});
|
|
37
|
+
test("description records lengths, never text", () => {
|
|
38
|
+
const [e] = diffRequirement(base, { ...base, description: "secret text" });
|
|
39
|
+
expect(e).toEqual({ kind: "changed", field: "description", old: { chars: 0 }, new: { chars: 11 } });
|
|
40
|
+
});
|
|
41
|
+
test("eventPublic: bigint / string ids from PostgreSQL come out as strings, seq as a number", () => {
|
|
42
|
+
const row = { id: 12n as unknown as string, network_id: "n", requirement_id: "r", seq: "3", title: "t", actor_json: null, kind: "changed", field: "priority", old_json: "\"low\"", new_json: "\"high\"", created_at: "2026-10-01T00:00:00.000Z" };
|
|
43
|
+
expect(eventPublic(row)).toMatchObject({ id: "12", seq: 3, old: "low", new: "high", actor: null });
|
|
44
|
+
});
|
|
45
|
+
});
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
// 任务动态(#429,Vincent 2026-09-30「任务有新的状态…这完成了,这是有这种动态」)。
|
|
2
|
+
//
|
|
3
|
+
// requirements 表只存「现在是什么」和「最后是谁改的」(updated_by_json),改之前是什么没有任何地方留着 ——
|
|
4
|
+
// 「优先级 P2 → P0」「状态 需求池 → 进行中」画不出来。这里给每一次写入记字段级的流水:谁(用户 / 节点)、
|
|
5
|
+
// 什么时候、哪个字段、旧值 → 新值。写入点在 requirements.ts 的各条写路径里,和那次 UPDATE 在同一个事务里。
|
|
6
|
+
//
|
|
7
|
+
// 表只加不改:旧 Hub(回滚之后)不认识这张表,也不会碰它;再升回来接着记(回滚期间的改动没有流水)。
|
|
8
|
+
// 读:GET /api/requirements/events(requirements.ts,可见范围与列表相同),capability `events`。
|
|
9
|
+
import type { DbAdapter } from "./db-adapter.js";
|
|
10
|
+
|
|
11
|
+
/** 流水保留多久。更早的在写入时顺手清掉(每 PRUNE_EVERY 次写一次)。 */
|
|
12
|
+
export const EVENTS_RETENTION_MS = 180 * 86_400_000;
|
|
13
|
+
const PRUNE_EVERY = 500;
|
|
14
|
+
|
|
15
|
+
/** IF NOT EXISTS:重复执行无副作用;SQLite / PostgreSQL 同一段(适配层把 AUTOINCREMENT 译成 BIGSERIAL)。 */
|
|
16
|
+
export function ensureRequirementEvents(database: DbAdapter): void {
|
|
17
|
+
database.exec(`
|
|
18
|
+
CREATE TABLE IF NOT EXISTS requirement_events (
|
|
19
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
20
|
+
network_id TEXT NOT NULL,
|
|
21
|
+
requirement_id TEXT NOT NULL,
|
|
22
|
+
seq INTEGER,
|
|
23
|
+
title TEXT,
|
|
24
|
+
actor_json TEXT,
|
|
25
|
+
kind TEXT NOT NULL,
|
|
26
|
+
field TEXT,
|
|
27
|
+
old_json TEXT,
|
|
28
|
+
new_json TEXT,
|
|
29
|
+
created_at TEXT NOT NULL
|
|
30
|
+
);
|
|
31
|
+
`);
|
|
32
|
+
database.exec("CREATE INDEX IF NOT EXISTS idx_requirement_events_network ON requirement_events(network_id, id)");
|
|
33
|
+
database.exec("CREATE INDEX IF NOT EXISTS idx_requirement_events_card ON requirement_events(requirement_id, id)");
|
|
34
|
+
database.exec("CREATE INDEX IF NOT EXISTS idx_requirement_events_created ON requirement_events(created_at)");
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** 流水要比较的列(requirements.ts 的 Row 的子集)。 */
|
|
38
|
+
export type EventCard = {
|
|
39
|
+
requirement_id: string;
|
|
40
|
+
network_id: string;
|
|
41
|
+
seq: number | null;
|
|
42
|
+
title: string;
|
|
43
|
+
column_name: string;
|
|
44
|
+
priority: string;
|
|
45
|
+
due_on: string | null;
|
|
46
|
+
start_on: string | null;
|
|
47
|
+
assignee: string | null;
|
|
48
|
+
owner_json: string | null;
|
|
49
|
+
agent_owner_json: string | null;
|
|
50
|
+
participants_json: string | null;
|
|
51
|
+
tags_json: string | null;
|
|
52
|
+
checklist_json: string | null;
|
|
53
|
+
description: string | null;
|
|
54
|
+
project_id: string | null;
|
|
55
|
+
parent_id: string | null;
|
|
56
|
+
archived: number | null;
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
export type EventKind = "created" | "changed" | "deleted" | "comment";
|
|
60
|
+
/**
|
|
61
|
+
* field(kind = changed):column / title / priority / due / start / assignee / owner / agent_owner / participants /
|
|
62
|
+
* tags / checklist_item(勾选或取消一项:{id,text,done})/ checklist(增删改条目:{total,done})/
|
|
63
|
+
* description(只记字数,不存正文)/ project / parent / archived。
|
|
64
|
+
* kind = comment(#474):field 为 null,new = { text }(评论正文,≤ 4000 字),只追加,不对应任何字段的改动。
|
|
65
|
+
*/
|
|
66
|
+
export type EventDraft = { kind: EventKind; field: string | null; old: unknown; new: unknown };
|
|
67
|
+
|
|
68
|
+
const parse = (json: string | null | undefined): unknown => {
|
|
69
|
+
if (!json) return null;
|
|
70
|
+
try { return JSON.parse(json); } catch { return null; }
|
|
71
|
+
};
|
|
72
|
+
const list = (json: string | null | undefined): unknown[] => { const v = parse(json); return Array.isArray(v) ? v : []; };
|
|
73
|
+
const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b);
|
|
74
|
+
type Item = { id: string; text: string; done: boolean };
|
|
75
|
+
const items = (json: string | null | undefined): Item[] =>
|
|
76
|
+
list(json).filter((x): x is Item => !!x && typeof (x as Item).id === "string" && typeof (x as Item).text === "string").map(x => ({ id: x.id, text: x.text, done: !!x.done }));
|
|
77
|
+
const counts = (xs: Item[]) => ({ total: xs.length, done: xs.filter(x => x.done).length });
|
|
78
|
+
|
|
79
|
+
/** 一次写入前后的差异。before = null:新建(只记一条 created)。 */
|
|
80
|
+
export function diffRequirement(before: EventCard | null, after: EventCard): EventDraft[] {
|
|
81
|
+
if (!before) return [{ kind: "created", field: null, old: null, new: { title: after.title, column: after.column_name } }];
|
|
82
|
+
const out: EventDraft[] = [];
|
|
83
|
+
const scalar = (field: string, a: unknown, b: unknown) => { if (!same(a, b)) out.push({ kind: "changed", field, old: a, new: b }); };
|
|
84
|
+
scalar("column", before.column_name, after.column_name);
|
|
85
|
+
scalar("title", before.title, after.title);
|
|
86
|
+
scalar("priority", before.priority, after.priority);
|
|
87
|
+
scalar("due", before.due_on || null, after.due_on || null);
|
|
88
|
+
scalar("start", before.start_on || null, after.start_on || null);
|
|
89
|
+
scalar("assignee", before.assignee || null, after.assignee || null);
|
|
90
|
+
scalar("owner", parse(before.owner_json), parse(after.owner_json));
|
|
91
|
+
scalar("agent_owner", parse(before.agent_owner_json), parse(after.agent_owner_json));
|
|
92
|
+
scalar("participants", list(before.participants_json), list(after.participants_json));
|
|
93
|
+
scalar("tags", list(before.tags_json), list(after.tags_json));
|
|
94
|
+
// 子任务:同一条(同 id、同文字)只是勾选变了 = 一条 checklist_item;条目增删 / 改字 / 换顺序 = 一条 checklist。
|
|
95
|
+
const a = items(before.checklist_json), b = items(after.checklist_json);
|
|
96
|
+
const shape = (xs: Item[]) => xs.map(x => `${x.id}\u0000${x.text}`).join("\u0001");
|
|
97
|
+
if (shape(a) === shape(b)) {
|
|
98
|
+
for (let i = 0; i < b.length; i++) if (a[i].done !== b[i].done) out.push({ kind: "changed", field: "checklist_item", old: a[i], new: b[i] });
|
|
99
|
+
} else {
|
|
100
|
+
out.push({ kind: "changed", field: "checklist", old: counts(a), new: counts(b) });
|
|
101
|
+
}
|
|
102
|
+
if ((before.description || "") !== (after.description || "")) {
|
|
103
|
+
out.push({ kind: "changed", field: "description", old: { chars: (before.description || "").length }, new: { chars: (after.description || "").length } });
|
|
104
|
+
}
|
|
105
|
+
scalar("project", before.project_id || null, after.project_id || null);
|
|
106
|
+
scalar("parent", before.parent_id || null, after.parent_id || null);
|
|
107
|
+
scalar("archived", !!before.archived, !!after.archived);
|
|
108
|
+
return out;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
let writes = 0;
|
|
112
|
+
|
|
113
|
+
/** 记下一张卡的一组流水(调用方负责放进同一个事务)。actorJson = updated_by_json 的那个值。 */
|
|
114
|
+
export function recordRequirementEvents(database: DbAdapter, card: Pick<EventCard, "requirement_id" | "network_id" | "seq" | "title">, actorJson: string | null, drafts: readonly EventDraft[], at: string): void {
|
|
115
|
+
for (const d of drafts) {
|
|
116
|
+
database.run(
|
|
117
|
+
`INSERT INTO requirement_events (network_id, requirement_id, seq, title, actor_json, kind, field, old_json, new_json, created_at)
|
|
118
|
+
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)`,
|
|
119
|
+
[card.network_id, card.requirement_id, card.seq ?? null, card.title, actorJson && actorJson !== "null" ? actorJson : null, d.kind, d.field,
|
|
120
|
+
d.old === null || d.old === undefined ? null : JSON.stringify(d.old), d.new === null || d.new === undefined ? null : JSON.stringify(d.new), at],
|
|
121
|
+
);
|
|
122
|
+
writes++;
|
|
123
|
+
}
|
|
124
|
+
if (drafts.length && writes >= PRUNE_EVERY) {
|
|
125
|
+
writes = 0;
|
|
126
|
+
database.run("DELETE FROM requirement_events WHERE created_at < ?1", [new Date(Date.parse(at) - EVENTS_RETENTION_MS).toISOString()]);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export type EventRow = { id: number | string; network_id: string; requirement_id: string; seq: number | string | null; title: string | null; actor_json: string | null; kind: string; field: string | null; old_json: string | null; new_json: string | null; created_at: string };
|
|
131
|
+
|
|
132
|
+
/** 对外的一条(id 转成字符串:PostgreSQL 的 BIGSERIAL 可能回成字符串或 bigint,客户端一律按字符串比较 / 翻页)。 */
|
|
133
|
+
export const eventPublic = (row: EventRow) => ({
|
|
134
|
+
id: String(row.id),
|
|
135
|
+
requirement_id: row.requirement_id,
|
|
136
|
+
seq: row.seq == null ? null : Number(row.seq),
|
|
137
|
+
title: row.title,
|
|
138
|
+
actor: parse(row.actor_json),
|
|
139
|
+
kind: row.kind,
|
|
140
|
+
field: row.field,
|
|
141
|
+
old: parse(row.old_json),
|
|
142
|
+
new: parse(row.new_json),
|
|
143
|
+
at: row.created_at,
|
|
144
|
+
});
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
// 参与人改了任务 → 通知相关的人(Vincent 2026-10-01「参与人可以改,但是改了之后需要有个通知」)。
|
|
2
|
+
//
|
|
3
|
+
// 谁触发:操作者是人,且是这张卡的参与人、不是负责人(权限上参与人只能改状态和检查项,见 task-access.ts
|
|
4
|
+
// PARTICIPANT_EDIT_FIELDS;老成员 task_access='all' 的参与人改了也一样通知)。只说状态和检查项的变化,别的字段不进正文。
|
|
5
|
+
// 通知谁:负责人、创建者、其他参与人 —— 只要人类、去重、不含操作者本人。
|
|
6
|
+
// 怎么送:复用人与人私信(human-dm.ts,user_inbox kind=human_dm + /events/users/me 的 desktop_message),
|
|
7
|
+
// 发信人 = 操作者。App 已有的展示:顶部提示 + 人员列表未读 + 与他的私信会话。不新增渠道。
|
|
8
|
+
// 合并:同一 (收件人, 操作者, 卡) 在 COALESCE_WINDOW_MS 内的连续改动并进同一条还没读的私信(改写正文,不再弹)。
|
|
9
|
+
|
|
10
|
+
import { db, uuidv4 } from "./db.js";
|
|
11
|
+
import { isParticipant } from "./task-access.js";
|
|
12
|
+
import { rewriteUnreadNoticeDm, sendNoticeDm } from "./human-dm.js";
|
|
13
|
+
|
|
14
|
+
export const COALESCE_WINDOW_MS = 60_000;
|
|
15
|
+
const COLUMN_LABEL: Record<string, string> = { pool: "需求池", doing: "进行中", done: "完成", abandoned: "废弃" };
|
|
16
|
+
const MAX_LINES = 20;
|
|
17
|
+
const MAX_ITEM_CHARS = 40;
|
|
18
|
+
|
|
19
|
+
export type NoticeCard = {
|
|
20
|
+
requirement_id: string;
|
|
21
|
+
network_id: string;
|
|
22
|
+
seq: number | null;
|
|
23
|
+
title: string;
|
|
24
|
+
column_name: string;
|
|
25
|
+
checklist_json: string | null;
|
|
26
|
+
owner_json: string | null;
|
|
27
|
+
participants_json: string | null;
|
|
28
|
+
created_by: string | null;
|
|
29
|
+
created_by_json: string | null;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
type Item = { id: string; text: string; done: boolean };
|
|
33
|
+
const items = (raw: string | null): Item[] => {
|
|
34
|
+
try {
|
|
35
|
+
const list = raw ? JSON.parse(raw) : [];
|
|
36
|
+
return Array.isArray(list) ? list.filter((x) => x && typeof x.id === "string").map((x) => ({ id: x.id, text: String(x.text ?? ""), done: x.done === true })) : [];
|
|
37
|
+
} catch { return []; }
|
|
38
|
+
};
|
|
39
|
+
const clip = (s: string) => { const c = Array.from(s); return c.length > MAX_ITEM_CHARS ? c.slice(0, MAX_ITEM_CHARS).join("") + "…" : s; };
|
|
40
|
+
const parse = (raw: string | null) => { try { return raw ? JSON.parse(raw) : null; } catch { return null; } };
|
|
41
|
+
const userIdOf = (ref: unknown): string | null => {
|
|
42
|
+
const r = ref as { kind?: unknown; id?: unknown } | null;
|
|
43
|
+
return r && r.kind === "user" && typeof r.id === "string" ? r.id : null;
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* 这次改动里要说的那几件事,按「对象」做键:同一个对象后一次覆盖前一次(先勾再取消 = 只剩「取消勾选」)。
|
|
48
|
+
* 键:column / ck:<id>。值:一句短话(不带主语和卡名)。
|
|
49
|
+
*/
|
|
50
|
+
export function describeChanges(before: Pick<NoticeCard, "column_name" | "checklist_json">, after: Pick<NoticeCard, "column_name" | "checklist_json">): Array<[string, string]> {
|
|
51
|
+
const out: Array<[string, string]> = [];
|
|
52
|
+
if (before.column_name !== after.column_name) out.push(["column", `改为 ${COLUMN_LABEL[after.column_name] ?? after.column_name}`]);
|
|
53
|
+
const a = items(before.checklist_json), b = items(after.checklist_json);
|
|
54
|
+
const was = new Map(a.map((x) => [x.id, x]));
|
|
55
|
+
const now = new Map(b.map((x) => [x.id, x]));
|
|
56
|
+
for (const x of b) {
|
|
57
|
+
const old = was.get(x.id);
|
|
58
|
+
if (!old) { out.push([`ck:${x.id}`, `添加了检查项「${clip(x.text)}」`]); continue; }
|
|
59
|
+
if (old.text !== x.text) out.push([`ck:${x.id}`, `把检查项「${clip(old.text)}」改为「${clip(x.text)}」`]);
|
|
60
|
+
else if (old.done !== x.done) out.push([`ck:${x.id}`, `${x.done ? "勾选了" : "取消勾选了"}检查项「${clip(x.text)}」`]);
|
|
61
|
+
}
|
|
62
|
+
for (const x of a) if (!now.has(x.id)) out.push([`ck:${x.id}`, `删除了检查项「${clip(x.text)}」`]);
|
|
63
|
+
return out;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** 收件人:负责人、创建者、其他参与人(只要人,去重,去掉操作者)。 */
|
|
67
|
+
export function noticeRecipients(card: NoticeCard, actorUserId: string): string[] {
|
|
68
|
+
const ids = new Set<string>();
|
|
69
|
+
const owner = userIdOf(parse(card.owner_json));
|
|
70
|
+
if (owner) ids.add(owner);
|
|
71
|
+
const creator = userIdOf(parse(card.created_by_json)) ?? (!card.created_by_json && card.created_by ? card.created_by : null);
|
|
72
|
+
if (creator) ids.add(creator);
|
|
73
|
+
const participants = parse(card.participants_json);
|
|
74
|
+
if (Array.isArray(participants)) for (const p of participants) { const id = userIdOf(p); if (id) ids.add(id); }
|
|
75
|
+
ids.delete(actorUserId);
|
|
76
|
+
|
|
77
|
+
return [...ids];
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function noticeText(actorName: string, title: string, lines: readonly string[]): string {
|
|
81
|
+
if (lines.length === 1) {
|
|
82
|
+
const line = lines[0];
|
|
83
|
+
return line.startsWith("改为 ") ? `${actorName} 把「${title}」${line}` : `${actorName} 在「${title}」${line}`;
|
|
84
|
+
}
|
|
85
|
+
const shown = lines.slice(-MAX_LINES);
|
|
86
|
+
const more = lines.length > shown.length ? `\n…另有 ${lines.length - shown.length} 项` : "";
|
|
87
|
+
return `${actorName} 更新了「${title}」:\n${shown.map((l) => `· ${l}`).join("\n")}${more}`;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
type Pending = { messageId: string; startedAt: number; changes: Map<string, string> };
|
|
91
|
+
const pending = new Map<string, Pending>();
|
|
92
|
+
|
|
93
|
+
export function __resetRequirementNoticesForTest(): void { pending.clear(); }
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* 参与人(非负责人)改完一张卡之后调用(事务提交之后)。before / after = 改前改后的行。
|
|
97
|
+
* 不是参与人、或者状态和检查项都没变 → 什么都不发。返回这次通知到的收件人(测试用)。
|
|
98
|
+
*/
|
|
99
|
+
export function notifyParticipantChange(input: { before: NoticeCard; after: NoticeCard; actorUserId: string; now?: number }): string[] {
|
|
100
|
+
const { before, after, actorUserId } = input;
|
|
101
|
+
if (!isParticipant(before, actorUserId)) return [];
|
|
102
|
+
if (userIdOf(parse(before.owner_json)) === actorUserId) return [];
|
|
103
|
+
|
|
104
|
+
const changes = describeChanges(before, after);
|
|
105
|
+
if (!changes.length) return [];
|
|
106
|
+
const now = input.now ?? Date.now();
|
|
107
|
+
// 用户名从库里取:MCP 入口的 auth.username 是空串。
|
|
108
|
+
const user = db.get<{ username: string; display_name: string | null }>("SELECT username, display_name FROM users WHERE user_id = ?1", actorUserId);
|
|
109
|
+
if (!user) return [];
|
|
110
|
+
const actorName = user.display_name?.trim() || user.username;
|
|
111
|
+
const sender = { userId: actorUserId, username: user.username };
|
|
112
|
+
const sent: string[] = [];
|
|
113
|
+
for (const target of noticeRecipients(after, actorUserId)) {
|
|
114
|
+
const key = `${target}\u0000${actorUserId}\u0000${after.requirement_id}`;
|
|
115
|
+
const prev = pending.get(key);
|
|
116
|
+
const live = prev && now - prev.startedAt < COALESCE_WINDOW_MS ? prev : null;
|
|
117
|
+
const merged = new Map(live?.changes ?? []);
|
|
118
|
+
for (const [k, line] of changes) { merged.delete(k); merged.set(k, line); }
|
|
119
|
+
const meta = JSON.stringify({ task_notice: { requirement_id: after.requirement_id, seq: after.seq ?? null, network_id: after.network_id } });
|
|
120
|
+
const base = { networkId: after.network_id, targetUserId: target, sender, title: "任务更新", metaJson: meta };
|
|
121
|
+
if (live && rewriteUnreadNoticeDm({ ...base, messageId: live.messageId, text: noticeText(actorName, after.title, [...merged.values()]) })) {
|
|
122
|
+
live.changes = merged;
|
|
123
|
+
sent.push(target);
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
const messageId = `dm_task_${uuidv4()}`;
|
|
127
|
+
const fresh = new Map(changes);
|
|
128
|
+
if (!sendNoticeDm({ ...base, messageId, text: noticeText(actorName, after.title, [...fresh.values()]) })) continue;
|
|
129
|
+
pending.set(key, { messageId, startedAt: now, changes: fresh });
|
|
130
|
+
sent.push(target);
|
|
131
|
+
}
|
|
132
|
+
if (pending.size > 5_000) for (const [k, p] of pending) if (now - p.startedAt >= COALESCE_WINDOW_MS) pending.delete(k);
|
|
133
|
+
return sent;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* RFC-040 Q4:部门负责人(只凭负责人身份)删了本部门的一张卡 → 私信卡的负责人。
|
|
138
|
+
* 卡没有人类负责人时,私信负责 Agent 的主人(这张卡正是因为那个 Agent 才算「本部门的卡」)。
|
|
139
|
+
* 删的人就是收件人 / 收件人已不在网络 → 不发。返回收件人(测试用),没发 → null。
|
|
140
|
+
*/
|
|
141
|
+
export function notifyLeaderDeleted(input: { card: NoticeCard & { agent_owner_json?: string | null }; actorUserId: string }): string | null {
|
|
142
|
+
const { card, actorUserId } = input;
|
|
143
|
+
let target = userIdOf(parse(card.owner_json));
|
|
144
|
+
if (!target) {
|
|
145
|
+
const agent = parse(card.agent_owner_json ?? null) as { kind?: unknown; id?: unknown } | null;
|
|
146
|
+
if (agent?.kind === "node" && typeof agent.id === "string") {
|
|
147
|
+
target = db.get<{ owner_user_id: string | null }>("SELECT owner_user_id FROM nodes WHERE node_id = ?1 AND network_id = ?2", agent.id, card.network_id)?.owner_user_id ?? null;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
if (!target || target === actorUserId) return null;
|
|
151
|
+
const user = db.get<{ username: string; display_name: string | null }>("SELECT username, display_name FROM users WHERE user_id = ?1", actorUserId);
|
|
152
|
+
if (!user) return null;
|
|
153
|
+
const actorName = user.display_name?.trim() || user.username;
|
|
154
|
+
const number = card.seq ? ` #${card.seq}` : "";
|
|
155
|
+
const sent = sendNoticeDm({
|
|
156
|
+
networkId: card.network_id,
|
|
157
|
+
targetUserId: target,
|
|
158
|
+
sender: { userId: actorUserId, username: user.username },
|
|
159
|
+
title: "任务删除",
|
|
160
|
+
metaJson: JSON.stringify({ task_notice: { requirement_id: card.requirement_id, seq: card.seq ?? null, network_id: card.network_id, deleted: true } }),
|
|
161
|
+
messageId: `dm_task_${uuidv4()}`,
|
|
162
|
+
text: `${actorName}(部门负责人)删除了你负责的任务${number}「${card.title}」`,
|
|
163
|
+
});
|
|
164
|
+
return sent ? target : null;
|
|
165
|
+
}
|