@sleep2agi/commhub-server 0.9.0-preview.13 → 0.9.0-preview.130

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (317) hide show
  1. package/README.md +130 -10
  2. package/bin/commhub.ts +99 -11
  3. package/package.json +7 -7
  4. package/src/ack-create-request-transport.test.ts +182 -0
  5. package/src/ack-create-request.test.ts +50 -7
  6. package/src/admin-delete-network-http.test.ts +228 -0
  7. package/src/admin-networks-http.test.ts +88 -0
  8. package/src/adoption-candidates-http.test.ts +137 -0
  9. package/src/adoption-candidates.ts +158 -0
  10. package/src/agent-access-batch.test.ts +210 -0
  11. package/src/agent-access.ts +487 -0
  12. package/src/agent-acl-groups-http.test.ts +247 -0
  13. package/src/agent-acl-http.test.ts +659 -0
  14. package/src/agent-acl-slice3-http.test.ts +267 -0
  15. package/src/agent-groups-perf.test.ts +223 -0
  16. package/src/agent-notice.ts +48 -0
  17. package/src/agent-team-whoami-http.test.ts +98 -0
  18. package/src/agent-teams-http.test.ts +323 -0
  19. package/src/agent-teams.ts +244 -0
  20. package/src/alias-filter.test.ts +72 -0
  21. package/src/alias-filter.ts +42 -0
  22. package/src/api-host-supervisors-can-create-nodes.test.ts +350 -0
  23. package/src/api-host-supervisors-fallback.test.ts +271 -0
  24. package/src/api-host-supervisors-runtime-readiness.test.ts +195 -0
  25. package/src/api-nodes-shape.test.ts +26 -10
  26. package/src/auth-password-change-cli-tokens-http.test.ts +294 -0
  27. package/src/auth-sessions-http.test.ts +250 -0
  28. package/src/auth-validate.test.ts +5 -1
  29. package/src/auth-weak-password-login.test.ts +176 -0
  30. package/src/auth.ts +598 -49
  31. package/src/avatar-validate.test.ts +163 -0
  32. package/src/avatar-validate.ts +103 -0
  33. package/src/binding-generation-http.test.ts +121 -0
  34. package/src/blocked-exit-on-reply.test.ts +122 -0
  35. package/src/boot-side-effect.test.ts +124 -0
  36. package/src/clone-node.test.ts +248 -0
  37. package/src/clone-node.ts +289 -0
  38. package/src/codex-config-flags.ts +77 -0
  39. package/src/codex-fork-contract.ts +23 -0
  40. package/src/codex-fork-migration.test.ts +38 -0
  41. package/src/commhub-bin-args.test.ts +85 -0
  42. package/src/config-apply-sec1.test.ts +107 -0
  43. package/src/config-apply-validate.test.ts +134 -1
  44. package/src/config-apply-validate.ts +111 -5
  45. package/src/create-node-blocked-gate.test.ts +356 -0
  46. package/src/create-node-network-id.test.ts +79 -0
  47. package/src/create-node-tool-schema.test.ts +48 -0
  48. package/src/create-node-unicode-name.test.ts +120 -0
  49. package/src/create-node-validate.test.ts +193 -7
  50. package/src/create-node-validate.ts +227 -15
  51. package/src/create-node-workdir.test.ts +289 -0
  52. package/src/create-node.ts +77 -23
  53. package/src/daemon-provider-snapshots.test.ts +421 -0
  54. package/src/daemon-provider-snapshots.ts +327 -0
  55. package/src/daemon-token-owner-http.test.ts +236 -0
  56. package/src/dashboard-slash-routing-http.test.ts +107 -0
  57. package/src/db-adapter-guard.test.ts +148 -0
  58. package/src/db-adapter-translate.test.ts +128 -0
  59. package/src/db-adapter.ts +323 -87
  60. package/src/db-timestamp.test.ts +38 -0
  61. package/src/db-timestamp.ts +15 -0
  62. package/src/db.ts +930 -35
  63. package/src/delivered-without-push.test.ts +140 -0
  64. package/src/department-groups-http.test.ts +209 -0
  65. package/src/department-groups-sync-http.test.ts +328 -0
  66. package/src/department-groups.ts +434 -0
  67. package/src/department-heads-http.test.ts +330 -0
  68. package/src/department-heads.ts +226 -0
  69. package/src/departments-http.test.ts +185 -0
  70. package/src/departments.ts +260 -0
  71. package/src/desktop-message-seam.test.ts +150 -0
  72. package/src/desktop-message.test.ts +368 -0
  73. package/src/dm-file-scope-http.test.ts +178 -0
  74. package/src/ext-token-shared.test.ts +60 -0
  75. package/src/ext-validation-regression.test.ts +131 -0
  76. package/src/external-schedule-edits-http.test.ts +321 -0
  77. package/src/external-schedule-edits-timestamps.test.ts +64 -0
  78. package/src/external-schedule-edits.ts +327 -0
  79. package/src/file-download-authz-dev-open.test.ts +135 -0
  80. package/src/file-download-authz.test.ts +404 -0
  81. package/src/file-download-date-bucket.test.ts +436 -0
  82. package/src/file-network-scope-dev-open.test.ts +97 -0
  83. package/src/file-network-scope.test.ts +732 -0
  84. package/src/group-membership-events-http.test.ts +264 -0
  85. package/src/group-messages-http.test.ts +482 -0
  86. package/src/group-messages.ts +297 -0
  87. package/src/health-redaction.test.ts +642 -0
  88. package/src/http-gzip.test.ts +94 -0
  89. package/src/http-gzip.ts +112 -0
  90. package/src/hub-provider-config.test.ts +139 -0
  91. package/src/hub-provider-config.ts +105 -0
  92. package/src/hub-timestamp.test.ts +38 -0
  93. package/src/hub-timestamp.ts +27 -0
  94. package/src/human-dm.ts +215 -0
  95. package/src/inbox-caller.ts +49 -0
  96. package/src/inbox-count-sse.test.ts +310 -0
  97. package/src/inbox-count.ts +29 -0
  98. package/src/index.ts +15 -2362
  99. package/src/lifecycle-guard.ts +1 -1
  100. package/src/mcp-context-cost-http.test.ts +123 -0
  101. package/src/mcp-projects-events-http.test.ts +162 -0
  102. package/src/mcp-route-label-http.test.ts +120 -0
  103. package/src/mcp-write-network-resolution.test.ts +432 -0
  104. package/src/member-audit-network-id-http.test.ts +93 -0
  105. package/src/member-presence-http.test.ts +210 -0
  106. package/src/messages-ack-by-agent-http.test.ts +142 -0
  107. package/src/migrate-sqlite-to-pg.test.ts +47 -0
  108. package/src/migrate-sqlite-to-pg.ts +263 -0
  109. package/src/model-auth-notify-http.test.ts +181 -0
  110. package/src/model-auth-notify.ts +116 -0
  111. package/src/network-name-http.test.ts +75 -0
  112. package/src/network-scope.ts +276 -0
  113. package/src/network-token-membership-http.test.ts +139 -0
  114. package/src/node-alias-control.ts +12 -0
  115. package/src/node-attrs-validate.ts +88 -0
  116. package/src/node-attrs.test.ts +217 -0
  117. package/src/node-caller-identity-http.test.ts +781 -0
  118. package/src/node-create-request-status-http.test.ts +105 -0
  119. package/src/node-daemon-bindings.test.ts +132 -0
  120. package/src/node-daemon-bindings.ts +130 -0
  121. package/src/node-files-transport.test.ts +344 -0
  122. package/src/node-health-codex-login.test.ts +120 -0
  123. package/src/node-health-dispatch-http.test.ts +279 -0
  124. package/src/node-health-guard.ts +105 -0
  125. package/src/node-health-passthrough.test.ts +115 -0
  126. package/src/node-health-store.ts +101 -0
  127. package/src/node-id-alias.test.ts +190 -0
  128. package/src/node-identity-conflict-http.test.ts +269 -0
  129. package/src/node-identity-conflict.ts +142 -0
  130. package/src/node-identity-mismatch.test.ts +74 -0
  131. package/src/node-lifecycle-controllable.test.ts +64 -0
  132. package/src/node-lifecycle-controllable.ts +53 -0
  133. package/src/node-lifecycle-read-http.test.ts +245 -0
  134. package/src/node-lifecycle-read.ts +121 -0
  135. package/src/node-logs-transport.test.ts +263 -0
  136. package/src/node-permissions-http.test.ts +276 -0
  137. package/src/node-permissions.ts +285 -0
  138. package/src/node-request-retention.test.ts +281 -0
  139. package/src/node-request-retention.ts +120 -0
  140. package/src/node-skills-transport.test.ts +209 -0
  141. package/src/node-token-ownership.ts +51 -0
  142. package/src/node-token-privilege-http.test.ts +158 -0
  143. package/src/observer-avatar-http.test.ts +431 -0
  144. package/src/observer-push.test.ts +252 -0
  145. package/src/opencode-v2-catalog.test.ts +268 -0
  146. package/src/opencode-v2-catalog.ts +352 -0
  147. package/src/package-version-consistency.test.ts +25 -0
  148. package/src/peer-reply-atomic.test.ts +455 -0
  149. package/src/peer-reply-capability.test.ts +70 -0
  150. package/src/pg-worker.ts +87 -0
  151. package/src/project-dir-warn-clear-http.test.ts +132 -0
  152. package/src/project-viewer-can-http.test.ts +114 -0
  153. package/src/push.ts +429 -10
  154. package/src/redact-tokens.test.ts +65 -0
  155. package/src/redact-tokens.ts +40 -0
  156. package/src/rename.ts +22 -2
  157. package/src/reply-target-derivation.test.ts +96 -0
  158. package/src/report-status-handover-capabilities-http.test.ts +124 -0
  159. package/src/report-status-host-schema.test.ts +235 -0
  160. package/src/report-status-resume-id-handover.test.ts +150 -0
  161. package/src/require-explicit-test-db.ts +9 -0
  162. package/src/requirement-due-reminders-http.test.ts +620 -0
  163. package/src/requirement-due-reminders.ts +416 -0
  164. package/src/requirement-events-http.test.ts +268 -0
  165. package/src/requirement-events.test.ts +45 -0
  166. package/src/requirement-events.ts +144 -0
  167. package/src/requirement-notify.ts +165 -0
  168. package/src/requirement-participant-notify-http.test.ts +309 -0
  169. package/src/requirement-tag-ops-http.test.ts +266 -0
  170. package/src/requirement-tags.ts +89 -0
  171. package/src/requirements-abandoned-http.test.ts +236 -0
  172. package/src/requirements-comment-http.test.ts +167 -0
  173. package/src/requirements-completed-at-migration.test.ts +70 -0
  174. package/src/requirements-errors-mcp-http.test.ts +164 -0
  175. package/src/requirements-errors.ts +143 -0
  176. package/src/requirements-etag-http.test.ts +91 -0
  177. package/src/requirements-http.test.ts +709 -0
  178. package/src/requirements-last-event-http.test.ts +349 -0
  179. package/src/requirements-list-mcp-slim-http.test.ts +155 -0
  180. package/src/requirements-list-slim-http.test.ts +319 -0
  181. package/src/requirements-mcp.test.ts +163 -0
  182. package/src/requirements-migrate.ts +259 -0
  183. package/src/requirements-owner-strict-mcp-http.test.ts +145 -0
  184. package/src/requirements-people-http.test.ts +114 -0
  185. package/src/requirements-people-mcp-http.test.ts +225 -0
  186. package/src/requirements-people.ts +127 -0
  187. package/src/requirements-priority-lowest.test.ts +114 -0
  188. package/src/requirements-search-http.test.ts +182 -0
  189. package/src/requirements-search.test.ts +32 -0
  190. package/src/requirements-search.ts +145 -0
  191. package/src/requirements-seq-http.test.ts +193 -0
  192. package/src/requirements-seq-migration.test.ts +63 -0
  193. package/src/requirements-start-date.test.ts +125 -0
  194. package/src/requirements-stats-http.test.ts +288 -0
  195. package/src/requirements-stats.ts +167 -0
  196. package/src/requirements-status-participants-http.test.ts +222 -0
  197. package/src/requirements-upgrade-e2e.test.ts +126 -0
  198. package/src/requirements-upgrade-migration.test.ts +98 -0
  199. package/src/requirements.ts +1806 -0
  200. package/src/resolve-port.test.ts +57 -0
  201. package/src/resolve-port.ts +44 -0
  202. package/src/response-charset.test.ts +130 -0
  203. package/src/rest-explicit-columns-http.test.ts +222 -0
  204. package/src/rest-identity.test.ts +129 -0
  205. package/src/rest-identity.ts +125 -0
  206. package/src/rest-projections.ts +68 -0
  207. package/src/rest-write-network-resolution.test.ts +133 -0
  208. package/src/restricted-files.ts +76 -0
  209. package/src/retention.ts +15 -3
  210. package/src/route-callers-http.test.ts +120 -0
  211. package/src/route-timing.test.ts +211 -0
  212. package/src/route-timing.ts +258 -0
  213. package/src/rules-file-duplicate-alias.test.ts +234 -0
  214. package/src/rules-file-session-target.test.ts +207 -0
  215. package/src/rules-file-transport.test.ts +237 -0
  216. package/src/runtime-label.test.ts +22 -0
  217. package/src/runtime-label.ts +21 -0
  218. package/src/runtime-readiness.ts +90 -0
  219. package/src/schedule-agent-mcp-http.test.ts +381 -0
  220. package/src/schedule-agent.ts +192 -0
  221. package/src/scheduled-doorbell-nodeless-session.test.ts +134 -0
  222. package/src/scheduled-failures-http.test.ts +233 -0
  223. package/src/scheduled-failures.ts +179 -0
  224. package/src/scheduled-offline.test.ts +131 -0
  225. package/src/scheduled-offline.ts +66 -0
  226. package/src/scheduled-reply-unread-http.test.ts +212 -0
  227. package/src/scheduled-run-terminal.test.ts +268 -0
  228. package/src/scheduled-skip-blocking-task.test.ts +120 -0
  229. package/src/scheduled-stuck-http.test.ts +238 -0
  230. package/src/scheduled-stuck.ts +153 -0
  231. package/src/scheduled-tasks-http.test.ts +638 -0
  232. package/src/scheduled-tasks.ts +766 -0
  233. package/src/scoped-secrets.ts +124 -0
  234. package/src/send-dedup-request-id.test.ts +229 -0
  235. package/src/send-reply-agent-warning.test.ts +202 -0
  236. package/src/send-reply-alias-optional.test.ts +131 -0
  237. package/src/send-reply-attachments.test.ts +458 -0
  238. package/src/send_dedup.test.ts +54 -0
  239. package/src/send_dedup.ts +52 -6
  240. package/src/serve-error.test.ts +38 -0
  241. package/src/serve-error.ts +27 -0
  242. package/src/server.ts +5257 -0
  243. package/src/session-task-on-dispatch.ts +14 -0
  244. package/src/session-token-ownership-http.test.ts +122 -0
  245. package/src/shared/codex-inventory.ts +41 -0
  246. package/src/shared/daemon-provider-login.ts +31 -0
  247. package/src/shared/daemon-provider-snapshot.ts +52 -0
  248. package/src/shared/external-schedule-contract.ts +60 -0
  249. package/src/shared/node-name.test.ts +62 -0
  250. package/src/shared/node-name.ts +161 -0
  251. package/src/shared/provider-application.ts +29 -0
  252. package/src/shared/provider-collection.ts +14 -0
  253. package/src/shared/provider-initialization.ts +8 -0
  254. package/src/shared/reserved-env-drift.test.ts +10 -0
  255. package/src/shared/scoped-secret-contract.ts +5 -0
  256. package/src/shared/task-content-limit-drift.test.ts +28 -0
  257. package/src/shared/task-content-limit.ts +25 -0
  258. package/src/side-thread-command-transport.test.ts +312 -0
  259. package/src/side-thread-command-transport.ts +318 -0
  260. package/src/side-thread-http-integration.test.ts +233 -0
  261. package/src/side-thread-http.ts +504 -0
  262. package/src/side-thread-production.test.ts +72 -0
  263. package/src/side-thread-production.ts +118 -0
  264. package/src/side-thread.test.ts +1067 -0
  265. package/src/side-thread.ts +2499 -0
  266. package/src/skillhub-http.test.ts +108 -0
  267. package/src/sqlite-close-checkpoint.test.ts +78 -0
  268. package/src/start-node.test.ts +264 -0
  269. package/src/status-alias-filter-http.test.ts +106 -0
  270. package/src/status-alias-resolver-http.test.ts +163 -0
  271. package/src/status-alias-resolver.ts +19 -0
  272. package/src/status-node-id-filter-http.test.ts +161 -0
  273. package/src/status-read-cache-http.test.ts +229 -0
  274. package/src/status-read-cache.ts +122 -0
  275. package/src/stop-delete-node.test.ts +509 -1
  276. package/src/task-access-http.test.ts +402 -0
  277. package/src/task-access.ts +420 -0
  278. package/src/task-auth-origin-http.test.ts +91 -0
  279. package/src/task-auth-origin.test.ts +24 -0
  280. package/src/task-auth-origin.ts +7 -0
  281. package/src/task-consumption.test.ts +482 -0
  282. package/src/task-diagnostic-http.test.ts +149 -0
  283. package/src/task-diagnostic.test.ts +115 -0
  284. package/src/task-diagnostic.ts +118 -0
  285. package/src/task-expiry-notice-http.test.ts +287 -0
  286. package/src/task-expiry-notice.ts +315 -0
  287. package/src/task-idempotency-mcp.test.ts +142 -0
  288. package/src/task-idempotency.test.ts +60 -0
  289. package/src/task-idempotency.ts +75 -0
  290. package/src/task-late-replies.ts +54 -0
  291. package/src/task-late-reply-http.test.ts +152 -0
  292. package/src/task-lifecycle-watcher.test.ts +204 -0
  293. package/src/task-lifecycle-watcher.ts +49 -0
  294. package/src/task-network-resolution-http.test.ts +141 -0
  295. package/src/task-orphan-http.test.ts +287 -0
  296. package/src/task-orphan.ts +119 -0
  297. package/src/task-queue-ahead-http.test.ts +309 -0
  298. package/src/task-queue-ahead-scale.test.ts +236 -0
  299. package/src/task-queue-ahead.ts +186 -0
  300. package/src/task-rejection-log-http.test.ts +160 -0
  301. package/src/task-rejection-log.ts +49 -0
  302. package/src/task-stale-open-http.test.ts +290 -0
  303. package/src/task-stale-open.ts +103 -0
  304. package/src/tasks-pagination-http.test.ts +141 -0
  305. package/src/tool-audience-http.test.ts +220 -0
  306. package/src/tool-audience.ts +118 -0
  307. package/src/tools-list-json-schema.test.ts +67 -0
  308. package/src/tools.ts +3927 -323
  309. package/src/upload-early-reject-guard.test.ts +155 -0
  310. package/src/uploads-http.test.ts +97 -15
  311. package/src/uploads.ts +103 -6
  312. package/src/user-avatar-http.test.ts +74 -0
  313. package/src/user-avatar-migration.test.ts +25 -0
  314. package/src/user-inbox-by-agent-http.test.ts +161 -0
  315. package/src/user-inbox-netid-notnull.test.ts +122 -0
  316. package/src/user-inbox-read-http.test.ts +223 -0
  317. package/src/user-inbox-schema.test.ts +54 -0
@@ -0,0 +1,259 @@
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
+ /**
47
+ * 标签颜色(可选)。标签本身仍只是卡片 tags 数组里的字符串;这里只存「这个网络里这个名字用什么颜色」。
48
+ * 没有行 = 默认色。改名 / 合并 / 删除时跟着挪或删(见 requirements.ts 的标签管理)。IF NOT EXISTS:重复执行无副作用。
49
+ */
50
+ export function ensureNetworkTags(database: DbAdapter): void {
51
+ database.exec(`
52
+ CREATE TABLE IF NOT EXISTS network_tags (
53
+ network_id TEXT NOT NULL,
54
+ name TEXT NOT NULL,
55
+ color TEXT NOT NULL,
56
+ updated_at TEXT NOT NULL,
57
+ PRIMARY KEY (network_id, name)
58
+ );
59
+ `);
60
+ }
61
+
62
+ /**
63
+ * 删掉的卡留一条墓碑,给 GET /api/requirements?changes=1 报「这些 id 没了」(按 updated_since 增量同步的客户端
64
+ * 否则永远不知道一张卡被删了)。连同判断可见性要用的列一起存:受限成员只收到他本来看得见的卡的删除。
65
+ * 保留 30 天(requirements.ts TOMBSTONE_RETENTION_MS,写入时顺手清)。IF NOT EXISTS:重复执行无副作用。
66
+ */
67
+ export function ensureRequirementTombstones(database: DbAdapter): void {
68
+ database.exec(`
69
+ CREATE TABLE IF NOT EXISTS requirement_tombstones (
70
+ requirement_id TEXT PRIMARY KEY,
71
+ network_id TEXT NOT NULL,
72
+ deleted_at TEXT NOT NULL,
73
+ project_id TEXT,
74
+ owner_json TEXT,
75
+ participants_json TEXT,
76
+ created_by TEXT,
77
+ created_by_json TEXT
78
+ );
79
+ `);
80
+ database.exec("CREATE INDEX IF NOT EXISTS idx_requirement_tombstones_network ON requirement_tombstones(network_id, deleted_at)");
81
+ }
82
+
83
+ /** external_ref 在同一网络里唯一(只管有值的行)。IF NOT EXISTS:重复执行无副作用。 */
84
+ export function ensureRequirementIndexes(database: DbAdapter): void {
85
+ database.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_requirements_external_ref ON requirements(network_id, external_ref) WHERE external_ref IS NOT NULL");
86
+ database.exec("CREATE INDEX IF NOT EXISTS idx_requirements_network_updated ON requirements(network_id, updated_at)");
87
+ database.exec("CREATE INDEX IF NOT EXISTS idx_requirements_parent ON requirements(parent_id) WHERE parent_id IS NOT NULL");
88
+ }
89
+
90
+ /**
91
+ * 优先级加 lowest(P3 极低)。旧库建表时带 CHECK(priority IN ('high', 'normal', 'low')),SQLite 不能就地改
92
+ * CHECK,只能重建一次:拿 sqlite_master 里的原建表语句(含历次加的列)只换掉那个 CHECK,整表拷过去,
93
+ * 再按原样重建这张表的索引。已经放开的库什么都不做。存量值不改。
94
+ */
95
+ const OLD_PRIORITY_CHECK = /CHECK\s*\(\s*priority\s+IN\s*\(\s*'high'\s*,\s*'normal'\s*,\s*'low'\s*\)\s*\)/i;
96
+ export const PRIORITY_CHECK = "CHECK(priority IN ('high', 'normal', 'low', 'lowest'))";
97
+ export function migrateRequirementPriorityCheck(database: DbAdapter): { rebuilt: boolean } {
98
+ if (database.dialect === "postgres") {
99
+ try {
100
+ database.exec("ALTER TABLE requirements DROP CONSTRAINT IF EXISTS requirements_priority_check");
101
+ database.exec(`ALTER TABLE requirements ADD CONSTRAINT requirements_priority_check ${PRIORITY_CHECK}`);
102
+ } catch {}
103
+ return { rebuilt: false };
104
+ }
105
+ const table = database.get<{ sql: string }>("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'requirements'");
106
+ if (!table?.sql || !OLD_PRIORITY_CHECK.test(table.sql)) return { rebuilt: false };
107
+ const indexes = database.all<{ sql: string }>("SELECT sql FROM sqlite_master WHERE type = 'index' AND tbl_name = 'requirements' AND sql IS NOT NULL");
108
+ const createSql = table.sql
109
+ .replace(/^CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?["`]?requirements["`]?/i, "CREATE TABLE requirements_migrated")
110
+ .replace(OLD_PRIORITY_CHECK, PRIORITY_CHECK);
111
+ database.transaction(() => {
112
+ database.exec("DROP TABLE IF EXISTS requirements_migrated");
113
+ database.exec(createSql);
114
+ database.exec("INSERT INTO requirements_migrated SELECT * FROM requirements");
115
+ database.exec("DROP TABLE requirements");
116
+ database.exec("ALTER TABLE requirements_migrated RENAME TO requirements");
117
+ for (const index of indexes) database.exec(index.sql);
118
+ });
119
+ return { rebuilt: true };
120
+ }
121
+
122
+ /**
123
+ * 状态加 abandoned(废弃)。同 migrateRequirementPriorityCheck:旧库的 CHECK(column_name IN ('pool', 'doing', 'done'))
124
+ * SQLite 不能就地改,只重建一次;PostgreSQL 换掉默认名的列约束。已经放开的库什么都不做。存量值不改。
125
+ */
126
+ const OLD_COLUMN_CHECK = /CHECK\s*\(\s*column_name\s+IN\s*\(\s*'pool'\s*,\s*'doing'\s*,\s*'done'\s*\)\s*\)/i;
127
+ export const COLUMN_CHECK = "CHECK(column_name IN ('pool', 'doing', 'done', 'abandoned'))";
128
+ export function migrateRequirementColumnCheck(database: DbAdapter): { rebuilt: boolean } {
129
+ if (database.dialect === "postgres") {
130
+ // 只在约束还不认识 abandoned(或不存在)时动;一条 ALTER TABLE 里先删后加 = 一个语句,原子,
131
+ // 失败(比如存量里有不合法的值)整条回滚、旧约束原样留着,并且直接抛出 —— 不吞错,启动就该停下来。
132
+ const def = database.get<{ def: string }>(
133
+ "SELECT pg_get_constraintdef(c.oid) AS def FROM pg_constraint c JOIN pg_class t ON t.oid = c.conrelid WHERE t.relname = 'requirements' AND c.conname = 'requirements_column_name_check'",
134
+ )?.def ?? "";
135
+ if (def.includes("'abandoned'")) return { rebuilt: false };
136
+ database.exec(`ALTER TABLE requirements DROP CONSTRAINT IF EXISTS requirements_column_name_check, ADD CONSTRAINT requirements_column_name_check ${COLUMN_CHECK}`);
137
+ return { rebuilt: true };
138
+ }
139
+ const table = database.get<{ sql: string }>("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'requirements'");
140
+ if (!table?.sql || !OLD_COLUMN_CHECK.test(table.sql)) return { rebuilt: false };
141
+ const indexes = database.all<{ sql: string }>("SELECT sql FROM sqlite_master WHERE type = 'index' AND tbl_name = 'requirements' AND sql IS NOT NULL");
142
+ const createSql = table.sql
143
+ .replace(/^CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?["`]?requirements["`]?/i, "CREATE TABLE requirements_migrated")
144
+ .replace(OLD_COLUMN_CHECK, COLUMN_CHECK);
145
+ database.transaction(() => {
146
+ database.exec("DROP TABLE IF EXISTS requirements_migrated");
147
+ database.exec(createSql);
148
+ database.exec("INSERT INTO requirements_migrated SELECT * FROM requirements");
149
+ database.exec("DROP TABLE requirements");
150
+ database.exec("ALTER TABLE requirements_migrated RENAME TO requirements");
151
+ for (const index of indexes) database.exec(index.sql);
152
+ });
153
+ return { rebuilt: true };
154
+ }
155
+
156
+ /**
157
+ * 任务短号 seq:每个网络自己的 #1、#2…,界面显示和按 #N 查都用它。主键 requirement_id 不变。
158
+ * - 加可空列 seq;没有号的旧行按 created_at(再按 requirement_id)补号,接在该网络已有的最大号后面。
159
+ * - requirement_seq_counters 记每个网络发到过的最大号:删掉 / 归档的卡,号也不回收。
160
+ * - (network_id, seq) 唯一。重复执行只补还没号的行(回滚到旧 Hub 期间新建的卡)。
161
+ */
162
+ export function ensureRequirementSeq(database: DbAdapter): { backfilled: number } {
163
+ try { database.exec("ALTER TABLE requirements ADD COLUMN seq INTEGER"); } catch (e: any) { if (!/duplicate column|already exists/i.test(e?.message || "")) throw e; }
164
+ database.exec("CREATE TABLE IF NOT EXISTS requirement_seq_counters (network_id TEXT PRIMARY KEY, last_seq INTEGER NOT NULL DEFAULT 0)");
165
+ const pending = database.all<{ requirement_id: string; network_id: string; created_at: string | null }>(
166
+ "SELECT requirement_id, network_id, created_at FROM requirements WHERE seq IS NULL",
167
+ );
168
+ if (pending.length) {
169
+ // datetime('now') 的旧默认值「YYYY-MM-DD HH:MM:SS」是 UTC,和 ISO 混在一起时按字符串排会错位,换成毫秒再排。
170
+ const at = (v: string | null) => {
171
+ const s = v ?? "";
172
+ const ms = Date.parse(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(s) ? `${s.replace(" ", "T")}Z` : s);
173
+ return Number.isFinite(ms) ? ms : 0;
174
+ };
175
+ pending.sort((a, b) => a.network_id.localeCompare(b.network_id) || at(a.created_at) - at(b.created_at) || (a.requirement_id < b.requirement_id ? -1 : a.requirement_id > b.requirement_id ? 1 : 0));
176
+ database.transaction(() => {
177
+ const next = new Map<string, number>();
178
+ for (const row of pending) {
179
+ if (!next.has(row.network_id)) {
180
+ const max = database.get<{ m: number | null }>("SELECT MAX(seq) AS m FROM requirements WHERE network_id = ?1", row.network_id)?.m ?? 0;
181
+ const counter = database.get<{ last_seq: number }>("SELECT last_seq FROM requirement_seq_counters WHERE network_id = ?1", row.network_id)?.last_seq ?? 0;
182
+ next.set(row.network_id, Math.max(Number(max), Number(counter)));
183
+ }
184
+ const seq = next.get(row.network_id)! + 1;
185
+ next.set(row.network_id, seq);
186
+ database.run("UPDATE requirements SET seq = ?1 WHERE requirement_id = ?2 AND seq IS NULL", [seq, row.requirement_id]);
187
+ }
188
+ });
189
+ }
190
+ // 计数器不低于库里的最大号(补号之后、或计数器表是新建的)。
191
+ for (const row of database.all<{ network_id: string; m: number }>("SELECT network_id, MAX(seq) AS m FROM requirements WHERE seq IS NOT NULL GROUP BY network_id")) {
192
+ database.run(
193
+ `INSERT INTO requirement_seq_counters (network_id, last_seq) VALUES (?1, ?2)
194
+ ON CONFLICT(network_id) DO UPDATE SET last_seq = CASE WHEN excluded.last_seq > requirement_seq_counters.last_seq THEN excluded.last_seq ELSE requirement_seq_counters.last_seq END`,
195
+ [row.network_id, Number(row.m)],
196
+ );
197
+ }
198
+ database.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_requirements_network_seq ON requirements(network_id, seq) WHERE seq IS NOT NULL");
199
+ return { backfilled: pending.length };
200
+ }
201
+
202
+ /**
203
+ * 完成时间(仪表盘「今天 / 本周完成了多少」用)。三列只加不改:
204
+ * - completed_at:进入「完成」列的时刻(ISO,UTC)。移出「完成」列清空;在「完成」列里改别的字段不动它。
205
+ * - completed_by_json:谁把它移进「完成」的({kind,id},同 updated_by)。
206
+ * - completed_at_approx:1 = 这个时刻是补出来的近似值(见下),界面可以标「近似」。
207
+ * 补值:已经在「完成」列、还没有 completed_at 的卡,按 updated_at(没有就 created_at)补,approx = 1,completed_by 留空
208
+ * —— updated_at 是「最后一次改」,不是「完成那一刻」,只能当近似。旧库里 datetime('now') 的「YYYY-MM-DD HH:MM:SS」(UTC)
209
+ * 统一换成 ISO,按时间范围比较时不和 ISO 值错位。
210
+ * 每次启动都跑,重复执行只处理需要处理的行:回滚到旧 Hub 期间移进「完成」的卡补近似值,移出「完成」的卡清掉残留。
211
+ */
212
+ export function ensureRequirementCompletedAt(database: DbAdapter): { backfilled: number; cleared: number } {
213
+ for (const column of ["completed_at TEXT", "completed_by_json TEXT", "completed_at_approx INTEGER NOT NULL DEFAULT 0"]) {
214
+ try { database.exec(`ALTER TABLE requirements ADD COLUMN ${column}`); } catch (e: any) { if (!/duplicate column|already exists/i.test(e?.message || "")) throw e; }
215
+ }
216
+ const pending = database.all<{ requirement_id: string; updated_at: string | null; created_at: string | null }>(
217
+ "SELECT requirement_id, updated_at, created_at FROM requirements WHERE column_name = 'done' AND completed_at IS NULL",
218
+ );
219
+ const stale = database.all<{ requirement_id: string }>(
220
+ "SELECT requirement_id FROM requirements WHERE column_name <> 'done' AND (completed_at IS NOT NULL OR completed_by_json IS NOT NULL OR completed_at_approx <> 0)",
221
+ );
222
+ if (pending.length || stale.length) {
223
+ database.transaction(() => {
224
+ for (const row of pending) {
225
+ database.run(
226
+ "UPDATE requirements SET completed_at = ?1, completed_by_json = NULL, completed_at_approx = 1 WHERE requirement_id = ?2 AND completed_at IS NULL",
227
+ [isoInstant(row.updated_at) ?? isoInstant(row.created_at) ?? new Date().toISOString(), row.requirement_id],
228
+ );
229
+ }
230
+ for (const row of stale) {
231
+ database.run("UPDATE requirements SET completed_at = NULL, completed_by_json = NULL, completed_at_approx = 0 WHERE requirement_id = ?1", [row.requirement_id]);
232
+ }
233
+ });
234
+ }
235
+ database.exec("CREATE INDEX IF NOT EXISTS idx_requirements_network_completed ON requirements(network_id, completed_at) WHERE completed_at IS NOT NULL");
236
+ return { backfilled: pending.length, cleared: stale.length };
237
+ }
238
+
239
+ /** 库里的时间 → ISO(UTC)。认 ISO 和旧默认值「YYYY-MM-DD HH:MM:SS」(SQLite datetime('now'),UTC);读不懂 → null。 */
240
+ export function isoInstant(value: string | null | undefined): string | null {
241
+ const s = value ?? "";
242
+ const ms = Date.parse(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(s) ? `${s.replace(" ", "T")}Z` : s);
243
+ return Number.isFinite(ms) ? new Date(ms).toISOString() : null;
244
+ }
245
+
246
+ /**
247
+ * 给新卡领下一个号。调用方把它和 INSERT 放在同一个事务里:插入失败(client_id / external_ref 撞了)号也一起回滚。
248
+ * 一条语句完成「读 + 加一 + 写回」,两个并发的新建拿不到同一个号;(network_id, seq) 唯一索引兜底。
249
+ */
250
+ export function nextRequirementSeq(database: DbAdapter, networkId: string): number {
251
+ const row = database.get<{ last_seq: number }>(
252
+ `INSERT INTO requirement_seq_counters (network_id, last_seq)
253
+ VALUES (?1, COALESCE((SELECT MAX(seq) FROM requirements WHERE network_id = ?1), 0) + 1)
254
+ ON CONFLICT(network_id) DO UPDATE SET last_seq = requirement_seq_counters.last_seq + 1
255
+ RETURNING last_seq`,
256
+ networkId,
257
+ );
258
+ return Number(row!.last_seq);
259
+ }
@@ -0,0 +1,145 @@
1
+ // #470(MCP 任务生命周期测试报告问题 1)—— Agent 经 MCP 把负责人设成节点:以前走旧 App 的兼容改写,
2
+ // 人类负责人被静默清空、负责 Agent 被换掉,响应还显示 owner=节点。现在:
3
+ // - MCP 上 owner 传节点(建 / 改 / upsert,节点令牌和用户令牌都一样)→ 400 owner_must_be_human + hint,什么都不写;
4
+ // - MCP 写入的响应就是落库的那一行(和紧接着的 requirements_get 一字不差);
5
+ // - REST 上旧 App ≤ 0.2.142 的兼容路径不变(requirements-http.test.ts「old-app compat」那条钉着)。
6
+ import { describe, expect, test, beforeAll, afterAll } from "bun:test";
7
+ import { mkdtempSync, rmSync } from "fs";
8
+ import { join } from "path";
9
+ import { tmpdir } from "os";
10
+ import { register, createNetworkTokenForNode } from "./auth.js";
11
+ import { db } from "./db.js";
12
+
13
+ const DIR = mkdtempSync(join(tmpdir(), "anet-owner-strict-mcp-"));
14
+ let BASE = "";
15
+ let hub: any = null;
16
+ const PW = "OwnerStrictMcpPassw0rd!x";
17
+ let NET = "", ownerToken = "", ownerId = "", nodeToken = "";
18
+ const human = () => ({ kind: "user", id: ownerId });
19
+ const nodeA = { kind: "node", id: "node_strict_a" };
20
+ const nodeB = { kind: "node", id: "node_strict_b" };
21
+
22
+ async function rest(token: string, method: string, path: string, body?: unknown) {
23
+ const res = await fetch(`${BASE}${path}`, { method, headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });
24
+ const text = await res.text();
25
+ let json: any = null;
26
+ try { json = JSON.parse(text); } catch {}
27
+ return { status: res.status, body: json };
28
+ }
29
+ async function mcp(token: string, name: string, args: Record<string, unknown>): Promise<any> {
30
+ const res = await fetch(`${BASE}/mcp`, {
31
+ method: "POST",
32
+ headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json", Accept: "application/json, text/event-stream", "MCP-Protocol-Version": "2025-03-26" },
33
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } }),
34
+ });
35
+ const raw = await res.text();
36
+ const lines = raw.split("\n").filter(x => x.startsWith("data:"));
37
+ const out = lines.length ? JSON.parse(lines.at(-1)!.slice(5).trim()) : JSON.parse(raw);
38
+ return JSON.parse(out.result.content[0].text);
39
+ }
40
+ const stored = (id: string) => db.get<{ owner_json: string | null; agent_owner_json: string | null }>("SELECT owner_json, agent_owner_json FROM requirements WHERE requirement_id = ?1", id)!;
41
+
42
+ beforeAll(async () => {
43
+ process.env.COMMHUB_DB ||= join(DIR, "hub.db");
44
+ process.env.COMMHUB_UPLOADS_DIR = join(DIR, "uploads");
45
+ process.env.HOST = "127.0.0.1";
46
+ const a = register(`strict_owner_${Date.now()}`, PW, undefined, "Owner");
47
+ ownerToken = a.token!; ownerId = a.user!.user_id; NET = a.network_id!;
48
+ nodeToken = createNetworkTokenForNode(ownerId, NET, "strict-a", "node_strict_a").token!;
49
+ createNetworkTokenForNode(ownerId, NET, "strict-b", "node_strict_b");
50
+ const mod: any = await import("./server.js");
51
+ hub = mod.bootServer({ port: 0, hostname: "127.0.0.1" });
52
+ BASE = `http://127.0.0.1:${hub.port}`;
53
+ }, 30_000);
54
+
55
+ afterAll(() => {
56
+ try { hub?.stop?.(true); } catch {}
57
+ try { rmSync(DIR, { recursive: true, force: true }); } catch {}
58
+ });
59
+
60
+ describe("MCP: owner must be a person", () => {
61
+ test("update owner=node → 400 owner_must_be_human + hint; the human owner and the agent owner are untouched", async () => {
62
+ const card = (await mcp(nodeToken, "requirements_create", { name: "负责人保护", owner: human(), agent_owner: nodeB })).requirement;
63
+ expect(card.owner).toEqual(human());
64
+ const r = await mcp(nodeToken, "requirements_update", { id: card.id, owner: nodeA });
65
+ expect(r.ok).toBe(false);
66
+ expect(r.error).toBe("owner_must_be_human");
67
+ expect(r.status).toBe(400);
68
+ expect(r.hint).toContain("agent_owner");
69
+ expect(r.owner_coerced_to_agent_owner).toBeUndefined();
70
+ const row = stored(card.id);
71
+ expect(JSON.parse(row.owner_json!)).toEqual(human());
72
+ expect(JSON.parse(row.agent_owner_json!)).toEqual(nodeB);
73
+ const got = (await mcp(nodeToken, "requirements_get", { id: card.id })).requirement;
74
+ expect(got.owner).toEqual(human());
75
+ expect(got.agent_owner).toEqual(nodeB);
76
+ });
77
+
78
+ test("…the same for a user token over MCP, for create (nothing is written) and for upsert", async () => {
79
+ const r = await mcp(ownerToken, "requirements_update", { network_id: NET, id: (await mcp(ownerToken, "requirements_create", { network_id: NET, name: "用户令牌", owner: human() })).requirement.id, owner: nodeA });
80
+ expect(r.error).toBe("owner_must_be_human");
81
+ const before = db.get<{ n: number }>("SELECT COUNT(*) AS n FROM requirements WHERE network_id = ?1", NET)!.n;
82
+ const c = await mcp(nodeToken, "requirements_create", { name: "建时就传节点", owner: nodeA });
83
+ expect(c.error).toBe("owner_must_be_human");
84
+ expect(c.hint).toContain("agent_owner");
85
+ expect(db.get<{ n: number }>("SELECT COUNT(*) AS n FROM requirements WHERE network_id = ?1", NET)!.n).toBe(before);
86
+ const u = await mcp(nodeToken, "requirements_upsert_by_external_ref", { external_ref: "github:example/repo#470", name: "upsert", owner: nodeA });
87
+ expect(u.error).toBe("owner_must_be_human");
88
+ expect(db.get("SELECT 1 FROM requirements WHERE external_ref = 'github:example/repo#470'")).toBeNull();
89
+ });
90
+
91
+ test("the right way still works: agent_owner = node, owner = person, owner = null", async () => {
92
+ const card = (await mcp(nodeToken, "requirements_create", { name: "正确的写法", owner: human() })).requirement;
93
+ const r = await mcp(nodeToken, "requirements_update", { id: card.id, agent_owner: nodeA });
94
+ expect(r.ok).toBe(true);
95
+ expect(r.requirement.owner).toEqual(human());
96
+ expect(r.requirement.agent_owner).toEqual(nodeA);
97
+ const cleared = await mcp(nodeToken, "requirements_update", { id: card.id, owner: null });
98
+ expect(cleared.requirement.owner).toBeNull();
99
+ // agent_owner given a person is refused the other way round, with its own hint.
100
+ const wrong = await mcp(nodeToken, "requirements_update", { id: card.id, agent_owner: human() });
101
+ expect(wrong.error).toBe("agent_owner_must_be_agent");
102
+ expect(wrong.hint).toContain("owner");
103
+ });
104
+
105
+ test("every MCP write's response equals a fresh requirements_get", async () => {
106
+ const card = (await mcp(nodeToken, "requirements_create", { name: "响应即落库", owner: human(), checklist: [{ text: "一" }] })).requirement;
107
+ expect((await mcp(nodeToken, "requirements_get", { id: card.id })).requirement).toEqual(card);
108
+ const patches: Record<string, unknown>[] = [
109
+ { column: "doing" }, { agent_owner: nodeA }, { participants: [nodeB, human()] }, { owner: null }, { owner: human(), priority: "high" },
110
+ { agent_owner: null }, { due: "2026-10-10" }, { archived: true }, { archived: false },
111
+ ];
112
+ for (const p of patches) {
113
+ const r = await mcp(nodeToken, "requirements_update", { id: card.id, ...p });
114
+ expect(r.ok).toBe(true);
115
+ expect(r.owner_coerced_to_agent_owner).toBeUndefined();
116
+ expect(r.requirement).toEqual((await mcp(nodeToken, "requirements_get", { id: card.id })).requirement);
117
+ }
118
+ });
119
+ });
120
+
121
+ describe("REST", () => {
122
+ test("new clients' responses equal a fresh GET (the old-app compat echo is the only exception, pinned in requirements-http.test.ts)", async () => {
123
+ const card = (await rest(ownerToken, "POST", "/api/requirements", { network_id: NET, name: "REST 响应", owner: human() })).body.requirement;
124
+ for (const p of [{ agent_owner: nodeA }, { owner: human(), agent_owner: nodeB }, { participants: [nodeA] }]) {
125
+ const r = await rest(ownerToken, "PATCH", `/api/requirements/${card.id}`, p);
126
+ expect(r.status).toBe(200);
127
+ expect(r.body.requirement).toEqual((await rest(ownerToken, "GET", `/api/requirements/${card.id}`)).body.requirement);
128
+ }
129
+ // A new client (sends agent_owner) passing a node as owner: still strict, now with the hint.
130
+ const strict = await rest(ownerToken, "PATCH", `/api/requirements/${card.id}`, { owner: nodeA, agent_owner: nodeB });
131
+ expect(strict.status).toBe(400);
132
+ expect(strict.body.error).toBe("owner_must_be_human");
133
+ expect(strict.body.hint).toContain("agent_owner");
134
+ });
135
+
136
+ test("old-app compat on REST is unchanged: owner=node without agent_owner is still coerced (200 + flag)", async () => {
137
+ const card = (await rest(ownerToken, "POST", "/api/requirements", { network_id: NET, name: "旧 App", owner: human() })).body.requirement;
138
+ const old = await rest(ownerToken, "PATCH", `/api/requirements/${card.id}`, { owner: nodeA });
139
+ expect(old.status).toBe(200);
140
+ expect(old.body.owner_coerced_to_agent_owner).toBe(true);
141
+ const row = stored(card.id);
142
+ expect(row.owner_json).toBeNull();
143
+ expect(JSON.parse(row.agent_owner_json!)).toEqual(nodeA);
144
+ });
145
+ });
@@ -0,0 +1,114 @@
1
+ // GET /api/requirements/people 的 display_name 字段 —— HTTP 集成测试(真实 Bun.serve,私有端口,临时库)。
2
+ // test2123 在真实 PostgreSQL 上原样再跑一遍(COMMHUB_TEST_PG_URL)。
3
+ //
4
+ // name 保持原样:成员 = display_name,没设回落到用户名;节点 = display_name → alias → node_name(旧 app 只读它)。
5
+ // display_name 另给一份,没设就是 "" —— 分享图等对外场景据此不把 admin 之类的账号名印出去。
6
+ // 成员的 display_name 等于用户名也返回 "":register() 没给显示名时存的就是 username。
7
+
8
+ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
9
+ import { mkdtempSync, rmSync } from "node:fs";
10
+ import { tmpdir } from "node:os";
11
+ import { join } from "node:path";
12
+
13
+ const DIR = mkdtempSync(join(tmpdir(), "anet-req-people-"));
14
+ process.env.COMMHUB_DB ||= join(DIR, "hub.db");
15
+ process.env.COMMHUB_UPLOADS_DIR = join(DIR, "uploads");
16
+ process.env.HOST = "127.0.0.1";
17
+ const PW = "ReqPeoplePassw0rd!x";
18
+
19
+ let BASE = "";
20
+ let hub: any = null;
21
+ let NET = "";
22
+ let owner = { token: "", id: "", username: "" };
23
+ let named = { id: "" };
24
+ let plain = { id: "", username: "" };
25
+ let same = { id: "", username: "" };
26
+
27
+ async function people(token: string) {
28
+ const res = await fetch(`${BASE}/api/requirements/people?network_id=${NET}`, { headers: { Authorization: `Bearer ${token}` } });
29
+ return { status: res.status, body: await res.json() as any };
30
+ }
31
+
32
+ beforeAll(async () => {
33
+ const { db } = await import("./db.js");
34
+ const { addNetworkMember, register } = await import("./auth.js");
35
+ const stamp = Date.now();
36
+ const o = register(`rp_owner_${stamp}`, PW, undefined, "");
37
+ expect(o.ok).toBe(true);
38
+ owner = { token: o.token!, id: o.user!.user_id, username: o.user!.username };
39
+ NET = o.network_id!;
40
+ const m = register(`rp_member_${stamp}`, PW, undefined, "");
41
+ expect(m.ok).toBe(true);
42
+ named = { id: m.user!.user_id };
43
+ addNetworkMember(NET, named.id, "member", owner.id, { taskAccess: "all" });
44
+ // owner:没有显示名(= 只有用户名);member:有显示名。
45
+ db.run("UPDATE users SET display_name = NULL WHERE user_id = ?1", [owner.id]);
46
+ db.run("UPDATE users SET display_name = ?1 WHERE user_id = ?2", ["Placeholder Person", named.id]);
47
+ // plain:注册时没给显示名 —— register() 存的是 display_name = username,不改。
48
+ const pl = register(`rp_plain_${stamp}`, PW);
49
+ expect(pl.ok).toBe(true);
50
+ plain = { id: pl.user!.user_id, username: pl.user!.username };
51
+ addNetworkMember(NET, plain.id, "member", owner.id, { taskAccess: "all" });
52
+ // same:显示名被显式设成和用户名一模一样。
53
+ const sm = register(`rp_same_${stamp}`, PW, undefined, "Placeholder Other");
54
+ expect(sm.ok).toBe(true);
55
+ same = { id: sm.user!.user_id, username: sm.user!.username };
56
+ addNetworkMember(NET, same.id, "member", owner.id, { taskAccess: "all" });
57
+ db.run("UPDATE users SET display_name = username WHERE user_id = ?1", [same.id]);
58
+ db.run("INSERT INTO nodes(node_id,node_name,alias,display_name,network_id) VALUES (?1,?2,?3,?4,?5)", ["rp-node-alias", "rp-node-name", "placeholder-alias", "", NET]);
59
+ db.run("INSERT INTO nodes(node_id,node_name,alias,display_name,network_id) VALUES (?1,?2,?3,?4,?5)", ["rp-node-named", "rp-node-name-2", "placeholder-alias-2", "Placeholder Agent", NET]);
60
+ db.run("INSERT INTO nodes(node_id,node_name,network_id) VALUES (?1,?2,?3)", ["rp-node-bare", "rp-node-bare-name", NET]);
61
+ const mod: any = await import("./server.js");
62
+ hub = mod.bootServer({ port: 0, hostname: "127.0.0.1" });
63
+ BASE = `http://127.0.0.1:${hub.port}`;
64
+ }, 30_000);
65
+
66
+ afterAll(() => {
67
+ try { hub?.stop?.(true); } catch {}
68
+ try { rmSync(DIR, { recursive: true, force: true }); } catch {}
69
+ });
70
+
71
+ describe("GET /api/requirements/people display_name", () => {
72
+ test("display_name is its own field, empty when unset; name keeps the username / alias fallback", async () => {
73
+ const r = await people(owner.token);
74
+ expect(r.status).toBe(200);
75
+ const find = (kind: string, id: string) => r.body.people.find((p: any) => p.kind === kind && p.id === id);
76
+ expect(find("user", owner.id)).toMatchObject({ name: owner.username, display_name: "", networkId: NET });
77
+ expect(find("user", named.id)).toMatchObject({ name: "Placeholder Person", display_name: "Placeholder Person" });
78
+ expect(find("node", "rp-node-alias")).toMatchObject({ name: "placeholder-alias", display_name: "" });
79
+ expect(find("node", "rp-node-named")).toMatchObject({ name: "Placeholder Agent", display_name: "Placeholder Agent" });
80
+ expect(find("node", "rp-node-bare")).toMatchObject({ name: "rp-node-bare-name", display_name: "" });
81
+ expect(r.body.people.every((p: any) => typeof p.display_name === "string")).toBe(true);
82
+ });
83
+
84
+ test("a member whose display_name is just the username gets display_name \"\" (name still the username)", async () => {
85
+ const { db } = await import("./db.js");
86
+ // 前提是真的:register() 没给显示名时存的就是用户名。
87
+ expect(db.get<{ display_name: string }>("SELECT display_name FROM users WHERE user_id = ?1", plain.id)!.display_name).toBe(plain.username);
88
+ const r = await people(owner.token);
89
+ const find = (id: string) => r.body.people.find((p: any) => p.kind === "user" && p.id === id);
90
+ expect(find(plain.id)).toMatchObject({ name: plain.username, display_name: "" });
91
+ expect(find(same.id)).toMatchObject({ name: same.username, display_name: "" });
92
+ // 显示名只是「包含」用户名、不等于它:照常返回。
93
+ db.run("UPDATE users SET display_name = ?1 WHERE user_id = ?2", [`${same.username} (placeholder)`, same.id]);
94
+ const r2 = await people(owner.token);
95
+ expect(r2.body.people.find((p: any) => p.kind === "user" && p.id === same.id)).toMatchObject({ display_name: `${same.username} (placeholder)` });
96
+ db.run("UPDATE users SET display_name = username WHERE user_id = ?1", [same.id]);
97
+ });
98
+
99
+ test("sort order is still by name, then id", async () => {
100
+ const r = await people(owner.token);
101
+ const users = r.body.people.filter((p: any) => p.kind === "user");
102
+ const sorted = [...users].sort((a: any, b: any) => (a.name < b.name ? -1 : a.name > b.name ? 1 : a.id < b.id ? -1 : 1));
103
+ expect(users.map((p: any) => p.id)).toEqual(sorted.map((p: any) => p.id));
104
+ });
105
+
106
+ test("the existing fields keep their shape for old apps", async () => {
107
+ const r = await people(owner.token);
108
+ for (const p of r.body.people) {
109
+ expect(Object.keys(p).sort()).toEqual(["display_name", "id", "kind", "name", "networkId"]);
110
+ expect(typeof p.name).toBe("string");
111
+ expect(p.name.length).toBeGreaterThan(0);
112
+ }
113
+ });
114
+ });