@sleep2agi/commhub-server 0.9.0-preview.23 → 0.9.0-preview.231

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 (408) hide show
  1. package/README.md +129 -9
  2. package/bin/commhub.ts +93 -9
  3. package/package.json +7 -7
  4. package/src/ack-create-request-transport.test.ts +182 -0
  5. package/src/ack-create-request.test.ts +50 -7
  6. package/src/admin-delete-network-http.test.ts +228 -0
  7. package/src/admin-networks-http.test.ts +88 -0
  8. package/src/adoption-candidates-http.test.ts +137 -0
  9. package/src/adoption-candidates.ts +158 -0
  10. package/src/agent-access-batch.test.ts +210 -0
  11. package/src/agent-access.ts +487 -0
  12. package/src/agent-acl-groups-http.test.ts +247 -0
  13. package/src/agent-acl-http.test.ts +659 -0
  14. package/src/agent-acl-slice3-http.test.ts +654 -0
  15. package/src/agent-department-http.test.ts +215 -0
  16. package/src/agent-groups-perf.test.ts +223 -0
  17. package/src/agent-notice.ts +48 -0
  18. package/src/agent-team-whoami-http.test.ts +98 -0
  19. package/src/agent-teams-http.test.ts +330 -0
  20. package/src/agent-teams.ts +244 -0
  21. package/src/alias-baseline-2571.test.ts +162 -0
  22. package/src/alias-baseline.ts +113 -0
  23. package/src/alias-filter.test.ts +72 -0
  24. package/src/alias-filter.ts +42 -0
  25. package/src/api-host-supervisors-can-create-nodes.test.ts +350 -0
  26. package/src/api-host-supervisors-fallback.test.ts +6 -7
  27. package/src/api-host-supervisors-runtime-readiness.test.ts +195 -0
  28. package/src/api-nodes-shape.test.ts +95 -4
  29. package/src/auth-password-change-cli-tokens-http.test.ts +423 -0
  30. package/src/auth-sessions-http.test.ts +250 -0
  31. package/src/auth-validate.test.ts +5 -1
  32. package/src/auth-weak-password-login.test.ts +176 -0
  33. package/src/auth.ts +609 -51
  34. package/src/avatar-validate.test.ts +52 -2
  35. package/src/avatar-validate.ts +35 -1
  36. package/src/backfill-node-ids-2664.test.ts +128 -0
  37. package/src/binding-generation-http.test.ts +121 -0
  38. package/src/blocked-exit-on-reply.test.ts +122 -0
  39. package/src/broadcast-fanout-2721.test.ts +149 -0
  40. package/src/broadcast-fanout.ts +117 -0
  41. package/src/chain-attempt-dedup.test.ts +447 -0
  42. package/src/clip.test.ts +36 -0
  43. package/src/clip.ts +46 -0
  44. package/src/clone-node.test.ts +248 -0
  45. package/src/clone-node.ts +289 -0
  46. package/src/codex-config-flags.ts +77 -0
  47. package/src/codex-fork-contract.ts +23 -0
  48. package/src/codex-fork-migration.test.ts +38 -0
  49. package/src/commhub-bin-args.test.ts +85 -0
  50. package/src/config-apply-validate.test.ts +188 -1
  51. package/src/config-apply-validate.ts +222 -3
  52. package/src/cors-origins.test.ts +73 -0
  53. package/src/create-node-blocked-gate.test.ts +356 -0
  54. package/src/create-node-network-id.test.ts +91 -0
  55. package/src/create-node-tool-schema.test.ts +49 -0
  56. package/src/create-node-unicode-name.test.ts +120 -0
  57. package/src/create-node-validate.test.ts +199 -7
  58. package/src/create-node-validate.ts +232 -15
  59. package/src/create-node-workdir.test.ts +289 -0
  60. package/src/create-node.ts +88 -23
  61. package/src/daemon-provider-snapshots.test.ts +421 -0
  62. package/src/daemon-provider-snapshots.ts +327 -0
  63. package/src/daemon-token-owner-http.test.ts +236 -0
  64. package/src/dashboard-slash-routing-http.test.ts +109 -0
  65. package/src/db-adapter-guard.test.ts +148 -0
  66. package/src/db-adapter-translate.test.ts +128 -0
  67. package/src/db-adapter.ts +377 -91
  68. package/src/db-timestamp.test.ts +38 -0
  69. package/src/db-timestamp.ts +15 -0
  70. package/src/db.ts +1264 -153
  71. package/src/delivered-without-push.test.ts +140 -0
  72. package/src/department-groups-http.test.ts +209 -0
  73. package/src/department-groups-sync-http.test.ts +328 -0
  74. package/src/department-groups.ts +434 -0
  75. package/src/department-heads-http.test.ts +350 -0
  76. package/src/department-heads.ts +226 -0
  77. package/src/departments-agent-count.test.ts +132 -0
  78. package/src/departments-http.test.ts +185 -0
  79. package/src/departments-mcp.test.ts +128 -0
  80. package/src/departments.ts +318 -0
  81. package/src/desktop-message-seam.test.ts +150 -0
  82. package/src/desktop-message.test.ts +368 -0
  83. package/src/dm-file-scope-http.test.ts +178 -0
  84. package/src/empty-node-sweeper.test.ts +104 -0
  85. package/src/empty-node-sweeper.ts +88 -0
  86. package/src/env-transport-gate-http.test.ts +240 -0
  87. package/src/env-transport-gate.ts +80 -0
  88. package/src/env-transport-policy.ts +56 -0
  89. package/src/etag-of.test.ts +57 -0
  90. package/src/event-loop-lag.test.ts +180 -0
  91. package/src/event-loop-lag.ts +201 -0
  92. package/src/ext-token-shared.test.ts +60 -0
  93. package/src/ext-validation-regression.test.ts +131 -0
  94. package/src/external-schedule-edits-http.test.ts +321 -0
  95. package/src/external-schedule-edits-timestamps.test.ts +64 -0
  96. package/src/external-schedule-edits.ts +327 -0
  97. package/src/file-download-authz-dev-open.test.ts +1 -1
  98. package/src/file-download-authz.test.ts +73 -18
  99. package/src/file-download-date-bucket.test.ts +436 -0
  100. package/src/file-network-scope-dev-open.test.ts +97 -0
  101. package/src/file-network-scope.test.ts +732 -0
  102. package/src/group-membership-events-http.test.ts +264 -0
  103. package/src/group-messages-http.test.ts +482 -0
  104. package/src/group-messages.ts +297 -0
  105. package/src/health-anon-readers.ts +60 -0
  106. package/src/health-host-disk-2756.test.ts +71 -0
  107. package/src/health-redaction.test.ts +1740 -2
  108. package/src/host-supervisor-identity-http.test.ts +152 -0
  109. package/src/host-supervisor-identity.ts +92 -0
  110. package/src/host-supervisors-daemon-version.test.ts +137 -0
  111. package/src/http-gzip.test.ts +94 -0
  112. package/src/http-gzip.ts +112 -0
  113. package/src/hub-catalog-read-http.test.ts +437 -0
  114. package/src/hub-provider-config.test.ts +156 -0
  115. package/src/hub-provider-config.ts +170 -0
  116. package/src/hub-timestamp.test.ts +38 -0
  117. package/src/hub-timestamp.ts +27 -0
  118. package/src/human-dm.ts +215 -0
  119. package/src/human-inbox.ts +42 -0
  120. package/src/inbox-caller.ts +49 -0
  121. package/src/inbox-count-sse.test.ts +310 -0
  122. package/src/inbox-count.ts +29 -0
  123. package/src/index.ts +6 -2
  124. package/src/license-state.test.ts +56 -0
  125. package/src/license-state.ts +48 -0
  126. package/src/list-host-supervisors.test.ts +15 -4
  127. package/src/mcp-context-cost-http.test.ts +127 -0
  128. package/src/mcp-inflight.test.ts +92 -0
  129. package/src/mcp-inflight.ts +38 -0
  130. package/src/mcp-projects-events-http.test.ts +165 -0
  131. package/src/mcp-route-label-http.test.ts +120 -0
  132. package/src/mcp-write-network-resolution.test.ts +435 -0
  133. package/src/member-audit-network-id-http.test.ts +93 -0
  134. package/src/member-presence-http.test.ts +210 -0
  135. package/src/messages-ack-by-agent-http.test.ts +142 -0
  136. package/src/migrate-sqlite-to-pg.test.ts +47 -0
  137. package/src/migrate-sqlite-to-pg.ts +263 -0
  138. package/src/model-auth-notify-http.test.ts +181 -0
  139. package/src/model-auth-notify.ts +116 -0
  140. package/src/network-name-http.test.ts +75 -0
  141. package/src/network-rules-http.test.ts +169 -0
  142. package/src/network-rules.ts +129 -0
  143. package/src/network-scope.ts +276 -0
  144. package/src/network-token-membership-http.test.ts +139 -0
  145. package/src/node-alias-control.ts +12 -0
  146. package/src/node-attrs.test.ts +47 -2
  147. package/src/node-caller-identity-http.test.ts +1091 -0
  148. package/src/node-create-request-status-http.test.ts +105 -0
  149. package/src/node-daemon-bindings.test.ts +132 -0
  150. package/src/node-daemon-bindings.ts +135 -0
  151. package/src/node-failure-alert.test.ts +150 -0
  152. package/src/node-failure-alert.ts +177 -0
  153. package/src/node-files-transport.test.ts +344 -0
  154. package/src/node-health-codex-login.test.ts +120 -0
  155. package/src/node-health-dispatch-http.test.ts +335 -0
  156. package/src/node-health-guard.ts +121 -0
  157. package/src/node-health-passthrough.test.ts +115 -0
  158. package/src/node-health-store.ts +101 -0
  159. package/src/node-id-alias.test.ts +190 -0
  160. package/src/node-identity-conflict-http.test.ts +269 -0
  161. package/src/node-identity-conflict.ts +142 -0
  162. package/src/node-identity-mismatch.test.ts +74 -0
  163. package/src/node-in-flight-tasks.ts +31 -0
  164. package/src/node-lifecycle-controllable.test.ts +64 -0
  165. package/src/node-lifecycle-controllable.ts +53 -0
  166. package/src/node-lifecycle-read-http.test.ts +250 -0
  167. package/src/node-lifecycle-read.ts +124 -0
  168. package/src/node-logs-transport.test.ts +263 -0
  169. package/src/node-peer-allowlist.test.ts +114 -0
  170. package/src/node-permissions-http.test.ts +728 -0
  171. package/src/node-permissions.ts +494 -0
  172. package/src/node-request-retention.test.ts +281 -0
  173. package/src/node-request-retention.ts +120 -0
  174. package/src/node-secret-rest-http.test.ts +190 -0
  175. package/src/node-serviceability.test.ts +86 -0
  176. package/src/node-serviceability.ts +124 -0
  177. package/src/node-session-control-http.test.ts +310 -0
  178. package/src/node-session-control.ts +258 -0
  179. package/src/node-skills-transport.test.ts +212 -0
  180. package/src/node-token-identity.ts +35 -0
  181. package/src/node-token-ownership.ts +51 -0
  182. package/src/node-token-privilege-http.test.ts +158 -0
  183. package/src/not-found-api-http.test.ts +67 -0
  184. package/src/observer-avatar-http.test.ts +102 -9
  185. package/src/observer-push.test.ts +76 -0
  186. package/src/opencode-catalog-report-http.test.ts +139 -0
  187. package/src/opencode-v2-catalog.test.ts +268 -0
  188. package/src/opencode-v2-catalog.ts +356 -0
  189. package/src/package-version-consistency.test.ts +25 -0
  190. package/src/parent-source-marker.test.ts +50 -0
  191. package/src/password-network-tokens.ts +25 -0
  192. package/src/peer-reply-atomic.test.ts +457 -0
  193. package/src/peer-reply-capability.test.ts +70 -0
  194. package/src/pg-worker.ts +87 -0
  195. package/src/poll-pacing.test.ts +74 -0
  196. package/src/poll-pacing.ts +123 -0
  197. package/src/project-dir-warn-clear-http.test.ts +132 -0
  198. package/src/project-viewer-can-http.test.ts +116 -0
  199. package/src/push.test.ts +20 -10
  200. package/src/push.ts +382 -9
  201. package/src/redact-tokens.test.ts +86 -0
  202. package/src/redact-tokens.ts +43 -0
  203. package/src/rejection-counters.test.ts +72 -0
  204. package/src/rejection-counters.ts +173 -0
  205. package/src/rename.ts +38 -10
  206. package/src/reply-target-derivation.test.ts +96 -0
  207. package/src/report-status-handover-capabilities-http.test.ts +124 -0
  208. package/src/report-status-host-schema.test.ts +235 -0
  209. package/src/report-status-resume-id-handover.test.ts +184 -0
  210. package/src/report-status-secret-keys.test.ts +140 -0
  211. package/src/require-explicit-test-db.ts +9 -0
  212. package/src/requirement-due-reminders-http.test.ts +620 -0
  213. package/src/requirement-due-reminders.ts +416 -0
  214. package/src/requirement-events-http.test.ts +295 -0
  215. package/src/requirement-events.test.ts +45 -0
  216. package/src/requirement-events.ts +144 -0
  217. package/src/requirement-notify.ts +165 -0
  218. package/src/requirement-participant-notify-http.test.ts +309 -0
  219. package/src/requirement-tag-ops-http.test.ts +443 -0
  220. package/src/requirement-tag-tree-http.test.ts +275 -0
  221. package/src/requirement-tag-tree.ts +127 -0
  222. package/src/requirement-tags.ts +102 -0
  223. package/src/requirements-abandoned-http.test.ts +236 -0
  224. package/src/requirements-comment-http.test.ts +167 -0
  225. package/src/requirements-completed-at-migration.test.ts +70 -0
  226. package/src/requirements-errors-mcp-http.test.ts +164 -0
  227. package/src/requirements-errors.ts +158 -0
  228. package/src/requirements-etag-http.test.ts +91 -0
  229. package/src/requirements-http.test.ts +709 -0
  230. package/src/requirements-last-event-http.test.ts +349 -0
  231. package/src/requirements-list-mcp-slim-http.test.ts +155 -0
  232. package/src/requirements-list-slim-http.test.ts +324 -0
  233. package/src/requirements-mcp.test.ts +163 -0
  234. package/src/requirements-migrate.ts +283 -0
  235. package/src/requirements-owner-strict-mcp-http.test.ts +145 -0
  236. package/src/requirements-people-http.test.ts +114 -0
  237. package/src/requirements-people-mcp-http.test.ts +231 -0
  238. package/src/requirements-people.ts +196 -0
  239. package/src/requirements-priority-lowest.test.ts +114 -0
  240. package/src/requirements-projects-network-echo.test.ts +57 -0
  241. package/src/requirements-projects-parent-http.test.ts +123 -0
  242. package/src/requirements-search-http.test.ts +182 -0
  243. package/src/requirements-search.test.ts +32 -0
  244. package/src/requirements-search.ts +145 -0
  245. package/src/requirements-seq-http.test.ts +193 -0
  246. package/src/requirements-seq-migration.test.ts +63 -0
  247. package/src/requirements-start-date.test.ts +125 -0
  248. package/src/requirements-stats-http.test.ts +357 -0
  249. package/src/requirements-stats.ts +195 -0
  250. package/src/requirements-status-participants-http.test.ts +222 -0
  251. package/src/requirements-upgrade-e2e.test.ts +126 -0
  252. package/src/requirements-upgrade-migration.test.ts +98 -0
  253. package/src/requirements.ts +2064 -0
  254. package/src/resolve-port.test.ts +57 -0
  255. package/src/resolve-port.ts +44 -0
  256. package/src/rest-alias-network-fallback-http.test.ts +123 -0
  257. package/src/rest-alias-network-fallback.test.ts +60 -0
  258. package/src/rest-alias-network-fallback.ts +65 -0
  259. package/src/rest-explicit-columns-http.test.ts +266 -0
  260. package/src/rest-identity.test.ts +130 -0
  261. package/src/rest-identity.ts +141 -0
  262. package/src/rest-projections.ts +72 -0
  263. package/src/rest-read-network-real-chain.test.ts +97 -0
  264. package/src/rest-write-network-resolution.test.ts +133 -0
  265. package/src/restart-readiness-http.test.ts +121 -0
  266. package/src/restricted-files.ts +76 -0
  267. package/src/retention-first-sweep-quiet.test.ts +31 -0
  268. package/src/retention.test.ts +100 -40
  269. package/src/retention.ts +423 -104
  270. package/src/route-callers-http.test.ts +120 -0
  271. package/src/route-timing.test.ts +218 -0
  272. package/src/route-timing.ts +262 -0
  273. package/src/rules-file-duplicate-alias.test.ts +234 -0
  274. package/src/rules-file-session-target.test.ts +207 -0
  275. package/src/rules-file-transport.test.ts +237 -0
  276. package/src/runtime-label.test.ts +22 -0
  277. package/src/runtime-label.ts +21 -0
  278. package/src/runtime-readiness.ts +90 -0
  279. package/src/schedule-agent-mcp-http.test.ts +432 -0
  280. package/src/schedule-agent.ts +252 -0
  281. package/src/schedule-starved.test.ts +92 -0
  282. package/src/schedule-starved.ts +114 -0
  283. package/src/scheduled-backoff-http.test.ts +193 -0
  284. package/src/scheduled-backoff.ts +64 -0
  285. package/src/scheduled-doorbell-nodeless-session.test.ts +134 -0
  286. package/src/scheduled-failure-backoff-2622.test.ts +145 -0
  287. package/src/scheduled-failure-code.test.ts +73 -0
  288. package/src/scheduled-failure-code.ts +105 -0
  289. package/src/scheduled-failures-http.test.ts +279 -0
  290. package/src/scheduled-failures.ts +425 -0
  291. package/src/scheduled-noprogress-backoff-2622.test.ts +163 -0
  292. package/src/scheduled-offline-backoff-probe.test.ts +56 -0
  293. package/src/scheduled-offline.test.ts +131 -0
  294. package/src/scheduled-offline.ts +66 -0
  295. package/src/scheduled-outcome-guidance-http.test.ts +139 -0
  296. package/src/scheduled-outcome-guidance.ts +9 -0
  297. package/src/scheduled-reply-unread-http.test.ts +212 -0
  298. package/src/scheduled-requirement-wake-http.test.ts +279 -0
  299. package/src/scheduled-requirement-wake.ts +125 -0
  300. package/src/scheduled-run-terminal.test.ts +268 -0
  301. package/src/scheduled-skip-blocking-task.test.ts +120 -0
  302. package/src/scheduled-skip-path-backoff-2622.test.ts +98 -0
  303. package/src/scheduled-stuck-http.test.ts +316 -0
  304. package/src/scheduled-stuck-notice-cap.test.ts +80 -0
  305. package/src/scheduled-stuck.ts +219 -0
  306. package/src/scheduled-tasks-http.test.ts +679 -0
  307. package/src/scheduled-tasks.ts +959 -0
  308. package/src/scheduled-work-outcome-http.test.ts +154 -0
  309. package/src/scheduled-work-outcome.ts +50 -0
  310. package/src/scoped-secrets.ts +141 -0
  311. package/src/send-dedup-request-id.test.ts +229 -0
  312. package/src/send-reply-agent-warning.test.ts +38 -38
  313. package/src/send-reply-alias-optional.test.ts +131 -0
  314. package/src/send-reply-attachments.test.ts +458 -0
  315. package/src/send_dedup.test.ts +54 -0
  316. package/src/send_dedup.ts +52 -6
  317. package/src/serve-error.test.ts +73 -0
  318. package/src/serve-error.ts +56 -0
  319. package/src/server.ts +5035 -457
  320. package/src/session-task-on-dispatch.ts +14 -0
  321. package/src/session-token-ownership-http.test.ts +122 -0
  322. package/src/shared/codex-inventory.ts +41 -0
  323. package/src/shared/daemon-provider-login.ts +31 -0
  324. package/src/shared/daemon-provider-snapshot.ts +52 -0
  325. package/src/shared/external-schedule-contract.ts +60 -0
  326. package/src/shared/node-name.test.ts +62 -0
  327. package/src/shared/node-name.ts +161 -0
  328. package/src/shared/probe-host-allowlist-drift.test.ts +45 -0
  329. package/src/shared/provider-application.ts +29 -0
  330. package/src/shared/provider-collection.ts +14 -0
  331. package/src/shared/provider-initialization.ts +8 -0
  332. package/src/shared/reserved-env-drift.test.ts +10 -0
  333. package/src/shared/scoped-secret-contract.ts +5 -0
  334. package/src/shared/task-content-limit-drift.test.ts +28 -0
  335. package/src/shared/task-content-limit.ts +25 -0
  336. package/src/side-thread-command-transport.test.ts +312 -0
  337. package/src/side-thread-command-transport.ts +318 -0
  338. package/src/side-thread-http-integration.test.ts +233 -0
  339. package/src/side-thread-http.ts +504 -0
  340. package/src/side-thread-production.test.ts +72 -0
  341. package/src/side-thread-production.ts +118 -0
  342. package/src/side-thread.test.ts +1067 -0
  343. package/src/side-thread.ts +2499 -0
  344. package/src/skillhub-http.test.ts +142 -0
  345. package/src/sqlite-close-checkpoint.test.ts +78 -0
  346. package/src/start-node.test.ts +264 -0
  347. package/src/status-alias-filter-http.test.ts +106 -0
  348. package/src/status-alias-resolver-http.test.ts +163 -0
  349. package/src/status-alias-resolver.ts +19 -0
  350. package/src/status-node-id-filter-http.test.ts +161 -0
  351. package/src/status-read-cache-http.test.ts +229 -0
  352. package/src/status-read-cache.ts +129 -0
  353. package/src/stop-delete-node.test.ts +567 -1
  354. package/src/task-access-http.test.ts +402 -0
  355. package/src/task-access.ts +420 -0
  356. package/src/task-activity.ts +60 -0
  357. package/src/task-auth-origin-http.test.ts +93 -0
  358. package/src/task-auth-origin.test.ts +24 -0
  359. package/src/task-auth-origin.ts +7 -0
  360. package/src/task-consumption.test.ts +490 -0
  361. package/src/task-diagnostic-http.test.ts +149 -0
  362. package/src/task-diagnostic.test.ts +115 -0
  363. package/src/task-diagnostic.ts +118 -0
  364. package/src/task-expiry-notice-http.test.ts +287 -0
  365. package/src/task-expiry-notice.ts +315 -0
  366. package/src/task-idempotency-mcp.test.ts +142 -0
  367. package/src/task-idempotency.test.ts +76 -0
  368. package/src/task-idempotency.ts +81 -0
  369. package/src/task-late-replies.ts +54 -0
  370. package/src/task-late-reply-http.test.ts +227 -0
  371. package/src/task-lifecycle-watcher-busy.test.ts +114 -0
  372. package/src/task-lifecycle-watcher.test.ts +204 -0
  373. package/src/task-lifecycle-watcher.ts +109 -0
  374. package/src/task-network-resolution-http.test.ts +140 -0
  375. package/src/task-offline-delivery-2668.test.ts +119 -0
  376. package/src/task-offline-delivery.ts +81 -0
  377. package/src/task-orphan-http.test.ts +287 -0
  378. package/src/task-orphan.ts +119 -0
  379. package/src/task-queue-ahead-http.test.ts +309 -0
  380. package/src/task-queue-ahead-scale.test.ts +236 -0
  381. package/src/task-queue-ahead.ts +186 -0
  382. package/src/task-rejection-log-http.test.ts +160 -0
  383. package/src/task-rejection-log.ts +61 -0
  384. package/src/task-sender-http.test.ts +143 -0
  385. package/src/task-stale-open-http.test.ts +292 -0
  386. package/src/task-stale-open.ts +103 -0
  387. package/src/tasks-pagination-http.test.ts +141 -0
  388. package/src/team-rules-status-http.test.ts +90 -0
  389. package/src/team-rules-status.test.ts +59 -0
  390. package/src/team-rules-status.ts +72 -0
  391. package/src/tmux-allowlist.test.ts +48 -0
  392. package/src/tool-audience-http.test.ts +230 -0
  393. package/src/tool-audience.ts +127 -0
  394. package/src/tools-list-json-schema.test.ts +94 -0
  395. package/src/tools.ts +4310 -419
  396. package/src/upload-early-reject-guard.test.ts +155 -0
  397. package/src/uploads-http.test.ts +86 -7
  398. package/src/uploads.ts +103 -6
  399. package/src/user-avatar-http.test.ts +74 -0
  400. package/src/user-avatar-image.ts +160 -0
  401. package/src/user-avatar-migration.test.ts +25 -0
  402. package/src/user-avatar-upload-http.test.ts +348 -0
  403. package/src/user-inbox-by-agent-http.test.ts +161 -0
  404. package/src/user-inbox-netid-notnull.test.ts +122 -0
  405. package/src/user-inbox-read-http.test.ts +223 -0
  406. package/src/user-inbox-schema.test.ts +54 -0
  407. package/src/version-stats.test.ts +66 -0
  408. package/src/version-stats.ts +109 -0
@@ -0,0 +1,275 @@
1
+ // 标签树(POST /api/requirements/tags/create + GET /api/requirements/tags 的 nodes + ops 维护层级)
2
+ // —— HTTP 集成测试(真实 Bun.serve,私有端口,临时库)。
3
+ //
4
+ // 场景:Hub 管理员 admin 的网络 NET,另一个不相干的网络 NET2。成员:
5
+ // carol —— task_access='all' 的老成员(能管标签);
6
+ // alice —— scoped 成员(不能管);
7
+ // vic —— viewer;
8
+ // nodeToken —— 节点令牌。
9
+ //
10
+ // 正向:建根标签、建子标签并回读 parent_id/depth;0 任务的子标签能在 nodes 里读到;父只在卡片上出现过时
11
+ // 补登记成顶层(parent_registered=true)且子标签仍挂在它下面;改名 / 合并 / 删除让层级跟着动。
12
+ // 反向:重名 409、父不存在 404(不 root fallback)、超过 4 层 400、scoped / viewer / 节点令牌 403 且一行都不写、
13
+ // 同名标签在别的网络互不相干、坏参数 400、原子性(重名失败后不留半条节点)。
14
+
15
+ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
16
+ import { mkdtempSync, rmSync } from "node:fs";
17
+ import { tmpdir } from "node:os";
18
+ import { join } from "node:path";
19
+
20
+ const DIR = mkdtempSync(join(tmpdir(), "anet-tag-tree-"));
21
+ let BASE = "";
22
+ let hub: any = null;
23
+ let db: any = null;
24
+ const PW = "TagTreePassw0rd!x";
25
+ let NET = "";
26
+ let NET2 = "";
27
+ let admin = { token: "", id: "" };
28
+ let other = { token: "", id: "" };
29
+ let alice = { token: "", id: "" };
30
+ let carol = { token: "", id: "" };
31
+ let vic = { token: "", id: "" };
32
+ let nodeToken = "";
33
+
34
+ type R = { status: number; body: any };
35
+ async function send(token: string, method: string, path: string, payload?: unknown): Promise<R> {
36
+ const res = await fetch(`${BASE}${path}`, {
37
+ method,
38
+ headers: { ...(token ? { Authorization: `Bearer ${token}` } : {}), "Content-Type": "application/json" },
39
+ body: payload === undefined ? undefined : JSON.stringify(payload),
40
+ });
41
+ const text = await res.text();
42
+ let body: any = null;
43
+ try { body = JSON.parse(text); } catch {}
44
+ return { status: res.status, body };
45
+ }
46
+
47
+ const create = (token: string, payload: unknown, net = NET) => send(token, "POST", `/api/requirements/tags/create?network_id=${net}`, payload);
48
+ const tagsOf = (token: string, net = NET) => send(token, "GET", `/api/requirements/tags?network_id=${net}`);
49
+ const op = (token: string, payload: unknown, net = NET) => send(token, "POST", `/api/requirements/tags/ops?network_id=${net}`, payload);
50
+ const nodesOf = async (token = admin.token, net = NET): Promise<Record<string, { parent: string | null; depth: number; count: number; registered: boolean }>> => {
51
+ const r = await tagsOf(token, net);
52
+ expect(r.status).toBe(200);
53
+ return Object.fromEntries((r.body.nodes ?? []).map((n: any) => [n.name, { parent: n.parent_id, depth: n.depth, count: n.count, registered: n.registered }]));
54
+ };
55
+ const nodeRows = (net = NET) => db.all("SELECT name, parent_name FROM network_tag_nodes WHERE network_id = ?1 ORDER BY name", [net]);
56
+
57
+ beforeAll(async () => {
58
+ process.env.COMMHUB_DB ||= join(DIR, "hub.db");
59
+ process.env.COMMHUB_UPLOADS_DIR = join(DIR, "uploads");
60
+ process.env.HOST = "127.0.0.1";
61
+ ({ db } = await import("./db.js"));
62
+ const { createNetworkTokenForNode, register } = await import("./auth.js");
63
+ const stamp = Date.now();
64
+ const a = register(`tt_admin_${stamp}`, PW, undefined, "Admin");
65
+ expect(a.ok).toBe(true);
66
+ admin = { token: a.token!, id: a.user!.user_id };
67
+ NET = a.network_id!;
68
+ db.run("UPDATE users SET role = 'admin' WHERE user_id = ?1", [admin.id]);
69
+ const b = register(`tt_other_${stamp}`, PW, undefined, "Other");
70
+ expect(b.ok).toBe(true);
71
+ other = { token: b.token!, id: b.user!.user_id };
72
+ NET2 = b.network_id!;
73
+ const ntok = createNetworkTokenForNode(admin.id, NET, "tag-node");
74
+ expect(ntok.ok).toBe(true);
75
+ nodeToken = ntok.token!;
76
+
77
+ const mod: any = await import("./server.js");
78
+ hub = mod.bootServer({ port: 0, hostname: "127.0.0.1" });
79
+ BASE = `http://127.0.0.1:${hub.port}`;
80
+
81
+ const mk = async (username: string, role: string) => {
82
+ const r = await send(admin.token, "POST", "/api/admin/users", { username, password: PW, network_id: NET, role });
83
+ expect(r.status).toBe(200);
84
+ const login = await send("", "POST", "/api/auth/login", { username, password: PW });
85
+ expect(login.status).toBe(200);
86
+ return { token: login.body.token as string, id: login.body.user.user_id as string };
87
+ };
88
+ alice = await mk(`tt_alice_${stamp}`, "member");
89
+ carol = await mk(`tt_carol_${stamp}`, "member");
90
+ vic = await mk(`tt_vic_${stamp}`, "viewer");
91
+ db.run("UPDATE network_members SET task_access = 'scoped' WHERE network_id = ?1 AND user_id = ?2", [NET, alice.id]);
92
+ db.run("UPDATE network_members SET task_access = 'all' WHERE network_id = ?1 AND user_id = ?2", [NET, carol.id]);
93
+
94
+ // 一张只有 legacy 标签的卡:它的标签没有节点行 —— 用来验证「拿在用标签当父」时补登记。
95
+ const card = await send(admin.token, "POST", "/api/requirements", { network_id: NET, name: "legacy", tags: ["legacy"] });
96
+ expect(card.status).toBe(201);
97
+ }, 30_000);
98
+
99
+ afterAll(() => {
100
+ try { hub?.stop?.(true); } catch {}
101
+ try { rmSync(DIR, { recursive: true, force: true }); } catch {}
102
+ });
103
+
104
+ describe("capability 与权限", () => {
105
+ test("列表 capabilities 带 tag_tree(旧客户端忽略)", async () => {
106
+ const r = await send(admin.token, "GET", `/api/requirements?network_id=${NET}`);
107
+ expect(r.body.capabilities).toContain("tag_tree");
108
+ });
109
+
110
+ test("scoped / viewer / 节点令牌 403,且一行节点都不写", async () => {
111
+ for (const token of [alice.token, vic.token, nodeToken]) {
112
+ const r = await create(token, { name: "被拒" });
113
+ expect(r.status).toBe(403);
114
+ }
115
+ expect(nodeRows()).toEqual([]);
116
+ });
117
+
118
+ test("网络管理员与 task_access='all' 的老成员能建", async () => {
119
+ const r = await create(carol.token, { name: "carol建的" });
120
+ expect(r.status).toBe(201);
121
+ expect(r.body.tag).toEqual({ name: "carol建的", parent_id: null, depth: 1 });
122
+ const del = await op(admin.token, { op: "delete", tag: "carol建的" });
123
+ expect(del.status).toBe(200);
124
+ });
125
+ });
126
+
127
+ describe("建根标签与子标签", () => {
128
+ test("建根标签:201,parent_id=null,depth=1", async () => {
129
+ const r = await create(admin.token, { name: "需求" });
130
+ expect(r.status).toBe(201);
131
+ expect(r.body).toMatchObject({ ok: true, tag: { name: "需求", parent_id: null, depth: 1 }, parent_registered: false });
132
+ });
133
+
134
+ test("0 任务的标签也能在 nodes 里读到(count=0,registered=true)", async () => {
135
+ const nodes = await nodesOf();
136
+ expect(nodes["需求"]).toEqual({ parent: null, depth: 1, count: 0, registered: true });
137
+ // tags(卡片上出现过的)保持旧语义:0 任务的标签不在里面
138
+ const t = await tagsOf(admin.token);
139
+ expect(t.body.tags).not.toContain("需求");
140
+ });
141
+
142
+ test("建子标签:回读 parent_id / depth / count=0", async () => {
143
+ const r = await create(admin.token, { name: "前端", parent_id: "需求" });
144
+ expect(r.status).toBe(201);
145
+ expect(r.body.tag).toEqual({ name: "前端", parent_id: "需求", depth: 2 });
146
+ const nodes = await nodesOf();
147
+ expect(nodes["前端"]).toEqual({ parent: "需求", depth: 2, count: 0, registered: true });
148
+ });
149
+
150
+ test("三代:第 3 层 depth=3;超过 MAX_TAG_DEPTH 的第 4 层子标签 400", async () => {
151
+ const l3 = await create(admin.token, { name: "按钮", parent_id: "前端" });
152
+ expect(l3.status).toBe(201);
153
+ expect(l3.body.tag.depth).toBe(3);
154
+ const l4 = await create(admin.token, { name: "主按钮", parent_id: "按钮" });
155
+ expect(l4.status).toBe(201);
156
+ expect(l4.body.tag.depth).toBe(4);
157
+ const l5 = await create(admin.token, { name: "太深了", parent_id: "主按钮" });
158
+ expect(l5.status).toBe(400);
159
+ expect(l5.body.error).toBe("tag_depth_exceeded");
160
+ expect(nodeRows().some((r: any) => r.name === "太深了")).toBe(false);
161
+ });
162
+
163
+ test("重名 409:已登记的、卡片上在用的、有颜色行的都算重名;失败不留半条", async () => {
164
+ expect((await create(admin.token, { name: "需求" })).body.error).toBe("tag_exists");
165
+ expect((await create(admin.token, { name: "legacy" })).body.error).toBe("tag_exists");
166
+ // 只有颜色行、没有卡片也没有节点的名字也算存在(直接写库构造这种历史状态)
167
+ db.run("INSERT INTO network_tags (network_id, name, color, updated_at) VALUES (?1, ?2, ?3, ?4)", [NET, "有颜色的", "#112233", new Date().toISOString()]);
168
+ const colored = await create(admin.token, { name: "有颜色的" });
169
+ expect(colored.body.error).toBe("tag_exists");
170
+ const before = nodeRows();
171
+ expect(before.map((r: any) => r.name)).not.toContain("有颜色的");
172
+ });
173
+
174
+ test("父不存在 404 tag_parent_not_found —— 不会静默建到根上", async () => {
175
+ const r = await create(admin.token, { name: "孤儿", parent_id: "不存在的父" });
176
+ expect(r.status).toBe(404);
177
+ expect(r.body.error).toBe("tag_parent_not_found");
178
+ expect(nodeRows().some((row: any) => row.name === "孤儿")).toBe(false);
179
+ });
180
+
181
+ test("父只在卡片上出现过:补登记成顶层节点(parent_registered=true),子标签仍挂在它下面", async () => {
182
+ const r = await create(admin.token, { name: "legacy子", parent_id: "legacy" });
183
+ expect(r.status).toBe(201);
184
+ expect(r.body.parent_registered).toBe(true);
185
+ expect(r.body.tag).toEqual({ name: "legacy子", parent_id: "legacy", depth: 2 });
186
+ const nodes = await nodesOf();
187
+ expect(nodes["legacy"]).toMatchObject({ parent: null, depth: 1 });
188
+ expect(nodes["legacy子"]).toMatchObject({ parent: "legacy", depth: 2 });
189
+ });
190
+
191
+ test("坏参数 400:空名 / 太长 / 控制字符 / parent_id 不是字符串", async () => {
192
+ expect((await create(admin.token, { name: "" })).body.error).toBe("invalid_tag");
193
+ expect((await create(admin.token, { name: "一二三四五六七八九十一二三四五六七八九十多" })).body.error).toBe("invalid_tag");
194
+ expect((await create(admin.token, { name: "换\n行" })).body.error).toBe("invalid_tag");
195
+ const bad = await create(admin.token, { name: "正常", parent_id: 42 });
196
+ expect(bad.status).toBe(400);
197
+ expect(bad.body.error).toBe("invalid_tag_parent_id");
198
+ expect((await create(admin.token, {})).body.error).toBe("invalid_tag");
199
+ });
200
+
201
+ test("别的网络同名互不相干:NET2 里能再建「需求」,NET 的树不受影响", async () => {
202
+ const r = await create(other.token, { name: "需求" }, NET2);
203
+ expect(r.status).toBe(201);
204
+ expect(r.body.tag.depth).toBe(1);
205
+ expect((await nodesOf(admin.token, NET2))["需求"]).toMatchObject({ parent: null, depth: 1 });
206
+ expect((await nodesOf(admin.token, NET))["前端"]).toMatchObject({ parent: "需求", depth: 2 });
207
+ });
208
+
209
+ test("受限成员的 nodes 只含他看得见的标签(登记过但没有可见卡的名字不外泄)", async () => {
210
+ const r = await tagsOf(alice.token);
211
+ expect(r.status).toBe(200);
212
+ expect(r.body.nodes).toEqual([]);
213
+ expect(r.body.can_manage).toBe(false);
214
+ });
215
+ });
216
+
217
+ describe("改名 / 合并 / 删除让层级跟着动", () => {
218
+ test("rename:节点与子节点的 parent 一起改,深度不变", async () => {
219
+ const r = await op(admin.token, { op: "rename", from: "需求", to: "需求池" });
220
+ expect(r.status).toBe(200);
221
+ const nodes = await nodesOf();
222
+ expect(nodes["需求池"]).toMatchObject({ parent: null, depth: 1 });
223
+ expect(nodes["前端"]).toMatchObject({ parent: "需求池", depth: 2 });
224
+ expect(nodes["按钮"]).toMatchObject({ parent: "前端", depth: 3 });
225
+ expect(nodes["需求"]).toBeUndefined();
226
+ });
227
+
228
+ test("rename 到已存在的节点 = 合并:来源的子节点挂到目标,且不会自环", async () => {
229
+ await create(admin.token, { name: "临时" });
230
+ await create(admin.token, { name: "临时子", parent_id: "临时" });
231
+ const r = await op(admin.token, { op: "rename", from: "临时", to: "需求池" });
232
+ expect(r.status).toBe(200);
233
+ const nodes = await nodesOf();
234
+ expect(nodes["临时子"]).toMatchObject({ parent: "需求池", depth: 2 });
235
+ // 目标是来源的子孙时不能自环:把「前端」并到它的子节点「按钮」上
236
+ await op(admin.token, { op: "rename", from: "前端", to: "按钮" });
237
+ const after = await nodesOf();
238
+ expect(after["按钮"].parent).not.toBe("按钮");
239
+ expect(nodeRows().every((row: any) => row.name !== row.parent_name)).toBe(true);
240
+ });
241
+
242
+ test("merge:来源节点的子节点挂到目标,来源节点删掉", async () => {
243
+ await create(admin.token, { name: "源A" });
244
+ await create(admin.token, { name: "源A子", parent_id: "源A" });
245
+ await create(admin.token, { name: "目标B" });
246
+ const r = await op(admin.token, { op: "merge", from: ["源A"], to: "目标B" });
247
+ expect(r.status).toBe(200);
248
+ expect(r.body.reparented).toBe(1);
249
+ const nodes = await nodesOf();
250
+ expect(nodes["源A"]).toBeUndefined();
251
+ expect(nodes["源A子"]).toMatchObject({ parent: "目标B", depth: 2 });
252
+ });
253
+
254
+ test("delete:子节点挂到被删节点的父(没有父就成根),不丢层级", async () => {
255
+ const before = await nodesOf();
256
+ const r = await op(admin.token, { op: "delete", tag: "按钮" });
257
+ expect(r.status).toBe(200);
258
+ const nodes = await nodesOf();
259
+ // 「按钮」的父是「需求池」(rename 之后),所以「主按钮」挂到「需求池」
260
+ expect(nodes["主按钮"].parent).toBe(before["按钮"].parent);
261
+ expect(nodes["按钮"]).toBeUndefined();
262
+ });
263
+
264
+ test("0 任务的节点也能上色,改名时颜色跟着走(#tag/ops 不再只认卡片)", async () => {
265
+ await create(admin.token, { name: "上色前" });
266
+ const c = await op(admin.token, { op: "color", tag: "上色前", color: "#ABCDEF" });
267
+ expect(c.status).toBe(200);
268
+ expect((await tagsOf(admin.token)).body.colors["上色前"]).toBe("#abcdef");
269
+ const r = await op(admin.token, { op: "rename", from: "上色前", to: "上色后" });
270
+ expect(r.status).toBe(200);
271
+ const after = await tagsOf(admin.token);
272
+ expect(after.body.colors["上色后"]).toBe("#abcdef");
273
+ expect(after.body.colors["上色前"]).toBeUndefined();
274
+ });
275
+ });
@@ -0,0 +1,127 @@
1
+ // 标签树(父子标签)。标签本身仍然只是卡片 tags_json 里的字符串(见 requirement-tags.ts);
2
+ // 这里只多存两件事:
3
+ // ① 谁挂在谁下面 —— network_tag_nodes(network_id, name, parent_name);
4
+ // ② 创建过但还没有任何卡片用的标签 —— 否则 0 任务的子标签在 GET /tags 里读不到(它只会数卡片)。
5
+ // 语义:网络内标签名就是 id(没有 tag_id),parent_name 指向父标签名;改名时父引用跟着改。
6
+ // 深度上限 MAX_TAG_DEPTH(含根)。父不存在 = 报错,不静默挂到根上。
7
+ import { tagName } from "./requirement-tags.js";
8
+
9
+ /** 最多 4 层(顶层是第 1 层)。比子需求(5 层)浅一层:侧栏要一屏放得下父子孙。 */
10
+ export const MAX_TAG_DEPTH = 4;
11
+
12
+ /** 客户端用这个 capability 判断 Hub 有没有「创建标签 / 父标签」;没有就灰掉入口,别调用。 */
13
+ export const TAG_TREE_CAPABILITY = "tag_tree";
14
+
15
+ export type TagNodeRow = { name: string; parent_name: string | null };
16
+
17
+ export type TagNodePublic = {
18
+ name: string;
19
+ parent_id: string | null;
20
+ depth: number;
21
+ /** 这张标签是不是「登记过」的节点(create 建的、或被 create 当父补登记的)。false = 只在卡片上出现过。 */
22
+ registered: boolean;
23
+ };
24
+
25
+ export type CreateTagInput = { name: string; parent: string | null };
26
+
27
+ /**
28
+ * POST /api/requirements/tags/create 的 body:
29
+ * { "name": "子标签", "parent_id": null | "父标签名" }
30
+ * parent_id 缺省/null = 建在根上;给了字符串就必须是网络里已存在的标签 —— 不存在回 404,
31
+ * **绝不**悄悄建到根上(客户端要预选父标签,静默 root fallback 会让 UI 显示的和实际存的不一致)。
32
+ */
33
+ export function parseCreateTag(body: Record<string, unknown>): CreateTagInput | { error: string } {
34
+ const name = tagName(body.name);
35
+ if (!name) return { error: "invalid_tag" };
36
+ const rawParent = body.parent_id;
37
+ if (rawParent === undefined || rawParent === null) return { name, parent: null };
38
+ if (typeof rawParent !== "string") return { error: "invalid_tag_parent_id" };
39
+ const parent = tagName(rawParent);
40
+ if (!parent) return { error: "invalid_tag_parent_id" };
41
+ if (parent === name) return { error: "tag_parent_cycle" };
42
+ return { name, parent };
43
+ }
44
+
45
+ /** 从 name 往上数几层(顶层 = 1)。链上有环(历史脏数据)返回 Infinity,调用方据此拒绝。 */
46
+ export function tagDepth(name: string, parentOf: Map<string, string | null>): number {
47
+ let depth = 1;
48
+ let cur = parentOf.get(name) ?? null;
49
+ const seen = new Set<string>([name]);
50
+ while (cur) {
51
+ if (seen.has(cur)) return Number.POSITIVE_INFINITY;
52
+ seen.add(cur);
53
+ depth++;
54
+ cur = parentOf.get(cur) ?? null;
55
+ }
56
+ return depth;
57
+ }
58
+
59
+ /** child 是不是 ancestor 的子孙(用于改名时的防环判断)。 */
60
+ export function isDescendant(child: string, ancestor: string, parentOf: Map<string, string | null>): boolean {
61
+ let cur: string | null = parentOf.get(child) ?? null;
62
+ const seen = new Set<string>();
63
+ while (cur) {
64
+ if (cur === ancestor) return true;
65
+ if (seen.has(cur)) return false;
66
+ seen.add(cur);
67
+ cur = parentOf.get(cur) ?? null;
68
+ }
69
+ return false;
70
+ }
71
+
72
+ /**
73
+ * GET /api/requirements/tags 的 nodes:
74
+ * 登记过的节点 ∪ 调用者看得见的在用标签(后者 parent_id = null、registered = false,
75
+ * 老 Hub 上就是一堆平标签,升级后不会突然消失)。
76
+ */
77
+ export function buildTagNodes(registered: TagNodeRow[], inUse: string[]): TagNodePublic[] {
78
+ const parentOf = new Map<string, string | null>();
79
+ const isRegistered = new Set<string>();
80
+ for (const row of registered) {
81
+ parentOf.set(row.name, row.parent_name ?? null);
82
+ isRegistered.add(row.name);
83
+ }
84
+ for (const name of inUse) if (!parentOf.has(name)) parentOf.set(name, null);
85
+ const nodes: TagNodePublic[] = [];
86
+ for (const [name, parent] of parentOf) {
87
+ const depth = tagDepth(name, parentOf);
88
+ nodes.push({
89
+ name,
90
+ parent_id: parent,
91
+ // 环/脏数据不给客户端 NaN/Infinity:按顶层展示,写接口仍然会拒绝往里挂。
92
+ depth: Number.isFinite(depth) ? depth : 1,
93
+ registered: isRegistered.has(name),
94
+ });
95
+ }
96
+ return nodes.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
97
+ }
98
+
99
+ /**
100
+ * name 这棵子树有几层(叶子 = 1)。改父级时用它算「搬过去之后最深到几层」:
101
+ * 只检查新父的深度是不够的 —— 一个 3 层的子树挂到第 3 层下,最深会到 5 层。
102
+ * 历史脏数据里有环时用 visited 兜住,不要为脏数据死循环。
103
+ */
104
+ export function tagSubtreeHeight(name: string, parentOf: Map<string, string | null>): number {
105
+ const childrenOf = new Map<string, string[]>();
106
+ for (const [child, parent] of parentOf) {
107
+ if (!parent) continue;
108
+ const list = childrenOf.get(parent);
109
+ if (list) list.push(child); else childrenOf.set(parent, [child]);
110
+ }
111
+ let height = 1;
112
+ let frontier = [name];
113
+ const seen = new Set<string>([name]);
114
+ for (;;) {
115
+ const next: string[] = [];
116
+ for (const node of frontier) {
117
+ for (const child of childrenOf.get(node) ?? []) {
118
+ if (seen.has(child)) continue;
119
+ seen.add(child);
120
+ next.push(child);
121
+ }
122
+ }
123
+ if (!next.length) return height;
124
+ height++;
125
+ frontier = next;
126
+ }
127
+ }
@@ -0,0 +1,102 @@
1
+ /** Small, network-local labels; count Unicode code points rather than UTF-16 units. */
2
+ export function normalizeTags(value: unknown): string[] | null {
3
+ if (!Array.isArray(value) || value.length > 10) return null;
4
+ const tags: string[] = [];
5
+ for (const valueTag of value) {
6
+ if (typeof valueTag !== "string") return null;
7
+ const tag = valueTag.trim();
8
+ if (!tag || [...tag].length > 20 || /[\u0000-\u001f\u007f]/u.test(tag)) return null;
9
+ if (!tags.includes(tag)) tags.push(tag);
10
+ }
11
+ return tags;
12
+ }
13
+
14
+ export function storedTags(value: string | null): string[] {
15
+ try { return normalizeTags(JSON.parse(value || "[]")) ?? []; } catch { return []; }
16
+ }
17
+
18
+ // ── 标签管理(改名 / 合并 / 删除 / 颜色) ──
19
+ // 标签只是卡片 tags 数组里的字符串,没有自己的表;批量操作 = 把网络里每张带这个标签的卡的数组改写一遍。
20
+ // 颜色是可选的,单独存在 network_tags(network_id, name, color);没行 = 客户端用默认灰。
21
+ export const MAX_MERGE_SOURCES = 50;
22
+ export type TagOp =
23
+ | { op: "rename"; from: string; to: string }
24
+ | { op: "merge"; from: string[]; to: string }
25
+ | { op: "delete"; tag: string }
26
+ | { op: "color"; tag: string; color: string | null }
27
+ // 改父级(标签树自己的层级,与卡片无关):parent=null = 升为顶层。
28
+ | { op: "reparent"; tag: string; parent: string | null };
29
+
30
+ /** 单个标签名,规则同 normalizeTags。不合法 = null。 */
31
+ export function tagName(value: unknown): string | null {
32
+ const tags = normalizeTags([value]);
33
+ return tags && tags.length === 1 ? tags[0] : null;
34
+ }
35
+
36
+ const TAG_COLOR = /^#[0-9a-fA-F]{6}$/;
37
+ /** 请求体 → 操作;不合法返回错误码。 */
38
+ export function parseTagOp(body: Record<string, unknown>): TagOp | { error: string } {
39
+ switch (body.op) {
40
+ case "rename": {
41
+ const from = tagName(body.from), to = tagName(body.to);
42
+ if (!from || !to) return { error: "invalid_tag" };
43
+ if (from === to) return { error: "same_tag" };
44
+ return { op: "rename", from, to };
45
+ }
46
+ case "merge": {
47
+ if (!Array.isArray(body.from) || body.from.length === 0 || body.from.length > MAX_MERGE_SOURCES) return { error: "invalid_tag" };
48
+ const from: string[] = [];
49
+ for (const value of body.from) {
50
+ const tag = tagName(value);
51
+ if (!tag) return { error: "invalid_tag" };
52
+ if (!from.includes(tag)) from.push(tag);
53
+ }
54
+ const to = tagName(body.to);
55
+ if (!to) return { error: "invalid_tag" };
56
+ // 目标自己出现在来源里不算来源(合并进自己 = 什么都不做)。
57
+ const sources = from.filter(tag => tag !== to);
58
+ if (!sources.length) return { error: "same_tag" };
59
+ return { op: "merge", from: sources, to };
60
+ }
61
+ case "delete": {
62
+ const tag = tagName(body.tag);
63
+ return tag ? { op: "delete", tag } : { error: "invalid_tag" };
64
+ }
65
+ case "color": {
66
+ const tag = tagName(body.tag);
67
+ if (!tag) return { error: "invalid_tag" };
68
+ if (body.color !== null && (typeof body.color !== "string" || !TAG_COLOR.test(body.color))) return { error: "invalid_tag_color" };
69
+ return { op: "color", tag, color: body.color === null ? null : (body.color as string).toLowerCase() };
70
+ }
71
+ case "reparent": {
72
+ const tag = tagName(body.tag);
73
+ if (!tag) return { error: "invalid_tag" };
74
+ // 与 create 同一套读法:缺省 key 算错(不能靠"没传"把标签静默升到根),显式 null = 根。
75
+ if (!("parent" in body)) return { error: "invalid_tag_parent_id" };
76
+ if (body.parent === null || body.parent === "") return { op: "reparent", tag, parent: null };
77
+ const parent = tagName(body.parent);
78
+ if (!parent) return { error: "invalid_tag_parent_id" };
79
+ if (parent === tag) return { error: "tag_parent_cycle" };
80
+ return { op: "reparent", tag, parent };
81
+ }
82
+ default:
83
+ return { error: "invalid_tag_op" };
84
+ }
85
+ }
86
+
87
+ /** 这张卡的标签被这个操作改写后的样子;没变返回 null。顺序保留(新名字占第一个来源的位置),去重。 */
88
+ export function applyTagOp(tags: string[], op: TagOp): string[] | null {
89
+ let sources: string[];
90
+ let to: string | null;
91
+ if (op.op === "rename") { sources = [op.from]; to = op.to; }
92
+ else if (op.op === "merge") { sources = op.from; to = op.to; }
93
+ else if (op.op === "delete") { sources = [op.tag]; to = null; }
94
+ else return null;
95
+ if (!tags.some(tag => sources.includes(tag))) return null;
96
+ const next: string[] = [];
97
+ for (const tag of tags) {
98
+ const mapped = sources.includes(tag) ? to : tag;
99
+ if (mapped !== null && !next.includes(mapped)) next.push(mapped);
100
+ }
101
+ return next;
102
+ }