@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,165 @@
1
+ // 参与人改了任务 → 通知相关的人(Vincent 2026-10-01「参与人可以改,但是改了之后需要有个通知」)。
2
+ //
3
+ // 谁触发:操作者是人,且是这张卡的参与人、不是负责人(权限上参与人只能改状态和检查项,见 task-access.ts
4
+ // PARTICIPANT_EDIT_FIELDS;老成员 task_access='all' 的参与人改了也一样通知)。只说状态和检查项的变化,别的字段不进正文。
5
+ // 通知谁:负责人、创建者、其他参与人 —— 只要人类、去重、不含操作者本人。
6
+ // 怎么送:复用人与人私信(human-dm.ts,user_inbox kind=human_dm + /events/users/me 的 desktop_message),
7
+ // 发信人 = 操作者。App 已有的展示:顶部提示 + 人员列表未读 + 与他的私信会话。不新增渠道。
8
+ // 合并:同一 (收件人, 操作者, 卡) 在 COALESCE_WINDOW_MS 内的连续改动并进同一条还没读的私信(改写正文,不再弹)。
9
+
10
+ import { db, uuidv4 } from "./db.js";
11
+ import { isParticipant } from "./task-access.js";
12
+ import { rewriteUnreadNoticeDm, sendNoticeDm } from "./human-dm.js";
13
+
14
+ export const COALESCE_WINDOW_MS = 60_000;
15
+ const COLUMN_LABEL: Record<string, string> = { pool: "需求池", doing: "进行中", done: "完成", abandoned: "废弃" };
16
+ const MAX_LINES = 20;
17
+ const MAX_ITEM_CHARS = 40;
18
+
19
+ export type NoticeCard = {
20
+ requirement_id: string;
21
+ network_id: string;
22
+ seq: number | null;
23
+ title: string;
24
+ column_name: string;
25
+ checklist_json: string | null;
26
+ owner_json: string | null;
27
+ participants_json: string | null;
28
+ created_by: string | null;
29
+ created_by_json: string | null;
30
+ };
31
+
32
+ type Item = { id: string; text: string; done: boolean };
33
+ const items = (raw: string | null): Item[] => {
34
+ try {
35
+ const list = raw ? JSON.parse(raw) : [];
36
+ return Array.isArray(list) ? list.filter((x) => x && typeof x.id === "string").map((x) => ({ id: x.id, text: String(x.text ?? ""), done: x.done === true })) : [];
37
+ } catch { return []; }
38
+ };
39
+ const clip = (s: string) => { const c = Array.from(s); return c.length > MAX_ITEM_CHARS ? c.slice(0, MAX_ITEM_CHARS).join("") + "…" : s; };
40
+ const parse = (raw: string | null) => { try { return raw ? JSON.parse(raw) : null; } catch { return null; } };
41
+ const userIdOf = (ref: unknown): string | null => {
42
+ const r = ref as { kind?: unknown; id?: unknown } | null;
43
+ return r && r.kind === "user" && typeof r.id === "string" ? r.id : null;
44
+ };
45
+
46
+ /**
47
+ * 这次改动里要说的那几件事,按「对象」做键:同一个对象后一次覆盖前一次(先勾再取消 = 只剩「取消勾选」)。
48
+ * 键:column / ck:<id>。值:一句短话(不带主语和卡名)。
49
+ */
50
+ export function describeChanges(before: Pick<NoticeCard, "column_name" | "checklist_json">, after: Pick<NoticeCard, "column_name" | "checklist_json">): Array<[string, string]> {
51
+ const out: Array<[string, string]> = [];
52
+ if (before.column_name !== after.column_name) out.push(["column", `改为 ${COLUMN_LABEL[after.column_name] ?? after.column_name}`]);
53
+ const a = items(before.checklist_json), b = items(after.checklist_json);
54
+ const was = new Map(a.map((x) => [x.id, x]));
55
+ const now = new Map(b.map((x) => [x.id, x]));
56
+ for (const x of b) {
57
+ const old = was.get(x.id);
58
+ if (!old) { out.push([`ck:${x.id}`, `添加了检查项「${clip(x.text)}」`]); continue; }
59
+ if (old.text !== x.text) out.push([`ck:${x.id}`, `把检查项「${clip(old.text)}」改为「${clip(x.text)}」`]);
60
+ else if (old.done !== x.done) out.push([`ck:${x.id}`, `${x.done ? "勾选了" : "取消勾选了"}检查项「${clip(x.text)}」`]);
61
+ }
62
+ for (const x of a) if (!now.has(x.id)) out.push([`ck:${x.id}`, `删除了检查项「${clip(x.text)}」`]);
63
+ return out;
64
+ }
65
+
66
+ /** 收件人:负责人、创建者、其他参与人(只要人,去重,去掉操作者)。 */
67
+ export function noticeRecipients(card: NoticeCard, actorUserId: string): string[] {
68
+ const ids = new Set<string>();
69
+ const owner = userIdOf(parse(card.owner_json));
70
+ if (owner) ids.add(owner);
71
+ const creator = userIdOf(parse(card.created_by_json)) ?? (!card.created_by_json && card.created_by ? card.created_by : null);
72
+ if (creator) ids.add(creator);
73
+ const participants = parse(card.participants_json);
74
+ if (Array.isArray(participants)) for (const p of participants) { const id = userIdOf(p); if (id) ids.add(id); }
75
+ ids.delete(actorUserId);
76
+
77
+ return [...ids];
78
+ }
79
+
80
+ export function noticeText(actorName: string, title: string, lines: readonly string[]): string {
81
+ if (lines.length === 1) {
82
+ const line = lines[0];
83
+ return line.startsWith("改为 ") ? `${actorName} 把「${title}」${line}` : `${actorName} 在「${title}」${line}`;
84
+ }
85
+ const shown = lines.slice(-MAX_LINES);
86
+ const more = lines.length > shown.length ? `\n…另有 ${lines.length - shown.length} 项` : "";
87
+ return `${actorName} 更新了「${title}」:\n${shown.map((l) => `· ${l}`).join("\n")}${more}`;
88
+ }
89
+
90
+ type Pending = { messageId: string; startedAt: number; changes: Map<string, string> };
91
+ const pending = new Map<string, Pending>();
92
+
93
+ export function __resetRequirementNoticesForTest(): void { pending.clear(); }
94
+
95
+ /**
96
+ * 参与人(非负责人)改完一张卡之后调用(事务提交之后)。before / after = 改前改后的行。
97
+ * 不是参与人、或者状态和检查项都没变 → 什么都不发。返回这次通知到的收件人(测试用)。
98
+ */
99
+ export function notifyParticipantChange(input: { before: NoticeCard; after: NoticeCard; actorUserId: string; now?: number }): string[] {
100
+ const { before, after, actorUserId } = input;
101
+ if (!isParticipant(before, actorUserId)) return [];
102
+ if (userIdOf(parse(before.owner_json)) === actorUserId) return [];
103
+
104
+ const changes = describeChanges(before, after);
105
+ if (!changes.length) return [];
106
+ const now = input.now ?? Date.now();
107
+ // 用户名从库里取:MCP 入口的 auth.username 是空串。
108
+ const user = db.get<{ username: string; display_name: string | null }>("SELECT username, display_name FROM users WHERE user_id = ?1", actorUserId);
109
+ if (!user) return [];
110
+ const actorName = user.display_name?.trim() || user.username;
111
+ const sender = { userId: actorUserId, username: user.username };
112
+ const sent: string[] = [];
113
+ for (const target of noticeRecipients(after, actorUserId)) {
114
+ const key = `${target}\u0000${actorUserId}\u0000${after.requirement_id}`;
115
+ const prev = pending.get(key);
116
+ const live = prev && now - prev.startedAt < COALESCE_WINDOW_MS ? prev : null;
117
+ const merged = new Map(live?.changes ?? []);
118
+ for (const [k, line] of changes) { merged.delete(k); merged.set(k, line); }
119
+ const meta = JSON.stringify({ task_notice: { requirement_id: after.requirement_id, seq: after.seq ?? null, network_id: after.network_id } });
120
+ const base = { networkId: after.network_id, targetUserId: target, sender, title: "任务更新", metaJson: meta };
121
+ if (live && rewriteUnreadNoticeDm({ ...base, messageId: live.messageId, text: noticeText(actorName, after.title, [...merged.values()]) })) {
122
+ live.changes = merged;
123
+ sent.push(target);
124
+ continue;
125
+ }
126
+ const messageId = `dm_task_${uuidv4()}`;
127
+ const fresh = new Map(changes);
128
+ if (!sendNoticeDm({ ...base, messageId, text: noticeText(actorName, after.title, [...fresh.values()]) })) continue;
129
+ pending.set(key, { messageId, startedAt: now, changes: fresh });
130
+ sent.push(target);
131
+ }
132
+ if (pending.size > 5_000) for (const [k, p] of pending) if (now - p.startedAt >= COALESCE_WINDOW_MS) pending.delete(k);
133
+ return sent;
134
+ }
135
+
136
+ /**
137
+ * RFC-040 Q4:部门负责人(只凭负责人身份)删了本部门的一张卡 → 私信卡的负责人。
138
+ * 卡没有人类负责人时,私信负责 Agent 的主人(这张卡正是因为那个 Agent 才算「本部门的卡」)。
139
+ * 删的人就是收件人 / 收件人已不在网络 → 不发。返回收件人(测试用),没发 → null。
140
+ */
141
+ export function notifyLeaderDeleted(input: { card: NoticeCard & { agent_owner_json?: string | null }; actorUserId: string }): string | null {
142
+ const { card, actorUserId } = input;
143
+ let target = userIdOf(parse(card.owner_json));
144
+ if (!target) {
145
+ const agent = parse(card.agent_owner_json ?? null) as { kind?: unknown; id?: unknown } | null;
146
+ if (agent?.kind === "node" && typeof agent.id === "string") {
147
+ target = db.get<{ owner_user_id: string | null }>("SELECT owner_user_id FROM nodes WHERE node_id = ?1 AND network_id = ?2", agent.id, card.network_id)?.owner_user_id ?? null;
148
+ }
149
+ }
150
+ if (!target || target === actorUserId) return null;
151
+ const user = db.get<{ username: string; display_name: string | null }>("SELECT username, display_name FROM users WHERE user_id = ?1", actorUserId);
152
+ if (!user) return null;
153
+ const actorName = user.display_name?.trim() || user.username;
154
+ const number = card.seq ? ` #${card.seq}` : "";
155
+ const sent = sendNoticeDm({
156
+ networkId: card.network_id,
157
+ targetUserId: target,
158
+ sender: { userId: actorUserId, username: user.username },
159
+ title: "任务删除",
160
+ metaJson: JSON.stringify({ task_notice: { requirement_id: card.requirement_id, seq: card.seq ?? null, network_id: card.network_id, deleted: true } }),
161
+ messageId: `dm_task_${uuidv4()}`,
162
+ text: `${actorName}(部门负责人)删除了你负责的任务${number}「${card.title}」`,
163
+ });
164
+ return sent ? target : null;
165
+ }
@@ -0,0 +1,309 @@
1
+ // 参与人可以改任务的状态和检查项,改了通知相关的人(Vincent 2026-10-01)—— HTTP 集成测试(真实 Bun.serve,私有端口,临时库)。
2
+ // test2123 在真实 PostgreSQL 上原样再跑一遍(COMMHUB_TEST_PG_URL)。
3
+ //
4
+ // 网络 NET(owner = boss)。成员:
5
+ // owen —— 卡的负责人;cara —— 建卡的人(task_access='all');
6
+ // pat —— 参与人,scoped(只看相关任务);pia —— 另一个参与人(all);
7
+ // sam —— scoped,与卡无关(看不见)。
8
+ // 正向:pat 改状态 / 勾检查项 / 改检查项列表 → 200;owen、cara、pia 各收到一条私信(发信人 pat),pat 自己没有;
9
+ // 60 s 内连续改动并成一条(未读时改写正文);读过之后再改 → 新的一条;MCP 与 REST 一致。
10
+ // 反向:pat 改标题 / 描述 / 负责人 / 参与人 / 项目 / 优先级 / 日期 / 标签 → 403 task_read_only + field,卡不变、不通知;
11
+ // 负责人自己改不通知;sam 照旧看不见(与不存在的卡逐字节相同)。
12
+
13
+ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
14
+ import { mkdtempSync, rmSync } from "node:fs";
15
+ import { tmpdir } from "node:os";
16
+ import { join } from "node:path";
17
+
18
+ const DIR = mkdtempSync(join(tmpdir(), "anet-part-notify-"));
19
+ process.env.COMMHUB_DB ||= join(DIR, "hub.db");
20
+ process.env.COMMHUB_UPLOADS_DIR = join(DIR, "uploads");
21
+ process.env.HOST = "127.0.0.1";
22
+ const PW = "PartNotifyPassw0rd!x";
23
+
24
+ type U = { token: string; id: string; username: string };
25
+ let BASE = "";
26
+ let hub: any = null;
27
+ let NET = "";
28
+ let PROJ = "";
29
+ let db: any;
30
+ let notify: typeof import("./requirement-notify.js");
31
+ let boss: U, owen: U, cara: U, pat: U, pia: U, sam: U;
32
+
33
+ type R = { status: number; body: any; text: string };
34
+ async function send(token: string, method: string, path: string, payload?: unknown): Promise<R> {
35
+ const res = await fetch(`${BASE}${path}`, {
36
+ method,
37
+ headers: { ...(token ? { Authorization: `Bearer ${token}` } : {}), "Content-Type": "application/json" },
38
+ body: payload === undefined ? undefined : JSON.stringify(payload),
39
+ });
40
+ const text = await res.text();
41
+ let body: any = null;
42
+ try { body = JSON.parse(text); } catch {}
43
+ return { status: res.status, body, text };
44
+ }
45
+ async function mcp(token: string, name: string, args: Record<string, unknown>): Promise<any> {
46
+ const res = await fetch(`${BASE}/mcp`, {
47
+ method: "POST",
48
+ headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json", Accept: "application/json, text/event-stream", "MCP-Protocol-Version": "2025-03-26" },
49
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } }),
50
+ });
51
+ const raw = await res.text();
52
+ const lines = raw.split("\n").filter(x => x.startsWith("data:"));
53
+ const payload = lines.length ? JSON.parse(lines.at(-1)!.slice(5).trim()) : JSON.parse(raw);
54
+ return JSON.parse(payload.result.content[0].text);
55
+ }
56
+ const userRef = (id: string) => ({ kind: "user", id });
57
+
58
+ /** 某张卡发出的通知私信:按收件人分组(只看这张卡的,meta.task_notice.requirement_id)。 */
59
+ function notices(reqId: string): Record<string, Array<{ message_id: string; content: string; sender_user_id: string; acked: number; from_session: string }>> {
60
+ const rows = db.all(
61
+ "SELECT message_id, user_id, sender_user_id, from_session, content, acked, meta_json FROM user_inbox WHERE network_id = ?1 AND kind = 'human_dm' ORDER BY created_at, message_id",
62
+ NET,
63
+ ) as any[];
64
+ const out: Record<string, any[]> = {};
65
+ for (const r of rows) {
66
+ let meta: any = null;
67
+ try { meta = JSON.parse(r.meta_json); } catch {}
68
+ if (meta?.task_notice?.requirement_id !== reqId) continue;
69
+ (out[r.user_id] ||= []).push({ message_id: r.message_id, content: r.content, sender_user_id: r.sender_user_id, acked: Number(r.acked), from_session: r.from_session });
70
+ }
71
+ return out;
72
+ }
73
+
74
+ async function card(name: string, extra: Record<string, unknown> = {}) {
75
+ const r = await send(cara.token, "POST", "/api/requirements", {
76
+ network_id: NET, name, owner: userRef(owen.id), participants: [userRef(pat.id), userRef(pia.id)],
77
+ checklist: [{ id: "i1", text: "写测试", done: false }, { id: "i2", text: "发版", done: false }], ...extra,
78
+ });
79
+ expect(r.status).toBe(201);
80
+ return r.body.requirement.id as string;
81
+ }
82
+
83
+ beforeAll(async () => {
84
+ ({ db } = await import("./db.js"));
85
+ const { addNetworkMember, register } = await import("./auth.js");
86
+ const stamp = Date.now();
87
+ const mk = (name: string, display?: string): U => {
88
+ const r = register(`pn_${name}_${stamp}`, PW, undefined, display);
89
+ expect(r.ok).toBe(true);
90
+ return { token: r.token!, id: r.user!.user_id, username: r.user!.username };
91
+ };
92
+ const b = register(`pn_boss_${stamp}`, PW);
93
+ expect(b.ok).toBe(true);
94
+ boss = { token: b.token!, id: b.user!.user_id, username: b.user!.username };
95
+ NET = b.network_id!;
96
+ owen = mk("owen"); cara = mk("cara"); pat = mk("pat", "参与人甲"); pia = mk("pia"); sam = mk("sam");
97
+ addNetworkMember(NET, owen.id, "member", boss.id, { taskAccess: "all" });
98
+ addNetworkMember(NET, cara.id, "member", boss.id, { taskAccess: "all" });
99
+ addNetworkMember(NET, pat.id, "member", boss.id, { taskAccess: "scoped" });
100
+ addNetworkMember(NET, pia.id, "member", boss.id, { taskAccess: "all" });
101
+ addNetworkMember(NET, sam.id, "member", boss.id, { taskAccess: "scoped" });
102
+ notify = await import("./requirement-notify.js");
103
+ const mod: any = await import("./server.js");
104
+ hub = mod.bootServer({ port: 0, hostname: "127.0.0.1" });
105
+ BASE = `http://127.0.0.1:${hub.port}`;
106
+ // register() 给每人建了自己的网络:后面的请求一律带 network_id。
107
+ const p = await send(boss.token, "POST", "/api/requirements/projects", { network_id: NET, name: "pn-proj" });
108
+ expect(p.status).toBe(201);
109
+ PROJ = p.body.project.id;
110
+ }, 30_000);
111
+
112
+ afterAll(() => {
113
+ try { hub?.stop?.(true); } catch {}
114
+ try { rmSync(DIR, { recursive: true, force: true }); } catch {}
115
+ });
116
+
117
+ describe("参与人能改的", () => {
118
+ test("改状态:200,负责人 / 创建者 / 其他参与人各一条,操作者自己没有", async () => {
119
+ const id = await card("pn-状态");
120
+ const r = await send(pat.token, "PATCH", `/api/requirements/${id}?network_id=${NET}`, { column: "doing" });
121
+ expect(r.status).toBe(200);
122
+ expect(r.body.requirement.column).toBe("doing");
123
+ const n = notices(id);
124
+ expect(Object.keys(n).sort()).toEqual([owen.id, cara.id, pia.id].sort());
125
+ for (const uid of [owen.id, cara.id, pia.id]) {
126
+ expect(n[uid].length).toBe(1);
127
+ expect(n[uid][0].sender_user_id).toBe(pat.id);
128
+ expect(n[uid][0].from_session).toBe(pat.username);
129
+ expect(n[uid][0].content).toBe("参与人甲 把「pn-状态」改为 进行中");
130
+ }
131
+ expect(n[pat.id]).toBeUndefined();
132
+ });
133
+
134
+ test("勾检查项(单条接口):200 并通知", async () => {
135
+ const id = await card("pn-勾选");
136
+ const r = await send(pat.token, "PATCH", `/api/requirements/${id}/checklist/i1?network_id=${NET}`, { done: true });
137
+ expect(r.status).toBe(200);
138
+ expect(r.body.requirement.checklist.find((x: any) => x.id === "i1").done).toBe(true);
139
+ expect(notices(id)[owen.id].map(x => x.content)).toEqual(["参与人甲 在「pn-勾选」勾选了检查项「写测试」"]);
140
+ });
141
+
142
+ test("整表改检查项(增 / 删 / 改字)+ 状态:一次 PATCH 一条通知,逐项列出", async () => {
143
+ const id = await card("pn-整表");
144
+ const r = await send(pat.token, "PATCH", `/api/requirements/${id}?network_id=${NET}`, {
145
+ column: "done", checklist: [{ id: "i1", text: "写更多测试", done: false }, { id: "i3", text: "回归", done: false }],
146
+ });
147
+ expect(r.status).toBe(200);
148
+ const n = notices(id)[cara.id];
149
+ expect(n.length).toBe(1);
150
+ expect(n[0].content).toBe("参与人甲 更新了「pn-整表」:\n· 改为 完成\n· 把检查项「写测试」改为「写更多测试」\n· 添加了检查项「回归」\n· 删除了检查项「发版」");
151
+ });
152
+
153
+ test("60 s 内连续勾选并成一条(未读时改写正文);同一项先勾再取消只留最后一次", async () => {
154
+ const id = await card("pn-合并");
155
+ for (const [item, done] of [["i1", true], ["i2", true], ["i1", false]] as const) {
156
+ expect((await send(pat.token, "PATCH", `/api/requirements/${id}/checklist/${item}?network_id=${NET}`, { done })).status).toBe(200);
157
+ }
158
+ const n = notices(id);
159
+ for (const uid of [owen.id, cara.id, pia.id]) {
160
+ expect(n[uid].length).toBe(1);
161
+ expect(n[uid][0].content).toBe("参与人甲 更新了「pn-合并」:\n· 勾选了检查项「发版」\n· 取消勾选了检查项「写测试」");
162
+ }
163
+ });
164
+
165
+ test("收件人读过之后再改 → 另发一条;别人那条仍在合并", async () => {
166
+ const id = await card("pn-已读");
167
+ expect((await send(pat.token, "PATCH", `/api/requirements/${id}/checklist/i1?network_id=${NET}`, { done: true })).status).toBe(200);
168
+ db.run("UPDATE user_inbox SET acked = 1 WHERE user_id = ?1 AND message_id = ?2", [owen.id, notices(id)[owen.id][0].message_id]);
169
+ expect((await send(pat.token, "PATCH", `/api/requirements/${id}/checklist/i2?network_id=${NET}`, { done: true })).status).toBe(200);
170
+ const n = notices(id);
171
+ expect(n[owen.id].length).toBe(2);
172
+ expect(n[owen.id][1].content).toBe("参与人甲 在「pn-已读」勾选了检查项「发版」");
173
+ expect(n[cara.id].length).toBe(1);
174
+ });
175
+
176
+ test("过了合并窗口 → 另发一条", async () => {
177
+ const id = await card("pn-窗口");
178
+ const row = (col: string, ck: boolean) => ({
179
+ requirement_id: id, network_id: NET, seq: null, title: "pn-窗口", column_name: col,
180
+ checklist_json: JSON.stringify([{ id: "i1", text: "写测试", done: ck }]),
181
+ owner_json: JSON.stringify(userRef(owen.id)), participants_json: JSON.stringify([userRef(pat.id)]),
182
+ created_by: null, created_by_json: JSON.stringify(userRef(cara.id)),
183
+ });
184
+ const t0 = Date.now();
185
+ expect(notify.notifyParticipantChange({ before: row("pool", false), after: row("pool", true), actorUserId: pat.id, now: t0 }).sort()).toEqual([owen.id, cara.id].sort());
186
+ notify.notifyParticipantChange({ before: row("pool", true), after: row("doing", true), actorUserId: pat.id, now: t0 + notify.COALESCE_WINDOW_MS - 1 });
187
+ expect(notices(id)[owen.id].length).toBe(1);
188
+ notify.notifyParticipantChange({ before: row("doing", true), after: row("done", true), actorUserId: pat.id, now: t0 + notify.COALESCE_WINDOW_MS + 1 });
189
+ expect(notices(id)[owen.id].length).toBe(2);
190
+ });
191
+
192
+ test("推送:收件人的用户流收到 desktop_message(kind=human_dm,发信人 = 参与人)", async () => {
193
+ const id = await card("pn-推送");
194
+ const ctrl = new AbortController();
195
+ const res = await fetch(`${BASE}/events/users/me?network_id=${NET}`, { headers: { Authorization: `Bearer ${owen.token}` }, signal: ctrl.signal });
196
+ expect(res.status).toBe(200);
197
+ const events: any[] = [];
198
+ const reader = res.body!.getReader();
199
+ const dec = new TextDecoder();
200
+ let buf = "";
201
+ void (async () => {
202
+ try {
203
+ for (;;) {
204
+ const { done, value } = await reader.read();
205
+ if (done) break;
206
+ buf += dec.decode(value);
207
+ let i: number;
208
+ while ((i = buf.indexOf("\n\n")) >= 0) {
209
+ const frame = buf.slice(0, i); buf = buf.slice(i + 2);
210
+ for (const line of frame.split("\n")) if (line.startsWith("data: ")) { try { events.push(JSON.parse(line.slice(6))); } catch {} }
211
+ }
212
+ }
213
+ } catch {}
214
+ })();
215
+ const until = async (cond: () => boolean) => { for (let k = 0; k < 150 && !cond(); k++) await new Promise(r => setTimeout(r, 20)); };
216
+ await until(() => events.some(e => e.type === "connected"));
217
+ expect((await send(pat.token, "PATCH", `/api/requirements/${id}?network_id=${NET}`, { column: "doing" })).status).toBe(200);
218
+ await until(() => events.some(e => e.type === "desktop_message"));
219
+ ctrl.abort();
220
+ const ev = events.find(e => e.type === "desktop_message");
221
+ expect(ev).toMatchObject({ kind: "human_dm", from: pat.username, from_user_id: pat.id, title: "任务更新", message: "参与人甲 把「pn-推送」改为 进行中" });
222
+ expect(ev.meta.task_notice.requirement_id).toBe(id);
223
+ });
224
+
225
+ test("MCP 与 REST 一致:requirements_update 改状态能过并通知,改标题被拒", async () => {
226
+ const id = await card("pn-mcp");
227
+ const ok = await mcp(pat.token, "requirements_update", { id, network_id: NET, column: "doing" });
228
+ expect(ok.ok).toBe(true);
229
+ expect(notices(id)[owen.id][0].content).toBe("参与人甲 把「pn-mcp」改为 进行中");
230
+ expect(notices(id)[owen.id][0].from_session).toBe(pat.username);
231
+ const no = await mcp(pat.token, "requirements_update", { id, network_id: NET, name: "改名" });
232
+ expect(no).toMatchObject({ ok: false, error: "task_read_only", field: "name", status: 403 });
233
+ const tog = await mcp(pat.token, "requirements_checklist_toggle", { id, network_id: NET, item_id: "i2", done: true });
234
+ expect(tog.ok).toBe(true);
235
+ });
236
+
237
+ test("viewer_can:参与人带 edit_fields;负责人不带", async () => {
238
+ const id = await card("pn-权限");
239
+ const mine = await send(pat.token, "GET", `/api/requirements/${id}?network_id=${NET}`);
240
+ expect(mine.body.requirement.viewer_can).toEqual({ edit: false, delete: false, edit_fields: ["column", "checklist"] });
241
+ });
242
+ });
243
+
244
+ describe("参与人不能改的", () => {
245
+ test("标题 / 描述 / 负责人 / 负责 Agent / 参与人 / 项目 / 优先级 / 日期 / 标签:403 task_read_only + field;卡不变、不通知", async () => {
246
+ const id = await card("pn-拒绝");
247
+ const before = (await send(cara.token, "GET", `/api/requirements/${id}?network_id=${NET}`)).body.requirement;
248
+ const cases: Array<[string, unknown]> = [
249
+ ["name", "改名"], ["description", "x"], ["owner", userRef(pat.id)], ["agent_owner", null], ["participants", [userRef(pat.id)]],
250
+ ["project_id", PROJ], ["priority", "high"], ["due", "2026-12-31"], ["start", "2026-12-01"], ["tags", ["t"]], ["archived", true], ["parent_id", null],
251
+ ];
252
+ for (const [field, value] of cases) {
253
+ const r = await send(pat.token, "PATCH", `/api/requirements/${id}?network_id=${NET}`, { [field]: value });
254
+ expect(r.status).toBe(403);
255
+ expect(r.body.ok).toBe(false);
256
+ expect(r.body.error).toBe("task_read_only");
257
+ expect(r.body.field).toBe(field);
258
+ expect(typeof r.body.message).toBe("string");
259
+ }
260
+ // 混着能改的字段一起发:整条拒绝,状态也不动。
261
+ const mixed = await send(pat.token, "PATCH", `/api/requirements/${id}?network_id=${NET}`, { column: "doing", name: "改名" });
262
+ expect(mixed.status).toBe(403);
263
+ expect(mixed.body.field).toBe("name");
264
+ const after = (await send(cara.token, "GET", `/api/requirements/${id}?network_id=${NET}`)).body.requirement;
265
+ expect(after).toEqual(before);
266
+ expect(notices(id)).toEqual({});
267
+ });
268
+
269
+ test("负责人 / 创建者自己改:不通知;删除仍不行", async () => {
270
+ const id = await card("pn-负责人");
271
+ expect((await send(owen.token, "PATCH", `/api/requirements/${id}?network_id=${NET}`, { column: "doing" })).status).toBe(200);
272
+ expect((await send(cara.token, "PATCH", `/api/requirements/${id}/checklist/i1?network_id=${NET}`, { done: true })).status).toBe(200);
273
+ expect(notices(id)).toEqual({});
274
+ expect((await send(pat.token, "DELETE", `/api/requirements/${id}?network_id=${NET}`)).status).toBe(403);
275
+ });
276
+
277
+ test("负责人同时是参与人:改了也不通知", async () => {
278
+ const id = await card("pn-兼任", { owner: userRef(pat.id), participants: [userRef(pat.id), userRef(pia.id)] });
279
+ expect((await send(pat.token, "PATCH", `/api/requirements/${id}?network_id=${NET}`, { column: "doing" })).status).toBe(200);
280
+ expect(notices(id)).toEqual({});
281
+ });
282
+
283
+ test("只看相关任务的无关成员:看不见、改不了(与不存在的卡逐字节相同),也收不到通知", async () => {
284
+ const id = await card("pn-无关");
285
+ const list = await send(sam.token, "GET", `/api/requirements?network_id=${NET}`);
286
+ expect((list.body.requirements as any[]).some(x => x.id === id)).toBe(false);
287
+ const hidden = await send(sam.token, "PATCH", `/api/requirements/${id}?network_id=${NET}`, { column: "doing" });
288
+ const ghost = await send(sam.token, "PATCH", `/api/requirements/req_does_not_exist?network_id=${NET}`, { column: "doing" });
289
+ expect(hidden.status).toBe(404);
290
+ expect(hidden.text).toBe(ghost.text);
291
+ const hiddenCk = await send(sam.token, "PATCH", `/api/requirements/${id}/checklist/i1?network_id=${NET}`, { done: true });
292
+ expect(hiddenCk.status).toBe(404);
293
+ expect((await send(pat.token, "PATCH", `/api/requirements/${id}?network_id=${NET}`, { column: "doing" })).status).toBe(200);
294
+ expect(notices(id)[sam.id]).toBeUndefined();
295
+ });
296
+ });
297
+
298
+ describe("收件人(纯函数)", () => {
299
+ test("只要人、去重、去掉操作者;旧卡没有 created_by_json 时用 created_by", () => {
300
+ const base = {
301
+ requirement_id: "r", network_id: NET, seq: 1, title: "t", column_name: "pool", checklist_json: null,
302
+ owner_json: JSON.stringify(userRef("u-owner")),
303
+ participants_json: JSON.stringify([userRef("u-actor"), userRef("u-owner"), { kind: "node", id: "n-1" }, userRef("u-other")]),
304
+ created_by: null, created_by_json: JSON.stringify({ kind: "node", id: "n-2" }),
305
+ };
306
+ expect(notify.noticeRecipients(base, "u-actor").sort()).toEqual(["u-other", "u-owner"]);
307
+ expect(notify.noticeRecipients({ ...base, created_by_json: null, created_by: "u-legacy" }, "u-actor").sort()).toEqual(["u-legacy", "u-other", "u-owner"]);
308
+ });
309
+ });