@sleep2agi/commhub-server 0.9.0-preview.25 → 0.9.0-preview.250

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 (417) hide show
  1. package/README.md +129 -9
  2. package/bin/commhub.ts +93 -9
  3. package/build-info.json +7 -0
  4. package/package.json +10 -8
  5. package/src/ack-create-request-transport.test.ts +182 -0
  6. package/src/ack-create-request.test.ts +52 -8
  7. package/src/admin-delete-network-http.test.ts +228 -0
  8. package/src/admin-networks-http.test.ts +88 -0
  9. package/src/adoption-candidates-http.test.ts +140 -0
  10. package/src/adoption-candidates.ts +158 -0
  11. package/src/agent-access-batch.test.ts +210 -0
  12. package/src/agent-access.ts +487 -0
  13. package/src/agent-acl-groups-http.test.ts +247 -0
  14. package/src/agent-acl-http.test.ts +675 -0
  15. package/src/agent-acl-slice3-http.test.ts +717 -0
  16. package/src/agent-department-http.test.ts +215 -0
  17. package/src/agent-groups-perf.test.ts +223 -0
  18. package/src/agent-notice.ts +48 -0
  19. package/src/agent-team-whoami-http.test.ts +98 -0
  20. package/src/agent-teams-http.test.ts +330 -0
  21. package/src/agent-teams.ts +244 -0
  22. package/src/alias-baseline-2571.test.ts +162 -0
  23. package/src/alias-baseline.ts +113 -0
  24. package/src/alias-filter.test.ts +72 -0
  25. package/src/alias-filter.ts +42 -0
  26. package/src/api-host-supervisors-can-create-nodes.test.ts +350 -0
  27. package/src/api-host-supervisors-fallback.test.ts +6 -7
  28. package/src/api-host-supervisors-runtime-readiness.test.ts +195 -0
  29. package/src/api-nodes-shape.test.ts +95 -4
  30. package/src/auth-password-change-cli-tokens-http.test.ts +423 -0
  31. package/src/auth-sessions-http.test.ts +260 -0
  32. package/src/auth-validate.test.ts +5 -1
  33. package/src/auth-weak-password-login.test.ts +176 -0
  34. package/src/auth.ts +609 -51
  35. package/src/avatar-validate.test.ts +52 -2
  36. package/src/avatar-validate.ts +35 -1
  37. package/src/backfill-node-ids-2664.test.ts +128 -0
  38. package/src/binding-generation-http.test.ts +132 -0
  39. package/src/blocked-exit-on-reply.test.ts +122 -0
  40. package/src/broadcast-fanout-2721.test.ts +149 -0
  41. package/src/broadcast-fanout.ts +117 -0
  42. package/src/build-info.test.ts +60 -0
  43. package/src/build-info.ts +85 -0
  44. package/src/chain-attempt-dedup.test.ts +447 -0
  45. package/src/clip.test.ts +36 -0
  46. package/src/clip.ts +48 -0
  47. package/src/clone-node.test.ts +262 -0
  48. package/src/clone-node.ts +289 -0
  49. package/src/codex-config-flags.ts +77 -0
  50. package/src/codex-fork-contract.ts +23 -0
  51. package/src/codex-fork-migration.test.ts +38 -0
  52. package/src/commhub-bin-args.test.ts +85 -0
  53. package/src/config-apply-validate.test.ts +188 -1
  54. package/src/config-apply-validate.ts +222 -3
  55. package/src/cors-origins.test.ts +73 -0
  56. package/src/create-node-blocked-gate.test.ts +356 -0
  57. package/src/create-node-network-id.test.ts +91 -0
  58. package/src/create-node-tool-schema.test.ts +49 -0
  59. package/src/create-node-unicode-name.test.ts +126 -0
  60. package/src/create-node-validate.test.ts +199 -7
  61. package/src/create-node-validate.ts +232 -15
  62. package/src/create-node-workdir.test.ts +298 -0
  63. package/src/create-node.ts +88 -23
  64. package/src/daemon-provider-snapshots.test.ts +445 -0
  65. package/src/daemon-provider-snapshots.ts +327 -0
  66. package/src/daemon-token-owner-http.test.ts +292 -0
  67. package/src/dashboard-slash-routing-http.test.ts +109 -0
  68. package/src/db-adapter-guard.test.ts +148 -0
  69. package/src/db-adapter-translate.test.ts +128 -0
  70. package/src/db-adapter.ts +377 -91
  71. package/src/db-timestamp.test.ts +38 -0
  72. package/src/db-timestamp.ts +15 -0
  73. package/src/db.ts +1264 -153
  74. package/src/delivered-without-push.test.ts +140 -0
  75. package/src/department-groups-http.test.ts +209 -0
  76. package/src/department-groups-sync-http.test.ts +328 -0
  77. package/src/department-groups.ts +434 -0
  78. package/src/department-heads-http.test.ts +350 -0
  79. package/src/department-heads.ts +226 -0
  80. package/src/departments-agent-count.test.ts +132 -0
  81. package/src/departments-http.test.ts +185 -0
  82. package/src/departments-mcp.test.ts +128 -0
  83. package/src/departments.ts +318 -0
  84. package/src/desktop-message-seam.test.ts +150 -0
  85. package/src/desktop-message.test.ts +368 -0
  86. package/src/dm-file-scope-http.test.ts +178 -0
  87. package/src/empty-node-sweeper.test.ts +104 -0
  88. package/src/empty-node-sweeper.ts +88 -0
  89. package/src/env-transport-gate-http.test.ts +240 -0
  90. package/src/env-transport-gate.ts +80 -0
  91. package/src/env-transport-policy.ts +56 -0
  92. package/src/etag-of.test.ts +57 -0
  93. package/src/event-loop-lag.test.ts +180 -0
  94. package/src/event-loop-lag.ts +201 -0
  95. package/src/expiry-counters.test.ts +111 -0
  96. package/src/expiry-counters.ts +93 -0
  97. package/src/ext-token-shared.test.ts +60 -0
  98. package/src/ext-validation-regression.test.ts +131 -0
  99. package/src/external-schedule-edits-http.test.ts +321 -0
  100. package/src/external-schedule-edits-timestamps.test.ts +64 -0
  101. package/src/external-schedule-edits.ts +327 -0
  102. package/src/file-download-authz-dev-open.test.ts +1 -1
  103. package/src/file-download-authz.test.ts +73 -18
  104. package/src/file-download-date-bucket.test.ts +8 -26
  105. package/src/file-network-scope-dev-open.test.ts +97 -0
  106. package/src/file-network-scope.test.ts +732 -0
  107. package/src/group-membership-events-http.test.ts +264 -0
  108. package/src/group-messages-http.test.ts +483 -0
  109. package/src/group-messages.ts +297 -0
  110. package/src/health-anon-readers.ts +60 -0
  111. package/src/health-host-disk-2756.test.ts +71 -0
  112. package/src/health-redaction.test.ts +1541 -7
  113. package/src/host-supervisor-identity-http.test.ts +152 -0
  114. package/src/host-supervisor-identity.ts +92 -0
  115. package/src/host-supervisors-daemon-version.test.ts +137 -0
  116. package/src/http-gzip.test.ts +94 -0
  117. package/src/http-gzip.ts +112 -0
  118. package/src/hub-catalog-read-http.test.ts +641 -0
  119. package/src/hub-provider-config.test.ts +166 -0
  120. package/src/hub-provider-config.ts +202 -0
  121. package/src/hub-timestamp.test.ts +38 -0
  122. package/src/hub-timestamp.ts +27 -0
  123. package/src/human-dm.ts +215 -0
  124. package/src/human-inbox.ts +42 -0
  125. package/src/inbox-caller.ts +49 -0
  126. package/src/inbox-count-sse.test.ts +310 -0
  127. package/src/inbox-count.ts +29 -0
  128. package/src/index.ts +6 -2
  129. package/src/license-state.test.ts +56 -0
  130. package/src/license-state.ts +48 -0
  131. package/src/list-host-supervisors.test.ts +15 -4
  132. package/src/mcp-context-cost-http.test.ts +127 -0
  133. package/src/mcp-inflight.test.ts +92 -0
  134. package/src/mcp-inflight.ts +38 -0
  135. package/src/mcp-projects-events-http.test.ts +165 -0
  136. package/src/mcp-route-label-http.test.ts +120 -0
  137. package/src/mcp-write-network-resolution.test.ts +435 -0
  138. package/src/member-audit-network-id-http.test.ts +93 -0
  139. package/src/member-presence-http.test.ts +210 -0
  140. package/src/messages-ack-by-agent-http.test.ts +142 -0
  141. package/src/migrate-sqlite-to-pg.test.ts +47 -0
  142. package/src/migrate-sqlite-to-pg.ts +263 -0
  143. package/src/model-auth-notify-http.test.ts +181 -0
  144. package/src/model-auth-notify.ts +116 -0
  145. package/src/network-name-http.test.ts +75 -0
  146. package/src/network-rules-http.test.ts +169 -0
  147. package/src/network-rules.ts +129 -0
  148. package/src/network-scope.ts +276 -0
  149. package/src/network-token-membership-http.test.ts +186 -0
  150. package/src/node-alias-control.ts +12 -0
  151. package/src/node-attrs.test.ts +47 -2
  152. package/src/node-caller-identity-http.test.ts +1108 -0
  153. package/src/node-create-request-status-http.test.ts +105 -0
  154. package/src/node-daemon-bindings.test.ts +132 -0
  155. package/src/node-daemon-bindings.ts +135 -0
  156. package/src/node-failure-alert.test.ts +150 -0
  157. package/src/node-failure-alert.ts +177 -0
  158. package/src/node-files-transport.test.ts +347 -0
  159. package/src/node-health-codex-login.test.ts +120 -0
  160. package/src/node-health-dispatch-http.test.ts +373 -0
  161. package/src/node-health-guard.ts +121 -0
  162. package/src/node-health-passthrough.test.ts +115 -0
  163. package/src/node-health-store.ts +101 -0
  164. package/src/node-id-alias.test.ts +190 -0
  165. package/src/node-identity-conflict-http.test.ts +269 -0
  166. package/src/node-identity-conflict.ts +142 -0
  167. package/src/node-identity-mismatch.test.ts +74 -0
  168. package/src/node-in-flight-tasks.ts +31 -0
  169. package/src/node-lifecycle-controllable.test.ts +64 -0
  170. package/src/node-lifecycle-controllable.ts +53 -0
  171. package/src/node-lifecycle-read-http.test.ts +257 -0
  172. package/src/node-lifecycle-read.ts +124 -0
  173. package/src/node-logs-transport.test.ts +263 -0
  174. package/src/node-peer-allowlist.test.ts +114 -0
  175. package/src/node-permissions-http.test.ts +728 -0
  176. package/src/node-permissions.ts +494 -0
  177. package/src/node-request-retention.test.ts +281 -0
  178. package/src/node-request-retention.ts +120 -0
  179. package/src/node-secret-rest-http.test.ts +190 -0
  180. package/src/node-serviceability.test.ts +86 -0
  181. package/src/node-serviceability.ts +124 -0
  182. package/src/node-session-control-http.test.ts +310 -0
  183. package/src/node-session-control.ts +258 -0
  184. package/src/node-skills-transport.test.ts +212 -0
  185. package/src/node-token-identity.ts +35 -0
  186. package/src/node-token-ownership.ts +51 -0
  187. package/src/node-token-privilege-http.test.ts +158 -0
  188. package/src/not-found-api-http.test.ts +67 -0
  189. package/src/observer-avatar-http.test.ts +102 -9
  190. package/src/observer-push.test.ts +76 -0
  191. package/src/opencode-catalog-report-http.test.ts +139 -0
  192. package/src/opencode-v2-catalog.test.ts +268 -0
  193. package/src/opencode-v2-catalog.ts +356 -0
  194. package/src/package-version-consistency.test.ts +25 -0
  195. package/src/parent-source-marker.test.ts +50 -0
  196. package/src/password-network-tokens.ts +25 -0
  197. package/src/peer-reply-atomic.test.ts +462 -0
  198. package/src/peer-reply-capability.test.ts +70 -0
  199. package/src/pg-worker.ts +87 -0
  200. package/src/poll-pacing.test.ts +74 -0
  201. package/src/poll-pacing.ts +123 -0
  202. package/src/project-dir-warn-clear-http.test.ts +132 -0
  203. package/src/project-viewer-can-http.test.ts +116 -0
  204. package/src/provider-tools-shape.test.ts +150 -0
  205. package/src/push.test.ts +20 -10
  206. package/src/push.ts +373 -9
  207. package/src/redact-tokens.test.ts +86 -0
  208. package/src/redact-tokens.ts +43 -0
  209. package/src/rejection-counters.test.ts +72 -0
  210. package/src/rejection-counters.ts +173 -0
  211. package/src/rename.ts +38 -10
  212. package/src/reply-target-derivation.test.ts +96 -0
  213. package/src/report-status-handover-capabilities-http.test.ts +124 -0
  214. package/src/report-status-host-schema.test.ts +235 -0
  215. package/src/report-status-resume-id-handover.test.ts +184 -0
  216. package/src/report-status-secret-keys.test.ts +140 -0
  217. package/src/require-explicit-test-db.ts +9 -0
  218. package/src/requirement-due-reminders-http.test.ts +620 -0
  219. package/src/requirement-due-reminders.ts +416 -0
  220. package/src/requirement-events-http.test.ts +318 -0
  221. package/src/requirement-events.test.ts +45 -0
  222. package/src/requirement-events.ts +144 -0
  223. package/src/requirement-notify.ts +165 -0
  224. package/src/requirement-participant-notify-http.test.ts +309 -0
  225. package/src/requirement-tag-ops-http.test.ts +454 -0
  226. package/src/requirement-tag-tree-http.test.ts +275 -0
  227. package/src/requirement-tag-tree.ts +127 -0
  228. package/src/requirement-tags.ts +102 -0
  229. package/src/requirements-abandoned-http.test.ts +236 -0
  230. package/src/requirements-assignee-drift.test.ts +154 -0
  231. package/src/requirements-comment-http.test.ts +174 -0
  232. package/src/requirements-completed-at-migration.test.ts +70 -0
  233. package/src/requirements-errors-mcp-http.test.ts +164 -0
  234. package/src/requirements-errors.ts +158 -0
  235. package/src/requirements-etag-http.test.ts +91 -0
  236. package/src/requirements-http.test.ts +709 -0
  237. package/src/requirements-last-event-http.test.ts +349 -0
  238. package/src/requirements-list-mcp-slim-http.test.ts +155 -0
  239. package/src/requirements-list-slim-http.test.ts +324 -0
  240. package/src/requirements-mcp.test.ts +164 -0
  241. package/src/requirements-migrate.ts +283 -0
  242. package/src/requirements-owner-strict-mcp-http.test.ts +145 -0
  243. package/src/requirements-people-http.test.ts +114 -0
  244. package/src/requirements-people-mcp-http.test.ts +231 -0
  245. package/src/requirements-people.ts +196 -0
  246. package/src/requirements-priority-lowest.test.ts +114 -0
  247. package/src/requirements-projects-network-echo.test.ts +57 -0
  248. package/src/requirements-projects-parent-http.test.ts +123 -0
  249. package/src/requirements-search-http.test.ts +182 -0
  250. package/src/requirements-search.test.ts +32 -0
  251. package/src/requirements-search.ts +145 -0
  252. package/src/requirements-seq-http.test.ts +193 -0
  253. package/src/requirements-seq-migration.test.ts +63 -0
  254. package/src/requirements-start-date.test.ts +125 -0
  255. package/src/requirements-stats-http.test.ts +357 -0
  256. package/src/requirements-stats.ts +195 -0
  257. package/src/requirements-status-participants-http.test.ts +222 -0
  258. package/src/requirements-upgrade-e2e.test.ts +126 -0
  259. package/src/requirements-upgrade-migration.test.ts +98 -0
  260. package/src/requirements.ts +2205 -0
  261. package/src/resolve-port.test.ts +57 -0
  262. package/src/resolve-port.ts +44 -0
  263. package/src/rest-alias-network-fallback-http.test.ts +123 -0
  264. package/src/rest-alias-network-fallback.test.ts +60 -0
  265. package/src/rest-alias-network-fallback.ts +65 -0
  266. package/src/rest-explicit-columns-http.test.ts +266 -0
  267. package/src/rest-identity.test.ts +130 -0
  268. package/src/rest-identity.ts +141 -0
  269. package/src/rest-projections.ts +72 -0
  270. package/src/rest-read-network-real-chain.test.ts +97 -0
  271. package/src/rest-write-network-resolution.test.ts +133 -0
  272. package/src/restart-readiness-http.test.ts +121 -0
  273. package/src/restricted-files.ts +76 -0
  274. package/src/retention-first-sweep-quiet.test.ts +31 -0
  275. package/src/retention.test.ts +100 -40
  276. package/src/retention.ts +423 -104
  277. package/src/route-callers-http.test.ts +120 -0
  278. package/src/route-timing.test.ts +218 -0
  279. package/src/route-timing.ts +262 -0
  280. package/src/rules-file-duplicate-alias.test.ts +234 -0
  281. package/src/rules-file-session-target.test.ts +207 -0
  282. package/src/rules-file-transport.test.ts +237 -0
  283. package/src/runtime-label.test.ts +22 -0
  284. package/src/runtime-label.ts +21 -0
  285. package/src/runtime-readiness.ts +90 -0
  286. package/src/schedule-agent-mcp-http.test.ts +475 -0
  287. package/src/schedule-agent.ts +252 -0
  288. package/src/schedule-starved.test.ts +92 -0
  289. package/src/schedule-starved.ts +114 -0
  290. package/src/scheduled-backoff-http.test.ts +203 -0
  291. package/src/scheduled-backoff.ts +64 -0
  292. package/src/scheduled-doorbell-nodeless-session.test.ts +134 -0
  293. package/src/scheduled-failure-backoff-2622.test.ts +145 -0
  294. package/src/scheduled-failure-code.test.ts +73 -0
  295. package/src/scheduled-failure-code.ts +105 -0
  296. package/src/scheduled-failures-http.test.ts +279 -0
  297. package/src/scheduled-failures.ts +425 -0
  298. package/src/scheduled-noprogress-backoff-2622.test.ts +163 -0
  299. package/src/scheduled-offline-backoff-probe.test.ts +56 -0
  300. package/src/scheduled-offline.test.ts +131 -0
  301. package/src/scheduled-offline.ts +66 -0
  302. package/src/scheduled-outcome-guidance-http.test.ts +139 -0
  303. package/src/scheduled-outcome-guidance.ts +9 -0
  304. package/src/scheduled-reply-unread-http.test.ts +212 -0
  305. package/src/scheduled-requirement-wake-http.test.ts +285 -0
  306. package/src/scheduled-requirement-wake.ts +125 -0
  307. package/src/scheduled-run-terminal.test.ts +290 -0
  308. package/src/scheduled-skip-blocking-task.test.ts +120 -0
  309. package/src/scheduled-skip-path-backoff-2622.test.ts +98 -0
  310. package/src/scheduled-stuck-http.test.ts +316 -0
  311. package/src/scheduled-stuck-notice-cap.test.ts +80 -0
  312. package/src/scheduled-stuck.ts +219 -0
  313. package/src/scheduled-tasks-http.test.ts +679 -0
  314. package/src/scheduled-tasks.ts +959 -0
  315. package/src/scheduled-work-outcome-http.test.ts +154 -0
  316. package/src/scheduled-work-outcome.ts +50 -0
  317. package/src/scoped-secrets.ts +141 -0
  318. package/src/secret-echo-negative-control.test.ts +118 -0
  319. package/src/send-dedup-request-id.test.ts +229 -0
  320. package/src/send-reply-agent-warning.test.ts +38 -38
  321. package/src/send-reply-alias-optional.test.ts +131 -0
  322. package/src/send-reply-attachments.test.ts +458 -0
  323. package/src/send_dedup.test.ts +54 -0
  324. package/src/send_dedup.ts +52 -6
  325. package/src/serve-error.test.ts +73 -0
  326. package/src/serve-error.ts +56 -0
  327. package/src/server.ts +5134 -503
  328. package/src/session-task-on-dispatch.ts +14 -0
  329. package/src/session-token-ownership-http.test.ts +122 -0
  330. package/src/shared/codex-inventory.ts +41 -0
  331. package/src/shared/daemon-provider-login.ts +31 -0
  332. package/src/shared/daemon-provider-snapshot.ts +52 -0
  333. package/src/shared/external-schedule-contract.ts +60 -0
  334. package/src/shared/node-name.test.ts +62 -0
  335. package/src/shared/node-name.ts +161 -0
  336. package/src/shared/probe-host-allowlist-drift.test.ts +45 -0
  337. package/src/shared/provider-application.ts +29 -0
  338. package/src/shared/provider-collection.ts +14 -0
  339. package/src/shared/provider-initialization.ts +8 -0
  340. package/src/shared/reserved-env-drift.test.ts +10 -0
  341. package/src/shared/scoped-secret-contract.ts +5 -0
  342. package/src/shared/task-content-limit-drift.test.ts +28 -0
  343. package/src/shared/task-content-limit.ts +25 -0
  344. package/src/side-thread-command-transport.test.ts +312 -0
  345. package/src/side-thread-command-transport.ts +318 -0
  346. package/src/side-thread-http-integration.test.ts +233 -0
  347. package/src/side-thread-http.ts +504 -0
  348. package/src/side-thread-production.test.ts +72 -0
  349. package/src/side-thread-production.ts +118 -0
  350. package/src/side-thread.test.ts +1067 -0
  351. package/src/side-thread.ts +2499 -0
  352. package/src/skillhub-http.test.ts +142 -0
  353. package/src/sqlite-close-checkpoint.test.ts +78 -0
  354. package/src/start-node.test.ts +265 -0
  355. package/src/stats-versions-http.test.ts +65 -0
  356. package/src/status-alias-filter-http.test.ts +106 -0
  357. package/src/status-alias-resolver-http.test.ts +163 -0
  358. package/src/status-alias-resolver.ts +19 -0
  359. package/src/status-node-id-filter-http.test.ts +161 -0
  360. package/src/status-read-cache-http.test.ts +229 -0
  361. package/src/status-read-cache.ts +129 -0
  362. package/src/stop-delete-node.test.ts +567 -1
  363. package/src/task-access-http.test.ts +402 -0
  364. package/src/task-access.ts +420 -0
  365. package/src/task-activity.ts +60 -0
  366. package/src/task-auth-origin-http.test.ts +93 -0
  367. package/src/task-auth-origin.test.ts +24 -0
  368. package/src/task-auth-origin.ts +7 -0
  369. package/src/task-consumption.test.ts +498 -0
  370. package/src/task-diagnostic-http.test.ts +149 -0
  371. package/src/task-diagnostic.test.ts +115 -0
  372. package/src/task-diagnostic.ts +118 -0
  373. package/src/task-expiry-notice-http.test.ts +287 -0
  374. package/src/task-expiry-notice.ts +318 -0
  375. package/src/task-idempotency-mcp.test.ts +142 -0
  376. package/src/task-idempotency.test.ts +76 -0
  377. package/src/task-idempotency.ts +81 -0
  378. package/src/task-late-replies.ts +54 -0
  379. package/src/task-late-reply-http.test.ts +227 -0
  380. package/src/task-lifecycle-watcher-busy.test.ts +114 -0
  381. package/src/task-lifecycle-watcher.test.ts +209 -0
  382. package/src/task-lifecycle-watcher.ts +109 -0
  383. package/src/task-network-resolution-http.test.ts +140 -0
  384. package/src/task-offline-delivery-2668.test.ts +119 -0
  385. package/src/task-offline-delivery.ts +81 -0
  386. package/src/task-orphan-http.test.ts +287 -0
  387. package/src/task-orphan.ts +119 -0
  388. package/src/task-queue-ahead-http.test.ts +309 -0
  389. package/src/task-queue-ahead-scale.test.ts +236 -0
  390. package/src/task-queue-ahead.ts +186 -0
  391. package/src/task-rejection-log-http.test.ts +160 -0
  392. package/src/task-rejection-log.ts +61 -0
  393. package/src/task-sender-http.test.ts +143 -0
  394. package/src/task-stale-open-http.test.ts +292 -0
  395. package/src/task-stale-open.ts +103 -0
  396. package/src/tasks-pagination-http.test.ts +141 -0
  397. package/src/team-rules-status-http.test.ts +90 -0
  398. package/src/team-rules-status.test.ts +59 -0
  399. package/src/team-rules-status.ts +72 -0
  400. package/src/tmux-allowlist.test.ts +48 -0
  401. package/src/tool-audience-http.test.ts +230 -0
  402. package/src/tool-audience.ts +127 -0
  403. package/src/tools-list-json-schema.test.ts +94 -0
  404. package/src/tools.ts +4326 -420
  405. package/src/upload-early-reject-guard.test.ts +155 -0
  406. package/src/uploads-http.test.ts +86 -7
  407. package/src/uploads.ts +38 -4
  408. package/src/user-avatar-http.test.ts +74 -0
  409. package/src/user-avatar-image.ts +160 -0
  410. package/src/user-avatar-migration.test.ts +25 -0
  411. package/src/user-avatar-upload-http.test.ts +348 -0
  412. package/src/user-inbox-by-agent-http.test.ts +165 -0
  413. package/src/user-inbox-netid-notnull.test.ts +122 -0
  414. package/src/user-inbox-read-http.test.ts +223 -0
  415. package/src/user-inbox-schema.test.ts +54 -0
  416. package/src/version-stats.test.ts +66 -0
  417. package/src/version-stats.ts +109 -0
@@ -0,0 +1,231 @@
1
+ // #473(#469 问题 2)—— Agent 查人 + 人员字段按名字写。
2
+ //
3
+ // 钉住:
4
+ // 1. MCP requirements_people:紧凑行(user_id / username / display_name / role / department / agents),
5
+ // 没主人的 Agent 单列;q 按用户名 / 显示名 / 部门 / Agent 别名筛;50 人一页、offset 翻页;一页有字节上限。
6
+ // 2. 严格参数:不认识的参数 → -32602,列出能用的参数。
7
+ // 3. requirements_create / update / upsert 的 owner / agent_owner / participants 收 {kind:'user', username} 与
8
+ // {kind:'node', alias},在任务所在的网络里解析,存下来仍是 {kind, id}。
9
+ // 4. 别名对上多个 Agent → person_ambiguous;找不到 → person_not_in_network;都带 field 和指向 requirements_people 的 hint。
10
+ // 5. 绝不跨网络:别的网络的用户名 / 别名都是「找不到」。受限成员看不见的 Agent:通讯录里没有,按别名写也是「找不到」。
11
+ // 6. REST GET /api/requirements/people 的形状不变。
12
+ //
13
+ // 跑法:cd server && COMMHUB_DB=/tmp/x.db bun test src/requirements-people-mcp-http.test.ts
14
+ // PG:COMMHUB_TEST_PG_URL=… COMMHUB_PG_EXPERIMENTAL=1(tests/test2123-hub-postgres-ladder 里注册)
15
+ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
16
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
17
+ import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
18
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
19
+ import { addNetworkMember, register } from "./auth.js";
20
+ import { db } from "./db.js";
21
+ import { createDepartment, setMemberDepartment } from "./departments.js";
22
+ import { registerTools } from "./tools.js";
23
+
24
+ const activeDbPath = process.env.COMMHUB_DB ?? (process.env.COMMHUB_TEST_PG_URL ? "postgres" : undefined);
25
+ if (!activeDbPath) throw new Error("requirements-people-mcp requires COMMHUB_DB (or COMMHUB_TEST_PG_URL) before module import");
26
+
27
+ const stamp = Date.now();
28
+ const PW = "PeopleLookup123!";
29
+ /** 一页 50 人(每人带部门、1 个 Agent)的字节上限。实测约 12.6 KB(≈ 250 B / 人);上限 16 KB。 */
30
+ const PAGE_MAX_BYTES = 16_000;
31
+ const EXTRA_MEMBERS = 60;
32
+
33
+ let server: any;
34
+ let base = "";
35
+ let netA = "", netB = "";
36
+ let boss: { id: string; token: string; username: string };
37
+ let alice: { id: string; username: string };
38
+ let bob: { id: string; username: string };
39
+ let carol: { id: string; username: string };
40
+ let ruth: { id: string; username: string };
41
+ let deptId = "";
42
+ const node = (suffix: string) => `n_pl_${suffix}_${stamp}`;
43
+ const ALIAS = { alice: `alice-bot-${stamp}`, dup: `dup-bot-${stamp}`, free: `free-bot-${stamp}`, far: `far-bot-${stamp}` };
44
+
45
+ type Mcp = { call: (name: string, args: Record<string, unknown>) => Promise<any>; close: () => Promise<void> };
46
+ async function connect(userId: string, username: string): Promise<Mcp> {
47
+ const s = new McpServer({ name: "people", version: "1" });
48
+ registerTools(s, undefined, null, userId, username, false, "tok_user");
49
+ const client = new Client({ name: "people-client", version: "1" });
50
+ const [ct, st] = InMemoryTransport.createLinkedPair();
51
+ await s.connect(st);
52
+ await client.connect(ct);
53
+ return {
54
+ call: async (name, args) => {
55
+ const r: any = await client.callTool({ name, arguments: args });
56
+ const text = String(r.content?.[0]?.text ?? "");
57
+ if (r.isError) return { mcpError: true, text };
58
+ return { ...JSON.parse(text), _bytes: Buffer.byteLength(text, "utf8") };
59
+ },
60
+ close: async () => { await client.close(); await s.close(); },
61
+ };
62
+ }
63
+ let asBoss: Mcp, asRuth: Mcp;
64
+
65
+ function mk(name: string) {
66
+ const r = register(`${name}_${stamp}`, PW, undefined, name === "alice" ? "爱丽丝" : undefined);
67
+ expect(r.ok).toBe(true);
68
+ return { id: r.user!.user_id, token: r.token!, username: r.user!.username, net: r.network_id! };
69
+ }
70
+ const insertNode = (id: string, alias: string, net: string, owner: string | null) =>
71
+ db.run("INSERT INTO nodes (node_id, node_name, alias, network_id, owner_user_id) VALUES (?1, ?2, ?2, ?3, ?4)", [id, alias, net, owner]);
72
+
73
+ beforeAll(async () => {
74
+ const b = mk("boss"); boss = { id: b.id, token: b.token, username: b.username }; netA = b.net;
75
+ const a = mk("alice"); alice = { id: a.id, username: a.username };
76
+ const o = mk("bob"); bob = { id: o.id, username: o.username };
77
+ const c = mk("carol"); carol = { id: c.id, username: c.username }; netB = c.net;
78
+ const r = mk("ruth"); ruth = { id: r.id, username: r.username };
79
+ expect(addNetworkMember(netA, alice.id, "member", boss.id, { agentAccess: "all" }).ok).toBe(true);
80
+ expect(addNetworkMember(netA, bob.id, "member", boss.id, { agentAccess: "all" }).ok).toBe(true);
81
+ // ruth:受限成员(只看授权的 Agent),一个都没授权
82
+ expect(addNetworkMember(netA, ruth.id, "member", boss.id, { agentAccess: "granted" }).ok).toBe(true);
83
+ const dept = createDepartment(netA, boss.id, { name: `研发部${stamp % 1000}` });
84
+ expect(dept.ok).toBe(true);
85
+ deptId = (dept as any).department.id;
86
+ expect(setMemberDepartment(netA, alice.id, deptId).ok).toBe(true);
87
+ insertNode(node("alice"), ALIAS.alice, netA, alice.id);
88
+ insertNode(node("dup1"), ALIAS.dup, netA, null);
89
+ insertNode(node("dup2"), ALIAS.dup, netA, null);
90
+ insertNode(node("free"), ALIAS.free, netA, null);
91
+ insertNode(node("far"), ALIAS.far, netB, carol.id);
92
+ for (let i = 0; i < EXTRA_MEMBERS; i++) {
93
+ const m = register(`pl_m${String(i).padStart(2, "0")}_${stamp}`, PW, undefined, `成员${i}`);
94
+ expect(addNetworkMember(netA, m.user!.user_id, "member", boss.id, { agentAccess: "all" }).ok).toBe(true);
95
+ setMemberDepartment(netA, m.user!.user_id, deptId);
96
+ insertNode(node(`m${i}`), `m${i}-bot-${stamp}`, netA, m.user!.user_id);
97
+ }
98
+ const mod: any = await import("./server.js");
99
+ server = mod.bootServer({ port: 0, hostname: "127.0.0.1" });
100
+ base = `http://127.0.0.1:${server.port}`;
101
+ asBoss = await connect(boss.id, boss.username);
102
+ asRuth = await connect(ruth.id, ruth.username);
103
+ }, 120_000);
104
+ afterAll(async () => { await asBoss?.close(); await asRuth?.close(); server?.stop?.(true); });
105
+
106
+ describe("#473 requirements_people", () => {
107
+ test("compact rows: username, display_name, role, department, owned agents; unowned agents listed once", async () => {
108
+ const r = await asBoss.call("requirements_people", { network_id: netA, q: "alice" });
109
+ expect(r.ok).toBe(true);
110
+ // #2596 —— Agent 行新增 updated_at / lifecycle_state(客户端用它做 alias 去重与“近 7 天”过滤)。
111
+ // 形状断言改为「关键字段匹配 + 允许新增键」,而不是整行严格相等。
112
+ expect(r.people).toHaveLength(1);
113
+ expect(r.people[0]).toMatchObject({
114
+ user_id: alice.id, username: alice.username, display_name: "爱丽丝", role: "member",
115
+ department: { id: deptId, name: `研发部${stamp % 1000}` },
116
+ });
117
+ expect(r.people[0].agents).toHaveLength(1);
118
+ expect(r.people[0].agents[0]).toMatchObject({ node_id: node("alice"), alias: ALIAS.alice });
119
+ expect(r.people[0].agents[0]).toHaveProperty("updated_at");
120
+ const all = await asBoss.call("requirements_people", { network_id: netA, q: String(stamp) });
121
+ expect(all.agents_without_owner.map((a: any) => a.alias).sort()).toEqual([ALIAS.dup, ALIAS.dup, ALIAS.free].sort());
122
+ const bossRow = (await asBoss.call("requirements_people", { network_id: netA, q: boss.username })).people[0];
123
+ expect(bossRow.role).toBe("owner");
124
+ expect(bossRow.display_name).toBe("");
125
+ expect(bossRow.department).toBeNull();
126
+ });
127
+
128
+ test("q matches username, display name, department and Agent alias", async () => {
129
+ expect((await asBoss.call("requirements_people", { network_id: netA, q: "爱丽" })).people.map((p: any) => p.user_id)).toEqual([alice.id]);
130
+ expect((await asBoss.call("requirements_people", { network_id: netA, q: ALIAS.alice.toUpperCase() })).people.map((p: any) => p.user_id)).toEqual([alice.id]);
131
+ const dept = await asBoss.call("requirements_people", { network_id: netA, q: `研发部${stamp % 1000}`, limit: 200 });
132
+ expect(dept.total).toBe(EXTRA_MEMBERS + 1);
133
+ });
134
+
135
+ test("default page = 50 people under the byte bound; offset pages the rest", async () => {
136
+ const p1 = await asBoss.call("requirements_people", { network_id: netA });
137
+ expect(p1.people.length).toBe(50);
138
+ expect(p1.has_more).toBe(true);
139
+ console.log(`people page of 50: ${p1._bytes} B`);
140
+ expect(p1._bytes).toBeLessThan(PAGE_MAX_BYTES);
141
+ const p2 = await asBoss.call("requirements_people", { network_id: netA, offset: p1.next_offset });
142
+ expect(p2.people.length).toBe(p1.total - 50);
143
+ expect(p2.agents_without_owner).toBeUndefined();
144
+ expect(new Set([...p1.people, ...p2.people].map((p: any) => p.user_id)).size).toBe(p1.total);
145
+ });
146
+
147
+ test("strict params: unknown key → -32602 listing the valid ones", async () => {
148
+ const r = await asBoss.call("requirements_people", { network_id: netA, name: "alice" });
149
+ expect(r.mcpError).toBe(true);
150
+ expect(r.text).toContain("-32602");
151
+ expect(r.text).toContain("unknown parameter(s): name; valid parameters: network_id, q, limit, offset");
152
+ });
153
+
154
+ test("another network is not readable; a restricted member sees no ungranted Agents", async () => {
155
+ const other = await asBoss.call("requirements_people", { network_id: netB });
156
+ expect(other.ok).toBe(false);
157
+ const r = await asRuth.call("requirements_people", { network_id: netA, q: String(stamp), limit: 200 });
158
+ expect(r.people.every((p: any) => p.agents.length === 0)).toBe(true);
159
+ expect(r.agents_without_owner).toEqual([]);
160
+ });
161
+ });
162
+
163
+ describe("#473 person fields by name", () => {
164
+ test("create / update / upsert accept username and alias; stored as ids in this network", async () => {
165
+ const made = await asBoss.call("requirements_create", {
166
+ network_id: netA, name: `by name ${stamp}`,
167
+ owner: { kind: "user", username: alice.username },
168
+ agent_owner: { kind: "node", alias: ALIAS.alice },
169
+ participants: [{ kind: "user", username: bob.username }, { kind: "node", alias: ALIAS.free }],
170
+ });
171
+ expect(made.ok).toBe(true);
172
+ const req = made.requirement;
173
+ expect(req.owner).toEqual({ kind: "user", id: alice.id });
174
+ expect(req.agent_owner).toEqual({ kind: "node", id: node("alice") });
175
+ expect(req.participants).toEqual([{ kind: "user", id: bob.id }, { kind: "node", id: node("free") }]);
176
+
177
+ const upd = await asBoss.call("requirements_update", { id: req.id, network_id: netA, owner: { kind: "user", username: bob.username } });
178
+ expect(upd.requirement.owner).toEqual({ kind: "user", id: bob.id });
179
+
180
+ const ups = await asBoss.call("requirements_upsert_by_external_ref", {
181
+ network_id: netA, external_ref: `test:people#${stamp}`, name: "upserted", agent_owner: { kind: "node", alias: ALIAS.alice },
182
+ });
183
+ expect(ups.requirement.agent_owner).toEqual({ kind: "node", id: node("alice") });
184
+ // id 照旧可用,且优先于名字
185
+ const byId = await asBoss.call("requirements_update", { id: req.id, network_id: netA, owner: { kind: "user", id: alice.id, username: bob.username } });
186
+ expect(byId.requirement.owner).toEqual({ kind: "user", id: alice.id });
187
+ });
188
+
189
+ test("ambiguous alias → person_ambiguous with field and a requirements_people hint", async () => {
190
+ const r = await asBoss.call("requirements_create", { network_id: netA, name: "amb", agent_owner: { kind: "node", alias: ALIAS.dup } });
191
+ expect(r.ok).toBe(false);
192
+ expect(r.error).toBe("person_ambiguous");
193
+ expect(r.field).toBe("agent_owner");
194
+ expect(r.hint).toContain("requirements_people");
195
+ expect(r.hint).toContain("node_id");
196
+ });
197
+
198
+ test("unknown name → person_not_in_network naming the field and requirements_people", async () => {
199
+ const r = await asBoss.call("requirements_create", { network_id: netA, name: "nope", participants: [{ kind: "user", username: `ghost_${stamp}` }] });
200
+ expect(r.error).toBe("person_not_in_network");
201
+ expect(r.field).toBe("participants");
202
+ expect(r.hint).toContain("requirements_people");
203
+ });
204
+
205
+ test("never across networks: another network's username / alias is not found", async () => {
206
+ const u = await asBoss.call("requirements_create", { network_id: netA, name: "x", owner: { kind: "user", username: carol.username } });
207
+ expect(u.error).toBe("person_not_in_network");
208
+ const n = await asBoss.call("requirements_create", { network_id: netA, name: "x", agent_owner: { kind: "node", alias: ALIAS.far } });
209
+ expect(n.error).toBe("person_not_in_network");
210
+ });
211
+
212
+ test("wrong-kind or missing identifier → invalid_person", async () => {
213
+ for (const bad of [{ kind: "user", alias: ALIAS.alice }, { kind: "node", username: alice.username }, { kind: "user" }]) {
214
+ const r = await asBoss.call("requirements_create", { network_id: netA, name: "bad", participants: [bad] });
215
+ expect(r.error).toBe("invalid_person");
216
+ expect(r.hint).toContain("requirements_people");
217
+ }
218
+ });
219
+
220
+ test("a restricted member cannot resolve an Agent alias they are not granted", async () => {
221
+ const r = await asRuth.call("requirements_create", { network_id: netA, name: "hidden", agent_owner: { kind: "node", alias: ALIAS.alice } });
222
+ expect(r.error).toBe("person_not_in_network");
223
+ });
224
+
225
+ test("REST GET /api/requirements/people keeps its shape", async () => {
226
+ const res = await fetch(`${base}/api/requirements/people?network_id=${netA}`, { headers: { Authorization: `Bearer ${boss.token}` } });
227
+ const body = await res.json() as any;
228
+ expect(res.status).toBe(200);
229
+ for (const p of body.people) expect(Object.keys(p).sort()).toEqual(["display_name", "id", "kind", "name", "networkId"]);
230
+ });
231
+ });
@@ -0,0 +1,196 @@
1
+ // #473(#469 问题 2)—— Agent 查人。
2
+ //
3
+ // 现场:Agent 想把任务派给「张三」或者某个节点,手里只有用户名 / 别名,而任务的人员字段只收 id;
4
+ // GET /api/requirements/people 只给显示名,没有用户名、角色、部门,也看不出哪个 Agent 是谁的。
5
+ // 这里给 MCP requirements_people 一份紧凑的通讯录:每个成员一行(user_id、username、display_name、网络角色、
6
+ // 部门),带上他名下的 Agent(node_id、alias);没有主人(或主人不在本网络)的 Agent 单列。
7
+ // 只在一个网络里查,受限成员看不见的 Agent 一律不出现(与 /people 同一个 hidden 判据)。
8
+ //
9
+ // 人员字段按名字写(owner {kind:'user', username} / agent_owner {kind:'node', alias})的解析在
10
+ // requirements.ts personRef():同样只在任务所在的那个网络里找,看不见的节点等同不存在。
11
+
12
+ import { db } from "./db.js";
13
+ import "./departments.js"; // network_departments 表 + network_members.department_id 列(导入即建,只增)
14
+
15
+ type HiddenNode = ((nodeId: string) => boolean) | null;
16
+
17
+ export const PEOPLE_DEFAULT_LIMIT = 50;
18
+ export const PEOPLE_MAX_LIMIT = 200;
19
+
20
+ /** `department_id`: Agent 的**显式**部门归属(可空)。空 = 仍按「负责人在哪个部门」推断,
21
+ * 客户端据此把 Agent 放对格子 —— 2026-10-19 前没有这一列,328 个 Agent 只能全算「未归属」。 */
22
+ export type DirectoryAgent = {
23
+ node_id: string;
24
+ alias: string;
25
+ department_id?: string | null;
26
+ /**
27
+ * #2596 —— 这一行“最后一次被 Hub 看到”的时间(`nodes.updated_at`),以及生命周期状态。
28
+ *
29
+ * 为什么加:组织架构页把 368 个 agent 全塞进「未归属」,其中 125 个是 5–8 月的历史残留
30
+ * (如 `海报设计师1–5号` 注册于 2026-05-17、早已 offline)。客户端要能“默认只显示近 7 天活跃”
31
+ * 与“同一 alias 只保留最新的那条”,就必须拿到时间轴——否则只能靠 node_id 猜。
32
+ *
33
+ * 只增不改:老客户端忽略未知键,形状断言已在同批测试里放宽。
34
+ */
35
+ updated_at?: string | null;
36
+ lifecycle_state?: string | null;
37
+ };
38
+ export type DirectoryPerson = {
39
+ user_id: string;
40
+ username: string;
41
+ /** 没设(或等于用户名)为 ""(与 /people 同一规则)。 */
42
+ display_name: string;
43
+ role: string;
44
+ department: { id: string; name: string } | null;
45
+ agents: DirectoryAgent[];
46
+ };
47
+
48
+ /** q / limit / offset 解析;不合法 → 错误码(400)。 */
49
+ export function parsePeopleQuery(params: URLSearchParams): { q: string; limit: number; offset: number } | { error: string } {
50
+ const q = (params.get("q") ?? "").trim();
51
+ if (q.length > 100) return { error: "invalid_q" };
52
+ let limit = PEOPLE_DEFAULT_LIMIT;
53
+ const rawLimit = params.get("limit");
54
+ if (rawLimit !== null) {
55
+ if (!/^\d{1,4}$/.test(rawLimit)) return { error: "invalid_limit" };
56
+ limit = Number(rawLimit);
57
+ if (limit < 1 || limit > PEOPLE_MAX_LIMIT) return { error: "invalid_limit" };
58
+ }
59
+ let offset = 0;
60
+ const rawOffset = params.get("offset");
61
+ if (rawOffset !== null) {
62
+ if (!/^\d{1,6}$/.test(rawOffset)) return { error: "invalid_offset" };
63
+ offset = Number(rawOffset);
64
+ }
65
+ return { q, limit, offset };
66
+ }
67
+
68
+ /**
69
+ * 一个网络的通讯录。q = 不区分大小写的子串,匹配用户名 / 显示名 / 部门名 / 名下 Agent 的别名;
70
+ * 成员按 username 排序、offset 翻页;没主人的 Agent 只在第一页给(按 q 过滤)。
71
+ */
72
+ export function peopleDirectory(networkId: string, hidden: HiddenNode, query: { q: string; limit: number; offset: number }) {
73
+ const members = db.all<{ user_id: string; username: string; display_name: string | null; role: string | null; department_id: string | null; department_name: string | null }>(
74
+ `SELECT u.user_id, u.username, u.display_name, m.role, d.department_id, d.name AS department_name
75
+ FROM network_members m
76
+ JOIN users u ON u.user_id = m.user_id
77
+ LEFT JOIN network_departments d ON d.network_id = m.network_id AND d.department_id = m.department_id
78
+ WHERE m.network_id = ?1
79
+ ORDER BY u.username, u.user_id`,
80
+ networkId,
81
+ );
82
+ const nodes = db.all<{ node_id: string; alias: string | null; node_name: string; owner_user_id: string | null; department_id: string | null; updated_at: string | null; lifecycle_state: string | null }>(
83
+ "SELECT node_id, alias, node_name, owner_user_id, department_id, updated_at, lifecycle_state FROM nodes WHERE network_id = ?1 ORDER BY COALESCE(alias, node_name), node_id",
84
+ networkId,
85
+ ).filter(n => !hidden?.(n.node_id));
86
+ // #2965 —— 同 alias 多 node 行时**不删行**(保持既有契约:重复项照样列出,客户端去重),
87
+ // 只额外给一个确定性的「该保留哪条」:其余行带 `duplicate_of = <首选 node_id>`。
88
+ //
89
+ // 为什么必须由 hub 判:客户端只看得到 updated_at,而重复注册常发生在同一秒 ——
90
+ // 实测 TM客户端基建牛 三条 updated_at 完全相同(2026-10-26 12:26:22),
91
+ // 按「保留最新」会随机留一条,而真正在跑的是**有会话**的那条(客户端看不到会话)。
92
+ //
93
+ // 规则:有会话 > updated_at 新 > node_id 字典序(最后一条只为让结果稳定)。
94
+ const liveNodeIds = new Set(
95
+ db.all<{ node_id: string | null }>("SELECT DISTINCT node_id FROM sessions WHERE network_id = ?1", networkId)
96
+ .map(r => r.node_id).filter((x): x is string => !!x),
97
+ );
98
+ const byAliasForRank = new Map<string, typeof nodes>();
99
+ for (const n of nodes) {
100
+ const key = n.alias || n.node_name;
101
+ const bucket = byAliasForRank.get(key);
102
+ if (bucket) bucket.push(n); else byAliasForRank.set(key, [n]);
103
+ }
104
+ const preferredByAlias = new Map<string, string>();
105
+ for (const [key, bucket] of byAliasForRank) {
106
+ if (bucket.length < 2) continue;
107
+ const ranked = [...bucket].sort((a, b) => {
108
+ const alive = Number(liveNodeIds.has(b.node_id)) - Number(liveNodeIds.has(a.node_id));
109
+ if (alive !== 0) return alive;
110
+ const t = String(b.updated_at ?? "").localeCompare(String(a.updated_at ?? ""));
111
+ if (t !== 0) return t;
112
+ return a.node_id.localeCompare(b.node_id);
113
+ });
114
+ preferredByAlias.set(key, ranked[0].node_id);
115
+ }
116
+ const memberIds = new Set(members.map(m => m.user_id));
117
+ const byOwner = new Map<string, DirectoryAgent[]>();
118
+ const unowned: DirectoryAgent[] = [];
119
+ for (const n of nodes) {
120
+ // 只在**显式**归属时带这一格:没设 = 没有显式归属(顶层 agent_department_supported 告诉
121
+ // 客户端这一点)。行形状保持不变 —— 旧客户端拿到的行还是老样子(多一个键会让严格要求
122
+ // 形状的测试/客户端意外),只是新客户端不再把「负责人在哪个部门」当成 Agent 的部门。
123
+ const agent = {
124
+ node_id: n.node_id,
125
+ alias: n.alias || n.node_name,
126
+ ...(n.department_id ? { department_id: n.department_id } : {}),
127
+ // #2596 —— 客户端据此做「按 alias 去重(保留最新)」与「默认只看近 7 天」。
128
+ updated_at: n.updated_at ?? null,
129
+ lifecycle_state: n.lifecycle_state ?? null,
130
+ // #2965 —— 同 alias 的重复行:这一格指向「首选 node_id」,没有重复时不出现。
131
+ // 客户端可以据此只显示首选那条;也可以像以前一样自己按 updated_at 去重(行为不变)。
132
+ ...(() => {
133
+ const pref = preferredByAlias.get(n.alias || n.node_name);
134
+ return pref && pref !== n.node_id ? { duplicate_of: pref } : {};
135
+ })(),
136
+ };
137
+ if (n.owner_user_id && memberIds.has(n.owner_user_id)) {
138
+ const list = byOwner.get(n.owner_user_id) ?? [];
139
+ list.push(agent);
140
+ byOwner.set(n.owner_user_id, list);
141
+ } else unowned.push(agent);
142
+ }
143
+ const needle = query.q.toLowerCase();
144
+ const hit = (s: string | null | undefined) => !needle || (s ?? "").toLowerCase().includes(needle);
145
+ const people: DirectoryPerson[] = [];
146
+ for (const m of members) {
147
+ const displayName = !m.display_name || m.display_name === m.username ? "" : m.display_name;
148
+ const agents = byOwner.get(m.user_id) ?? [];
149
+ if (!(hit(m.username) || (displayName && hit(displayName)) || (m.department_name && hit(m.department_name)) || agents.some(a => hit(a.alias)))) continue;
150
+ people.push({
151
+ user_id: m.user_id,
152
+ username: m.username,
153
+ display_name: displayName,
154
+ role: m.role ?? "member",
155
+ department: m.department_id && m.department_name ? { id: m.department_id, name: m.department_name } : null,
156
+ agents,
157
+ });
158
+ }
159
+ const page = people.slice(query.offset, query.offset + query.limit);
160
+ const hasMore = query.offset + query.limit < people.length;
161
+ return {
162
+ ok: true,
163
+ network_id: networkId,
164
+ total: people.length,
165
+ people: page,
166
+ // #1976 —— 「Agent 归属」与「人类部门」是两个独立的结构。
167
+ // Agent 放哪个部门,只由**显式**设置(nodes.department_id)决定;**不再**从「负责人在哪个部门」推断。
168
+ // 这一格告诉客户端「这个 Hub 支持显式 Agent 部门」:客户端据此把「没有 department_id 这一行」
169
+ // 读成「没有显式归属 ⇒ 未归属」,而不是「按负责人部门推断」。
170
+ // 老 Hub 没有这一格 ⇒ 客户端保留旧的推断口径,行为不变。
171
+ agent_department_supported: true,
172
+ ...(query.offset === 0 ? { agents_without_owner: unowned.filter(a => hit(a.alias)) } : {}),
173
+ has_more: hasMore,
174
+ next_offset: hasMore ? query.offset + query.limit : null,
175
+ };
176
+ }
177
+
178
+ /**
179
+ * 按名字找人(personRef 用):只在 networkId 里找,hidden 的节点等同不存在。
180
+ * 返回 id;找不到 → person_not_in_network;同一个别名对上多个节点 → person_ambiguous。
181
+ */
182
+ export function resolvePersonName(kind: "user" | "node", name: string, networkId: string, hidden: HiddenNode): string {
183
+ if (kind === "user") {
184
+ const row = db.get<{ user_id: string }>(
185
+ "SELECT u.user_id FROM network_members m JOIN users u ON u.user_id = m.user_id WHERE m.network_id = ?1 AND u.username = ?2",
186
+ networkId, name,
187
+ );
188
+ if (!row) throw new Error("person_not_in_network");
189
+ return row.user_id;
190
+ }
191
+ const rows = db.all<{ node_id: string }>("SELECT node_id FROM nodes WHERE network_id = ?1 AND alias = ?2", networkId, name)
192
+ .filter(r => !hidden?.(r.node_id));
193
+ if (rows.length === 0) throw new Error("person_not_in_network");
194
+ if (rows.length > 1) throw new Error("person_ambiguous");
195
+ return rows[0].node_id;
196
+ }
@@ -0,0 +1,114 @@
1
+ // P0–P3 优先级:lowest(P3 极低)。生产库的 requirements 表建于旧 db.ts,带 CHECK(priority IN ('high', 'normal', 'low')),
2
+ // 光放开校验集合写进去也会被 SQLite 拒掉。这里先用旧建表语句建库、塞行,再走真实启动路径(db.ts + server.ts),
3
+ // 看:表重建一次、存量行 / 索引原样、lowest 在 POST / PATCH / upsert 都能写、坏值仍被拒、再启动不再重建。
4
+ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
5
+ import { Database } from "bun:sqlite";
6
+ import { mkdtempSync, rmSync } from "node:fs";
7
+ import { tmpdir } from "node:os";
8
+ import { join } from "node:path";
9
+
10
+ const dir = mkdtempSync(join(tmpdir(), "anet-req-priority-"));
11
+ const file = join(dir, "hub.db");
12
+ process.env.COMMHUB_DB = file;
13
+
14
+ const legacy = new Database(file);
15
+ legacy.exec(`
16
+ CREATE TABLE IF NOT EXISTS requirements (
17
+ requirement_id TEXT PRIMARY KEY,
18
+ network_id TEXT NOT NULL,
19
+ title TEXT NOT NULL,
20
+ column_name TEXT NOT NULL DEFAULT 'pool' CHECK(column_name IN ('pool', 'doing', 'done')),
21
+ priority TEXT NOT NULL DEFAULT 'normal' CHECK(priority IN ('high', 'normal', 'low')),
22
+ due_on TEXT,
23
+ assignee TEXT,
24
+ client_id TEXT,
25
+ issues_json TEXT,
26
+ created_by TEXT,
27
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
28
+ updated_at TEXT NOT NULL DEFAULT (datetime('now'))
29
+ );
30
+ CREATE INDEX IF NOT EXISTS idx_requirements_network ON requirements(network_id, created_at DESC);
31
+ `);
32
+ legacy.exec("ALTER TABLE requirements ADD COLUMN tags_json TEXT NOT NULL DEFAULT '[]'");
33
+ legacy.exec("ALTER TABLE requirements ADD COLUMN description TEXT");
34
+ const seeded = [["r_high", "high"], ["r_normal", "normal"], ["r_low", "low"]] as const;
35
+ for (const [id, p] of seeded) {
36
+ legacy.run("INSERT INTO requirements (requirement_id, network_id, title, priority, client_id, description, tags_json) VALUES (?1, 'net_legacy', ?2, ?3, ?4, ?5, '[\"旧\"]')", [id, `卡 ${id}`, p, `c_${id}`, `desc ${id}`]);
37
+ }
38
+ // 旧库确实拒 lowest:这就是光改 PRIORITIES 不够的原因
39
+ expect(() => legacy.run("INSERT INTO requirements (requirement_id, network_id, title, priority) VALUES ('x', 'n', 't', 'lowest')")).toThrow(/CHECK/);
40
+ legacy.close();
41
+
42
+ let base = "";
43
+ let token = "";
44
+ let server: { port: number; stop?: (force?: boolean) => void };
45
+ let db: any;
46
+
47
+ async function api(path: string, init?: RequestInit) {
48
+ const res = await fetch(`${base}${path}`, { ...init, headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" } });
49
+ return { status: res.status, body: await res.json() as any };
50
+ }
51
+
52
+ beforeAll(async () => {
53
+ ({ db } = await import("./db.js"));
54
+ const { register } = await import("./auth.js");
55
+ const owner = register(`prio_owner_${Date.now()}`, "PriorityOwner123!", undefined, "seed");
56
+ token = owner.token!;
57
+ const mod: any = await import("./server.js");
58
+ server = mod.bootServer({ port: 0, hostname: "127.0.0.1" });
59
+ base = `http://127.0.0.1:${server.port}`;
60
+ }, 30_000);
61
+
62
+ afterAll(() => {
63
+ try { server?.stop?.(true); } catch {}
64
+ try { rmSync(dir, { recursive: true, force: true }); } catch {}
65
+ });
66
+
67
+ describe("P3 lowest priority", () => {
68
+ test("startup rebuilds the legacy CHECK once and keeps every row and index", async () => {
69
+ const sql = db.get("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'requirements'").sql as string;
70
+ expect(sql).toContain("'lowest'");
71
+ expect(sql).toContain("CHECK(column_name IN ('pool', 'doing', 'done', 'abandoned'))");
72
+ const rows = db.all("SELECT requirement_id, network_id, title, priority, client_id, description, tags_json FROM requirements WHERE network_id = 'net_legacy' ORDER BY requirement_id") as any[];
73
+ expect(rows.map(r => [r.requirement_id, r.priority])).toEqual([["r_high", "high"], ["r_low", "low"], ["r_normal", "normal"]]);
74
+ for (const r of rows) {
75
+ expect(r.title).toBe(`卡 ${r.requirement_id}`);
76
+ expect(r.client_id).toBe(`c_${r.requirement_id}`);
77
+ expect(r.description).toBe(`desc ${r.requirement_id}`);
78
+ expect(r.tags_json).toBe('["旧"]');
79
+ }
80
+ const indexes = (db.all("PRAGMA index_list(requirements)") as { name: string; unique: number }[]).map(i => i.name);
81
+ for (const name of ["idx_requirements_network", "idx_requirements_client", "idx_requirements_external_ref", "idx_requirements_network_updated", "idx_requirements_parent"]) expect(indexes).toContain(name);
82
+ expect(db.get("SELECT name FROM sqlite_master WHERE name = 'requirements_migrated'")).toBeNull();
83
+ // 坏值仍被数据库拒
84
+ expect(() => db.run("INSERT INTO requirements (requirement_id, network_id, title, priority) VALUES ('bad', 'n', 't', 'urgent')")).toThrow(/CHECK/);
85
+ // 下次启动:已经放开,不再重建
86
+ const { migrateRequirementPriorityCheck } = await import("./requirements-migrate.js");
87
+ expect(migrateRequirementPriorityCheck(db).rebuilt).toBe(false);
88
+ });
89
+
90
+ test("lowest is accepted on create, PATCH and upsert; unknown values stay 400", async () => {
91
+ const created = await api("/api/requirements", { method: "POST", body: JSON.stringify({ name: "极低的活", priority: "lowest" }) });
92
+ expect(created.status).toBe(201);
93
+ expect(created.body.requirement.priority).toBe("lowest");
94
+ const id = created.body.requirement.id;
95
+ const patched = await api(`/api/requirements/${id}`, { method: "PATCH", body: JSON.stringify({ priority: "low" }) });
96
+ expect(patched.body.requirement.priority).toBe("low");
97
+ const back = await api(`/api/requirements/${id}`, { method: "PATCH", body: JSON.stringify({ priority: "lowest" }) });
98
+ expect(back.status).toBe(200);
99
+ expect(back.body.requirement.priority).toBe("lowest");
100
+ const up = await api("/api/requirements/upsert", { method: "POST", body: JSON.stringify({ name: "同步来的", external_ref: "github:t/p#1", priority: "lowest" }) });
101
+ expect(up.status).toBe(201);
102
+ expect(up.body.requirement.priority).toBe("lowest");
103
+ const upAgain = await api("/api/requirements/upsert", { method: "POST", body: JSON.stringify({ external_ref: "github:t/p#1", priority: "high" }) });
104
+ expect(upAgain.body.requirement.priority).toBe("high");
105
+ for (const [path, method] of [["/api/requirements", "POST"], [`/api/requirements/${id}`, "PATCH"]] as const) {
106
+ const bad = await api(path, { method, body: JSON.stringify({ name: "x", priority: "urgent" }) });
107
+ expect(bad.status).toBe(400);
108
+ expect(bad.body.error).toBe("invalid_priority");
109
+ }
110
+ const listed = await api("/api/requirements");
111
+ expect(listed.body.capabilities).toContain("priority_lowest");
112
+ expect(listed.body.requirements.find((r: any) => r.id === id).priority).toBe("lowest");
113
+ });
114
+ });
@@ -0,0 +1,57 @@
1
+ import { afterAll, beforeAll, expect, test } from "bun:test";
2
+ import { mkdtempSync } from "node:fs";
3
+
4
+ process.env.COMMHUB_DB ||= `${mkdtempSync("/tmp/req-echo-")}/hub.db`;
5
+
6
+ let hub: any;
7
+ let base = "";
8
+ let owner: any;
9
+ let outsider: any;
10
+
11
+ async function rest(token: string, path: string) {
12
+ const r = await fetch(`${base}${path}`, { headers: { Authorization: `Bearer ${token}` } });
13
+ return { status: r.status, body: await r.json() as any };
14
+ }
15
+
16
+ beforeAll(async () => {
17
+ const { register } = await import("./auth.js");
18
+ owner = register("echo_owner", "Fixture-Strong1!");
19
+ outsider = register("echo_outsider", "Fixture-Strong1!");
20
+ const { bootServer } = await import("./server.js");
21
+ hub = bootServer({ port: 0, hostname: "127.0.0.1" });
22
+ base = `http://127.0.0.1:${hub.port}`;
23
+ await rest(owner.token, `/api/requirements/projects?network_id=${owner.network_id}`); // warm
24
+ }, 60_000);
25
+ afterAll(() => hub?.stop(true));
26
+
27
+ // #2899 —— 三条复核的共同点:响应码不携带「你问的是不是这个网络」。
28
+ // 只加一个回显字段,不改鉴权、不改返回内容、不引入新的 4xx。
29
+ test("projects 列表回显实际使用的 network_id", async () => {
30
+ const r = await rest(owner.token, `/api/requirements/projects?network_id=${owner.network_id}`);
31
+ expect(r.status).toBe(200);
32
+ expect(r.body.network_id).toBe(owner.network_id);
33
+ });
34
+
35
+ test("不带 network_id(单一成员可被自动推断)时,回显推断出来的那个网络", async () => {
36
+ const r = await rest(owner.token, "/api/requirements/projects");
37
+ expect(r.status).toBe(200);
38
+ expect(r.body.network_id).toBe(owner.network_id);
39
+ // 没有跨网泄漏:项目都属于回显的那个网络
40
+ for (const p of r.body.projects) expect(p.network_id ?? owner.network_id).toBe(owner.network_id);
41
+ });
42
+
43
+ test("节点令牌传别人网络的 id 时,回显的是**它自己**的网络(调用方可据此发现不一致)", async () => {
44
+ const { db } = await import("./db.js");
45
+ const nodeId = `n_echo_${Date.now()}`;
46
+ db.run(`INSERT INTO nodes(node_id,node_name,alias,network_id,owner_user_id,lifecycle_state)
47
+ VALUES(?1,?1,?1,?2,?3,'active')`, [nodeId, owner.network_id, owner.user.user_id]);
48
+ const { generateNetworkToken, hashToken } = await import("./db.js");
49
+ const raw = generateNetworkToken();
50
+ db.run(`INSERT INTO api_tokens(token_id,user_id,network_id,scope,name,token_hash,bound_node_id,node_identity_epoch)
51
+ VALUES(?1,?2,?3,'network','node:echo',?4,?1,2)`, [nodeId, owner.user.user_id, owner.network_id, hashToken(raw)]);
52
+
53
+ const r = await rest(raw, "/api/requirements/projects?network_id=net_someone_else");
54
+ expect(r.status).toBe(200);
55
+ // 关键:不是 net_someone_else,而是令牌自己的网络 —— 客户端可据此判定「拿到的不是我问的」
56
+ expect(r.body.network_id).toBe(owner.network_id);
57
+ });