@sleep2agi/commhub-server 0.9.0-preview.20 → 0.9.0-preview.200

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 (398) hide show
  1. package/README.md +130 -10
  2. package/bin/commhub.ts +99 -11
  3. package/package.json +7 -7
  4. package/src/ack-create-request-transport.test.ts +182 -0
  5. package/src/ack-create-request.test.ts +50 -7
  6. package/src/admin-delete-network-http.test.ts +228 -0
  7. package/src/admin-networks-http.test.ts +88 -0
  8. package/src/adoption-candidates-http.test.ts +137 -0
  9. package/src/adoption-candidates.ts +158 -0
  10. package/src/agent-access-batch.test.ts +210 -0
  11. package/src/agent-access.ts +487 -0
  12. package/src/agent-acl-groups-http.test.ts +247 -0
  13. package/src/agent-acl-http.test.ts +659 -0
  14. package/src/agent-acl-slice3-http.test.ts +267 -0
  15. package/src/agent-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 +21 -12
  27. package/src/api-host-supervisors-runtime-readiness.test.ts +195 -0
  28. package/src/api-nodes-shape.test.ts +120 -13
  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 +163 -0
  35. package/src/avatar-validate.ts +103 -0
  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/boot-side-effect.test.ts +124 -0
  40. package/src/broadcast-fanout-2721.test.ts +118 -0
  41. package/src/broadcast-fanout.ts +98 -0
  42. package/src/chain-attempt-dedup.test.ts +447 -0
  43. package/src/clone-node.test.ts +248 -0
  44. package/src/clone-node.ts +289 -0
  45. package/src/codex-config-flags.ts +77 -0
  46. package/src/codex-fork-contract.ts +23 -0
  47. package/src/codex-fork-migration.test.ts +38 -0
  48. package/src/commhub-bin-args.test.ts +85 -0
  49. package/src/config-apply-sec1.test.ts +107 -0
  50. package/src/config-apply-validate.test.ts +134 -1
  51. package/src/config-apply-validate.ts +111 -5
  52. package/src/create-node-blocked-gate.test.ts +356 -0
  53. package/src/create-node-network-id.test.ts +79 -0
  54. package/src/create-node-tool-schema.test.ts +49 -0
  55. package/src/create-node-unicode-name.test.ts +120 -0
  56. package/src/create-node-validate.test.ts +199 -7
  57. package/src/create-node-validate.ts +232 -15
  58. package/src/create-node-workdir.test.ts +289 -0
  59. package/src/create-node.ts +88 -23
  60. package/src/daemon-provider-snapshots.test.ts +421 -0
  61. package/src/daemon-provider-snapshots.ts +327 -0
  62. package/src/daemon-token-owner-http.test.ts +236 -0
  63. package/src/dashboard-slash-routing-http.test.ts +109 -0
  64. package/src/db-adapter-guard.test.ts +148 -0
  65. package/src/db-adapter-translate.test.ts +128 -0
  66. package/src/db-adapter.ts +377 -91
  67. package/src/db-timestamp.test.ts +38 -0
  68. package/src/db-timestamp.ts +15 -0
  69. package/src/db.ts +1306 -153
  70. package/src/delivered-without-push.test.ts +140 -0
  71. package/src/department-groups-http.test.ts +209 -0
  72. package/src/department-groups-sync-http.test.ts +328 -0
  73. package/src/department-groups.ts +434 -0
  74. package/src/department-heads-http.test.ts +330 -0
  75. package/src/department-heads.ts +226 -0
  76. package/src/departments-agent-count.test.ts +129 -0
  77. package/src/departments-http.test.ts +185 -0
  78. package/src/departments-mcp.test.ts +128 -0
  79. package/src/departments.ts +318 -0
  80. package/src/desktop-message-seam.test.ts +150 -0
  81. package/src/desktop-message.test.ts +368 -0
  82. package/src/dm-file-scope-http.test.ts +178 -0
  83. package/src/empty-node-sweeper.test.ts +104 -0
  84. package/src/empty-node-sweeper.ts +88 -0
  85. package/src/env-transport-gate-http.test.ts +177 -0
  86. package/src/env-transport-gate.ts +74 -0
  87. package/src/env-transport-policy.ts +21 -0
  88. package/src/event-loop-lag.test.ts +139 -0
  89. package/src/event-loop-lag.ts +150 -0
  90. package/src/ext-token-shared.test.ts +60 -0
  91. package/src/ext-validation-regression.test.ts +131 -0
  92. package/src/external-schedule-edits-http.test.ts +321 -0
  93. package/src/external-schedule-edits-timestamps.test.ts +64 -0
  94. package/src/external-schedule-edits.ts +327 -0
  95. package/src/file-download-authz-dev-open.test.ts +135 -0
  96. package/src/file-download-authz.test.ts +404 -0
  97. package/src/file-download-date-bucket.test.ts +436 -0
  98. package/src/file-network-scope-dev-open.test.ts +97 -0
  99. package/src/file-network-scope.test.ts +732 -0
  100. package/src/group-membership-events-http.test.ts +264 -0
  101. package/src/group-messages-http.test.ts +482 -0
  102. package/src/group-messages.ts +297 -0
  103. package/src/health-host-disk-2756.test.ts +49 -0
  104. package/src/health-redaction.test.ts +685 -0
  105. package/src/host-supervisor-identity-http.test.ts +152 -0
  106. package/src/host-supervisor-identity.ts +92 -0
  107. package/src/host-supervisors-daemon-version.test.ts +137 -0
  108. package/src/http-gzip.test.ts +94 -0
  109. package/src/http-gzip.ts +112 -0
  110. package/src/hub-catalog-read-http.test.ts +187 -0
  111. package/src/hub-provider-config.test.ts +139 -0
  112. package/src/hub-provider-config.ts +105 -0
  113. package/src/hub-timestamp.test.ts +38 -0
  114. package/src/hub-timestamp.ts +27 -0
  115. package/src/human-dm.ts +215 -0
  116. package/src/human-inbox.ts +42 -0
  117. package/src/inbox-caller.ts +49 -0
  118. package/src/inbox-count-sse.test.ts +310 -0
  119. package/src/inbox-count.ts +29 -0
  120. package/src/index.ts +15 -2380
  121. package/src/list-host-supervisors.test.ts +5 -4
  122. package/src/mcp-context-cost-http.test.ts +127 -0
  123. package/src/mcp-inflight.test.ts +92 -0
  124. package/src/mcp-inflight.ts +38 -0
  125. package/src/mcp-projects-events-http.test.ts +162 -0
  126. package/src/mcp-route-label-http.test.ts +120 -0
  127. package/src/mcp-write-network-resolution.test.ts +432 -0
  128. package/src/member-audit-network-id-http.test.ts +93 -0
  129. package/src/member-presence-http.test.ts +210 -0
  130. package/src/messages-ack-by-agent-http.test.ts +142 -0
  131. package/src/migrate-sqlite-to-pg.test.ts +47 -0
  132. package/src/migrate-sqlite-to-pg.ts +263 -0
  133. package/src/model-auth-notify-http.test.ts +181 -0
  134. package/src/model-auth-notify.ts +116 -0
  135. package/src/network-name-http.test.ts +75 -0
  136. package/src/network-rules-http.test.ts +169 -0
  137. package/src/network-rules.ts +129 -0
  138. package/src/network-scope.ts +276 -0
  139. package/src/network-token-membership-http.test.ts +139 -0
  140. package/src/node-alias-control.ts +12 -0
  141. package/src/node-attrs-validate.ts +88 -0
  142. package/src/node-attrs.test.ts +258 -0
  143. package/src/node-caller-identity-http.test.ts +1083 -0
  144. package/src/node-create-request-status-http.test.ts +105 -0
  145. package/src/node-daemon-bindings.test.ts +132 -0
  146. package/src/node-daemon-bindings.ts +135 -0
  147. package/src/node-failure-alert.test.ts +150 -0
  148. package/src/node-failure-alert.ts +177 -0
  149. package/src/node-files-transport.test.ts +344 -0
  150. package/src/node-health-codex-login.test.ts +120 -0
  151. package/src/node-health-dispatch-http.test.ts +279 -0
  152. package/src/node-health-guard.ts +105 -0
  153. package/src/node-health-passthrough.test.ts +115 -0
  154. package/src/node-health-store.ts +101 -0
  155. package/src/node-id-alias.test.ts +190 -0
  156. package/src/node-identity-conflict-http.test.ts +269 -0
  157. package/src/node-identity-conflict.ts +142 -0
  158. package/src/node-identity-mismatch.test.ts +74 -0
  159. package/src/node-in-flight-tasks.ts +31 -0
  160. package/src/node-lifecycle-controllable.test.ts +64 -0
  161. package/src/node-lifecycle-controllable.ts +53 -0
  162. package/src/node-lifecycle-read-http.test.ts +250 -0
  163. package/src/node-lifecycle-read.ts +124 -0
  164. package/src/node-logs-transport.test.ts +263 -0
  165. package/src/node-peer-allowlist.test.ts +79 -0
  166. package/src/node-permissions-http.test.ts +345 -0
  167. package/src/node-permissions.ts +393 -0
  168. package/src/node-request-retention.test.ts +281 -0
  169. package/src/node-request-retention.ts +120 -0
  170. package/src/node-secret-rest-http.test.ts +190 -0
  171. package/src/node-serviceability.test.ts +86 -0
  172. package/src/node-serviceability.ts +124 -0
  173. package/src/node-session-control-http.test.ts +310 -0
  174. package/src/node-session-control.ts +258 -0
  175. package/src/node-skills-transport.test.ts +209 -0
  176. package/src/node-token-identity.ts +35 -0
  177. package/src/node-token-ownership.ts +51 -0
  178. package/src/node-token-privilege-http.test.ts +158 -0
  179. package/src/not-found-api-http.test.ts +67 -0
  180. package/src/observer-avatar-http.test.ts +442 -0
  181. package/src/observer-push.test.ts +252 -0
  182. package/src/opencode-catalog-report-http.test.ts +139 -0
  183. package/src/opencode-v2-catalog.test.ts +268 -0
  184. package/src/opencode-v2-catalog.ts +352 -0
  185. package/src/package-version-consistency.test.ts +25 -0
  186. package/src/parent-source-marker.test.ts +50 -0
  187. package/src/password-network-tokens.ts +25 -0
  188. package/src/peer-reply-atomic.test.ts +455 -0
  189. package/src/peer-reply-capability.test.ts +70 -0
  190. package/src/pg-worker.ts +87 -0
  191. package/src/project-dir-warn-clear-http.test.ts +132 -0
  192. package/src/project-viewer-can-http.test.ts +116 -0
  193. package/src/push.test.ts +20 -10
  194. package/src/push.ts +466 -13
  195. package/src/redact-tokens.test.ts +65 -0
  196. package/src/redact-tokens.ts +40 -0
  197. package/src/rename.ts +38 -10
  198. package/src/reply-target-derivation.test.ts +96 -0
  199. package/src/report-status-handover-capabilities-http.test.ts +124 -0
  200. package/src/report-status-host-schema.test.ts +235 -0
  201. package/src/report-status-resume-id-handover.test.ts +184 -0
  202. package/src/report-status-secret-keys.test.ts +140 -0
  203. package/src/require-explicit-test-db.ts +9 -0
  204. package/src/requirement-due-reminders-http.test.ts +620 -0
  205. package/src/requirement-due-reminders.ts +416 -0
  206. package/src/requirement-events-http.test.ts +268 -0
  207. package/src/requirement-events.test.ts +45 -0
  208. package/src/requirement-events.ts +144 -0
  209. package/src/requirement-notify.ts +165 -0
  210. package/src/requirement-participant-notify-http.test.ts +309 -0
  211. package/src/requirement-tag-ops-http.test.ts +425 -0
  212. package/src/requirement-tag-tree-http.test.ts +275 -0
  213. package/src/requirement-tag-tree.ts +127 -0
  214. package/src/requirement-tags.ts +102 -0
  215. package/src/requirements-abandoned-http.test.ts +236 -0
  216. package/src/requirements-comment-http.test.ts +167 -0
  217. package/src/requirements-completed-at-migration.test.ts +70 -0
  218. package/src/requirements-errors-mcp-http.test.ts +164 -0
  219. package/src/requirements-errors.ts +158 -0
  220. package/src/requirements-etag-http.test.ts +91 -0
  221. package/src/requirements-http.test.ts +709 -0
  222. package/src/requirements-last-event-http.test.ts +349 -0
  223. package/src/requirements-list-mcp-slim-http.test.ts +155 -0
  224. package/src/requirements-list-slim-http.test.ts +324 -0
  225. package/src/requirements-mcp.test.ts +163 -0
  226. package/src/requirements-migrate.ts +283 -0
  227. package/src/requirements-owner-strict-mcp-http.test.ts +145 -0
  228. package/src/requirements-people-http.test.ts +114 -0
  229. package/src/requirements-people-mcp-http.test.ts +231 -0
  230. package/src/requirements-people.ts +196 -0
  231. package/src/requirements-priority-lowest.test.ts +114 -0
  232. package/src/requirements-projects-parent-http.test.ts +123 -0
  233. package/src/requirements-search-http.test.ts +182 -0
  234. package/src/requirements-search.test.ts +32 -0
  235. package/src/requirements-search.ts +145 -0
  236. package/src/requirements-seq-http.test.ts +193 -0
  237. package/src/requirements-seq-migration.test.ts +63 -0
  238. package/src/requirements-start-date.test.ts +125 -0
  239. package/src/requirements-stats-http.test.ts +357 -0
  240. package/src/requirements-stats.ts +195 -0
  241. package/src/requirements-status-participants-http.test.ts +222 -0
  242. package/src/requirements-upgrade-e2e.test.ts +126 -0
  243. package/src/requirements-upgrade-migration.test.ts +98 -0
  244. package/src/requirements.ts +2027 -0
  245. package/src/resolve-port.test.ts +57 -0
  246. package/src/resolve-port.ts +44 -0
  247. package/src/response-charset.test.ts +130 -0
  248. package/src/rest-alias-network-fallback-http.test.ts +123 -0
  249. package/src/rest-alias-network-fallback.test.ts +60 -0
  250. package/src/rest-alias-network-fallback.ts +65 -0
  251. package/src/rest-explicit-columns-http.test.ts +266 -0
  252. package/src/rest-identity.test.ts +130 -0
  253. package/src/rest-identity.ts +141 -0
  254. package/src/rest-projections.ts +72 -0
  255. package/src/rest-read-network-real-chain.test.ts +97 -0
  256. package/src/rest-write-network-resolution.test.ts +133 -0
  257. package/src/restart-readiness-http.test.ts +121 -0
  258. package/src/restricted-files.ts +76 -0
  259. package/src/retention-first-sweep-quiet.test.ts +31 -0
  260. package/src/retention.test.ts +100 -40
  261. package/src/retention.ts +423 -104
  262. package/src/route-callers-http.test.ts +120 -0
  263. package/src/route-timing.test.ts +211 -0
  264. package/src/route-timing.ts +262 -0
  265. package/src/rules-file-duplicate-alias.test.ts +234 -0
  266. package/src/rules-file-session-target.test.ts +207 -0
  267. package/src/rules-file-transport.test.ts +237 -0
  268. package/src/runtime-label.test.ts +22 -0
  269. package/src/runtime-label.ts +21 -0
  270. package/src/runtime-readiness.ts +90 -0
  271. package/src/schedule-agent-mcp-http.test.ts +391 -0
  272. package/src/schedule-agent.ts +192 -0
  273. package/src/schedule-starved.test.ts +92 -0
  274. package/src/schedule-starved.ts +114 -0
  275. package/src/scheduled-backoff-http.test.ts +193 -0
  276. package/src/scheduled-backoff.ts +64 -0
  277. package/src/scheduled-doorbell-nodeless-session.test.ts +134 -0
  278. package/src/scheduled-failure-backoff-2622.test.ts +145 -0
  279. package/src/scheduled-failure-code.test.ts +73 -0
  280. package/src/scheduled-failure-code.ts +105 -0
  281. package/src/scheduled-failures-http.test.ts +279 -0
  282. package/src/scheduled-failures.ts +377 -0
  283. package/src/scheduled-noprogress-backoff-2622.test.ts +133 -0
  284. package/src/scheduled-offline-backoff-probe.test.ts +56 -0
  285. package/src/scheduled-offline.test.ts +131 -0
  286. package/src/scheduled-offline.ts +66 -0
  287. package/src/scheduled-outcome-guidance-http.test.ts +139 -0
  288. package/src/scheduled-outcome-guidance.ts +9 -0
  289. package/src/scheduled-reply-unread-http.test.ts +212 -0
  290. package/src/scheduled-requirement-wake-http.test.ts +279 -0
  291. package/src/scheduled-requirement-wake.ts +125 -0
  292. package/src/scheduled-run-terminal.test.ts +268 -0
  293. package/src/scheduled-skip-blocking-task.test.ts +120 -0
  294. package/src/scheduled-skip-path-backoff-2622.test.ts +98 -0
  295. package/src/scheduled-stuck-http.test.ts +312 -0
  296. package/src/scheduled-stuck-notice-cap.test.ts +80 -0
  297. package/src/scheduled-stuck.ts +219 -0
  298. package/src/scheduled-tasks-http.test.ts +679 -0
  299. package/src/scheduled-tasks.ts +959 -0
  300. package/src/scheduled-work-outcome-http.test.ts +154 -0
  301. package/src/scheduled-work-outcome.ts +50 -0
  302. package/src/scoped-secrets.ts +139 -0
  303. package/src/send-dedup-request-id.test.ts +229 -0
  304. package/src/send-reply-agent-warning.test.ts +202 -0
  305. package/src/send-reply-alias-optional.test.ts +131 -0
  306. package/src/send-reply-attachments.test.ts +458 -0
  307. package/src/send_dedup.test.ts +54 -0
  308. package/src/send_dedup.ts +52 -6
  309. package/src/serve-error.test.ts +38 -0
  310. package/src/serve-error.ts +27 -0
  311. package/src/server.ts +5997 -0
  312. package/src/session-task-on-dispatch.ts +14 -0
  313. package/src/session-token-ownership-http.test.ts +122 -0
  314. package/src/shared/codex-inventory.ts +41 -0
  315. package/src/shared/daemon-provider-login.ts +31 -0
  316. package/src/shared/daemon-provider-snapshot.ts +52 -0
  317. package/src/shared/external-schedule-contract.ts +60 -0
  318. package/src/shared/node-name.test.ts +62 -0
  319. package/src/shared/node-name.ts +161 -0
  320. package/src/shared/provider-application.ts +29 -0
  321. package/src/shared/provider-collection.ts +14 -0
  322. package/src/shared/provider-initialization.ts +8 -0
  323. package/src/shared/reserved-env-drift.test.ts +10 -0
  324. package/src/shared/scoped-secret-contract.ts +5 -0
  325. package/src/shared/task-content-limit-drift.test.ts +28 -0
  326. package/src/shared/task-content-limit.ts +25 -0
  327. package/src/side-thread-command-transport.test.ts +312 -0
  328. package/src/side-thread-command-transport.ts +318 -0
  329. package/src/side-thread-http-integration.test.ts +233 -0
  330. package/src/side-thread-http.ts +504 -0
  331. package/src/side-thread-production.test.ts +72 -0
  332. package/src/side-thread-production.ts +118 -0
  333. package/src/side-thread.test.ts +1067 -0
  334. package/src/side-thread.ts +2499 -0
  335. package/src/skillhub-http.test.ts +108 -0
  336. package/src/sqlite-close-checkpoint.test.ts +78 -0
  337. package/src/start-node.test.ts +264 -0
  338. package/src/status-alias-filter-http.test.ts +106 -0
  339. package/src/status-alias-resolver-http.test.ts +163 -0
  340. package/src/status-alias-resolver.ts +19 -0
  341. package/src/status-node-id-filter-http.test.ts +161 -0
  342. package/src/status-read-cache-http.test.ts +229 -0
  343. package/src/status-read-cache.ts +122 -0
  344. package/src/stop-delete-node.test.ts +567 -1
  345. package/src/task-access-http.test.ts +402 -0
  346. package/src/task-access.ts +420 -0
  347. package/src/task-activity.ts +60 -0
  348. package/src/task-auth-origin-http.test.ts +93 -0
  349. package/src/task-auth-origin.test.ts +24 -0
  350. package/src/task-auth-origin.ts +7 -0
  351. package/src/task-consumption.test.ts +482 -0
  352. package/src/task-diagnostic-http.test.ts +149 -0
  353. package/src/task-diagnostic.test.ts +115 -0
  354. package/src/task-diagnostic.ts +118 -0
  355. package/src/task-expiry-notice-http.test.ts +287 -0
  356. package/src/task-expiry-notice.ts +315 -0
  357. package/src/task-idempotency-mcp.test.ts +142 -0
  358. package/src/task-idempotency.test.ts +76 -0
  359. package/src/task-idempotency.ts +81 -0
  360. package/src/task-late-replies.ts +54 -0
  361. package/src/task-late-reply-http.test.ts +152 -0
  362. package/src/task-lifecycle-watcher-busy.test.ts +114 -0
  363. package/src/task-lifecycle-watcher.test.ts +204 -0
  364. package/src/task-lifecycle-watcher.ts +109 -0
  365. package/src/task-network-resolution-http.test.ts +140 -0
  366. package/src/task-offline-delivery-2668.test.ts +119 -0
  367. package/src/task-offline-delivery.ts +81 -0
  368. package/src/task-orphan-http.test.ts +287 -0
  369. package/src/task-orphan.ts +119 -0
  370. package/src/task-queue-ahead-http.test.ts +309 -0
  371. package/src/task-queue-ahead-scale.test.ts +236 -0
  372. package/src/task-queue-ahead.ts +186 -0
  373. package/src/task-rejection-log-http.test.ts +160 -0
  374. package/src/task-rejection-log.ts +49 -0
  375. package/src/task-sender-http.test.ts +143 -0
  376. package/src/task-stale-open-http.test.ts +290 -0
  377. package/src/task-stale-open.ts +103 -0
  378. package/src/tasks-pagination-http.test.ts +141 -0
  379. package/src/team-rules-status-http.test.ts +90 -0
  380. package/src/team-rules-status.test.ts +59 -0
  381. package/src/team-rules-status.ts +72 -0
  382. package/src/tool-audience-http.test.ts +230 -0
  383. package/src/tool-audience.ts +120 -0
  384. package/src/tools-list-json-schema.test.ts +94 -0
  385. package/src/tools.ts +4212 -404
  386. package/src/upload-early-reject-guard.test.ts +155 -0
  387. package/src/uploads-http.test.ts +97 -15
  388. package/src/uploads.ts +103 -6
  389. package/src/user-avatar-http.test.ts +74 -0
  390. package/src/user-avatar-image.ts +160 -0
  391. package/src/user-avatar-migration.test.ts +25 -0
  392. package/src/user-avatar-upload-http.test.ts +348 -0
  393. package/src/user-inbox-by-agent-http.test.ts +161 -0
  394. package/src/user-inbox-netid-notnull.test.ts +122 -0
  395. package/src/user-inbox-read-http.test.ts +223 -0
  396. package/src/user-inbox-schema.test.ts +54 -0
  397. package/src/version-stats.test.ts +66 -0
  398. package/src/version-stats.ts +109 -0
@@ -0,0 +1,425 @@
1
+ // 标签管理(POST /api/requirements/tags/ops + GET /api/requirements/tags 的 counts / colors / can_manage)
2
+ // —— HTTP 集成测试(真实 Bun.serve,私有端口,临时库)。
3
+ //
4
+ // 场景:Hub 管理员 admin 的网络 NET,另有一个不相干的网络 NET2(同名标签,不能被波及)。成员:
5
+ // alice —— scoped 成员(RFC-038 §9),只授权项目 P1;
6
+ // carol —— task_access='all' 的老成员;
7
+ // vic —— viewer。
8
+ // 正向:改名 / 合并 / 删除改写网络里每张带这个标签的卡(含归档的)、颜色跟着挪、写审计、updated_at 前移;
9
+ // carol 与 owner 能管;GET 带用量与颜色。
10
+ // 反向:scoped / viewer / 节点令牌被挡且一张卡都不改;scoped 的 counts / colors 只含看得见的卡;
11
+ // 不存在的标签 404、坏参数 400;事务中途失败一张都不改;别的网络不受影响。
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-tag-ops-"));
19
+ let BASE = "";
20
+ let hub: any = null;
21
+ let db: any = null;
22
+ const PW = "TagOpsPassw0rd!x";
23
+ let NET = "";
24
+ let NET2 = "";
25
+ let admin = { token: "", id: "" };
26
+ let other = { token: "", id: "" };
27
+ let alice = { token: "", id: "" };
28
+ let carol = { token: "", id: "" };
29
+ let vic = { token: "", id: "" };
30
+ let nodeToken = "";
31
+ let P1 = "";
32
+ const C: Record<string, string> = {};
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
+ const op = (token: string, payload: unknown, net = NET) => send(token, "POST", `/api/requirements/tags/ops?network_id=${net}`, payload);
47
+ const tagsOf = (token: string, net = NET) => send(token, "GET", `/api/requirements/tags?network_id=${net}`);
48
+ const cardTags = (name: string): string[] => JSON.parse(db.get("SELECT tags_json FROM requirements WHERE requirement_id = ?1", C[name]).tags_json);
49
+ const snapshot = () => Object.fromEntries(Object.keys(C).map(name => [name, cardTags(name)]));
50
+
51
+ beforeAll(async () => {
52
+ process.env.COMMHUB_DB ||= join(DIR, "hub.db");
53
+ process.env.COMMHUB_UPLOADS_DIR = join(DIR, "uploads");
54
+ process.env.HOST = "127.0.0.1";
55
+ ({ db } = await import("./db.js"));
56
+ const { createNetworkTokenForNode, register } = await import("./auth.js");
57
+ const stamp = Date.now();
58
+ const a = register(`to_admin_${stamp}`, PW, undefined, "Admin");
59
+ expect(a.ok).toBe(true);
60
+ admin = { token: a.token!, id: a.user!.user_id };
61
+ NET = a.network_id!;
62
+ db.run("UPDATE users SET role = 'admin' WHERE user_id = ?1", [admin.id]);
63
+ const b = register(`to_other_${stamp}`, PW, undefined, "Other");
64
+ expect(b.ok).toBe(true);
65
+ other = { token: b.token!, id: b.user!.user_id };
66
+ NET2 = b.network_id!;
67
+ const ntok = createNetworkTokenForNode(admin.id, NET, "tag-node");
68
+ expect(ntok.ok).toBe(true);
69
+ nodeToken = ntok.token!;
70
+
71
+ const mod: any = await import("./server.js");
72
+ hub = mod.bootServer({ port: 0, hostname: "127.0.0.1" });
73
+ BASE = `http://127.0.0.1:${hub.port}`;
74
+
75
+ const mk = async (username: string, role: string) => {
76
+ const r = await send(admin.token, "POST", "/api/admin/users", { username, password: PW, network_id: NET, role });
77
+ expect(r.status).toBe(200);
78
+ const login = await send("", "POST", "/api/auth/login", { username, password: PW });
79
+ expect(login.status).toBe(200);
80
+ return { token: login.body.token as string, id: login.body.user.user_id as string };
81
+ };
82
+ alice = await mk(`to_alice_${stamp}`, "member");
83
+ carol = await mk(`to_carol_${stamp}`, "member");
84
+ vic = await mk(`to_vic_${stamp}`, "viewer");
85
+ db.run("UPDATE network_members SET task_access = 'scoped' WHERE network_id = ?1 AND user_id = ?2", [NET, alice.id]);
86
+ db.run("UPDATE network_members SET task_access = 'all' WHERE network_id = ?1 AND user_id = ?2", [NET, carol.id]);
87
+
88
+ const p = await send(admin.token, "POST", "/api/requirements/projects", { network_id: NET, name: "to-P1" });
89
+ expect(p.status).toBe(201);
90
+ P1 = p.body.project.id;
91
+ const g = await send(admin.token, "PUT", `/api/networks/${NET}/members/${alice.id}/task-grants`, { project_grants: [{ project_id: P1, can_edit: true }] });
92
+ expect(g.status).toBe(200);
93
+
94
+ const card = async (name: string, tags: string[], extra: Record<string, unknown> = {}, token = admin.token, net = NET) => {
95
+ const r = await send(token, "POST", "/api/requirements", { network_id: net, name, tags, ...extra });
96
+ expect(r.status).toBe(201);
97
+ C[name] = r.body.requirement.id;
98
+ };
99
+ await card("visible", ["UI", "交互", "bug"], { project_id: P1 });
100
+ await card("hidden", ["UI", "secret"]);
101
+ await card("archived", ["UI", "旧"], { archived: true });
102
+ await card("both", ["交互", "TMWork", "UI"]);
103
+ await card("plain", []);
104
+ await card("net2", ["UI", "交互"], {}, other.token, NET2);
105
+ }, 30_000);
106
+
107
+ afterAll(() => {
108
+ try { hub?.stop?.(true); } catch {}
109
+ try { rmSync(DIR, { recursive: true, force: true }); } catch {}
110
+ });
111
+
112
+ describe("GET /api/requirements/tags", () => {
113
+ test("owner:tags 仍是排序后的字符串数组(旧 App 形状不变),多出 counts / colors / can_manage", async () => {
114
+ const r = await tagsOf(admin.token);
115
+ expect(r.status).toBe(200);
116
+ expect(r.body.tags).toEqual(["TMWork", "UI", "bug", "secret", "交互", "旧"]);
117
+ expect(r.body.counts).toEqual({ UI: 4, 交互: 2, bug: 1, secret: 1, 旧: 1, TMWork: 1 });
118
+ expect(r.body.colors).toEqual({});
119
+ expect(r.body.can_manage).toBe(true);
120
+ });
121
+
122
+ test("scoped 成员:counts 只数看得见的卡,不能管;viewer 与节点令牌也不能管;老成员能管", async () => {
123
+ const a = await tagsOf(alice.token);
124
+ expect(a.body.tags).toEqual(["UI", "bug", "交互"]);
125
+ expect(a.body.counts).toEqual({ UI: 1, bug: 1, 交互: 1 });
126
+ expect(a.body.can_manage).toBe(false);
127
+ expect((await tagsOf(vic.token)).body.can_manage).toBe(false);
128
+ expect((await send(nodeToken, "GET", "/api/requirements/tags")).body.can_manage).toBe(false);
129
+ expect((await tagsOf(carol.token)).body.can_manage).toBe(true);
130
+ });
131
+
132
+ test("列表响应的 capabilities 带 tag_ops", async () => {
133
+ const r = await send(admin.token, "GET", `/api/requirements?network_id=${NET}`);
134
+ expect(r.body.capabilities).toContain("tag_ops");
135
+ });
136
+ });
137
+
138
+ describe("被拒的调用一张卡都不改", () => {
139
+ test("scoped 成员 403(连他看得见的那张也不改,不做半套改名)", async () => {
140
+ const before = snapshot();
141
+ for (const payload of [{ op: "rename", from: "UI", to: "界面" }, { op: "delete", tag: "bug" }, { op: "merge", from: ["UI", "交互"], to: "x" }, { op: "color", tag: "UI", color: "#123456" }]) {
142
+ const r = await op(alice.token, payload);
143
+ expect(r.status).toBe(403);
144
+ expect(r.body.error).toBe("permission_denied");
145
+ }
146
+ expect(snapshot()).toEqual(before);
147
+ expect(db.get("SELECT COUNT(*) AS n FROM network_tags WHERE network_id = ?1", NET).n).toBe(0);
148
+ });
149
+
150
+ test("viewer 403;节点令牌 403 user_token_required;别的网络的 owner 碰不到这个网络", async () => {
151
+ const before = snapshot();
152
+ expect((await op(vic.token, { op: "delete", tag: "UI" })).status).toBe(403);
153
+ const n = await send(nodeToken, "POST", "/api/requirements/tags/ops", { op: "delete", tag: "UI" });
154
+ expect(n.status).toBe(403);
155
+ expect(n.body.error).toBe("user_token_required");
156
+ expect((await op(other.token, { op: "delete", tag: "UI" })).status).toBe(403);
157
+ expect(snapshot()).toEqual(before);
158
+ });
159
+
160
+ test("坏参数 400、不存在的标签 404、GET 到 ops 404", async () => {
161
+ expect((await op(admin.token, { op: "explode" })).body.error).toBe("invalid_tag_op");
162
+ expect((await op(admin.token, { op: "rename", from: "UI", to: "" })).body.error).toBe("invalid_tag");
163
+ expect((await op(admin.token, { op: "rename", from: "UI", to: "x".repeat(21) })).body.error).toBe("invalid_tag");
164
+ expect((await op(admin.token, { op: "rename", from: "UI", to: " UI " })).body.error).toBe("same_tag");
165
+ expect((await op(admin.token, { op: "merge", from: [], to: "UI" })).body.error).toBe("invalid_tag");
166
+ expect((await op(admin.token, { op: "merge", from: ["UI"], to: "UI" })).body.error).toBe("same_tag");
167
+ expect((await op(admin.token, { op: "color", tag: "UI", color: "red" })).body.error).toBe("invalid_tag_color");
168
+ const missing = await op(admin.token, { op: "delete", tag: "没有这个" });
169
+ expect(missing.status).toBe(404);
170
+ expect(missing.body.error).toBe("tag_not_found");
171
+ expect((await send(admin.token, "GET", `/api/requirements/tags/ops?network_id=${NET}`)).status).toBe(404);
172
+ });
173
+
174
+ test("事务:改到一半失败 → 一张都不改,颜色也不挪", async () => {
175
+ expect((await op(admin.token, { op: "color", tag: "UI", color: "#2563EB" })).status).toBe(200);
176
+ // 让其中一张卡的 UPDATE 抛错(SQLite 用 RAISE,PostgreSQL 用 plpgsql 触发器;PG 阶梯会跑这个文件)。
177
+ const pg = db.dialect === "postgres";
178
+ if (pg) {
179
+ db.exec(`CREATE OR REPLACE FUNCTION tag_ops_fail() RETURNS trigger AS $$ BEGIN IF NEW.requirement_id = '${C["both"]}' THEN RAISE EXCEPTION 'boom'; END IF; RETURN NEW; END $$ LANGUAGE plpgsql`);
180
+ db.exec("CREATE TRIGGER tag_ops_fail BEFORE UPDATE OF tags_json ON requirements FOR EACH ROW EXECUTE FUNCTION tag_ops_fail()");
181
+ } else {
182
+ db.exec(`CREATE TRIGGER tag_ops_fail BEFORE UPDATE OF tags_json ON requirements WHEN NEW.requirement_id = '${C["both"]}' BEGIN SELECT RAISE(ABORT, 'boom'); END;`);
183
+ }
184
+ const before = snapshot();
185
+ try {
186
+ const r = await op(admin.token, { op: "rename", from: "UI", to: "界面" });
187
+ expect(r.status).toBeGreaterThanOrEqual(500);
188
+ } finally {
189
+ db.exec(pg ? "DROP TRIGGER tag_ops_fail ON requirements" : "DROP TRIGGER tag_ops_fail");
190
+ if (pg) db.exec("DROP FUNCTION tag_ops_fail()");
191
+ }
192
+ expect(snapshot()).toEqual(before);
193
+ expect(db.get("SELECT color FROM network_tags WHERE network_id = ?1 AND name = 'UI'", NET).color).toBe("#2563eb");
194
+ });
195
+ });
196
+
197
+ describe("改名 / 合并 / 删除 / 颜色", () => {
198
+ test("颜色:设置(存小写)、GET 带出来;scoped 成员看不到他看不见的标签的颜色", async () => {
199
+ expect((await op(admin.token, { op: "color", tag: "secret", color: "#DC2626" })).status).toBe(200);
200
+ const r = await tagsOf(admin.token);
201
+ expect(r.body.colors).toEqual({ UI: "#2563eb", secret: "#dc2626" });
202
+ expect((await tagsOf(alice.token)).body.colors).toEqual({ UI: "#2563eb" });
203
+ expect((await op(admin.token, { op: "color", tag: "secret", color: null })).status).toBe(200);
204
+ expect((await tagsOf(admin.token)).body.colors).toEqual({ UI: "#2563eb" });
205
+ });
206
+
207
+ test("改名:每张卡(含看不见的、归档的)都改,位置不变;颜色跟着走;updated_at 前移;审计;别的网络不动", async () => {
208
+ const t0 = new Date().toISOString();
209
+ const r = await op(admin.token, { op: "rename", from: "UI", to: "界面" });
210
+ expect(r.status).toBe(200);
211
+ expect(r.body).toEqual({ ok: true, op: "rename", affected: 4, reparented: 0 });
212
+ expect(cardTags("visible")).toEqual(["界面", "交互", "bug"]);
213
+ expect(cardTags("hidden")).toEqual(["界面", "secret"]);
214
+ expect(cardTags("archived")).toEqual(["界面", "旧"]);
215
+ expect(cardTags("both")).toEqual(["交互", "TMWork", "界面"]);
216
+ expect(cardTags("net2")).toEqual(["UI", "交互"]);
217
+ expect((await tagsOf(admin.token)).body.colors).toEqual({ 界面: "#2563eb" });
218
+ const row = db.get("SELECT updated_at, updated_by_json FROM requirements WHERE requirement_id = ?1", C["hidden"]);
219
+ expect(row.updated_at >= t0).toBe(true);
220
+ expect(JSON.parse(row.updated_by_json)).toEqual({ kind: "user", id: admin.id });
221
+ const audit = db.get("SELECT detail, target_id, network_id FROM audit_log WHERE action = 'requirement_tag_rename' ORDER BY id DESC LIMIT 1");
222
+ expect(audit.target_id).toBe("界面");
223
+ expect(audit.network_id).toBe(NET);
224
+ expect(JSON.parse(audit.detail)).toEqual({ op: "rename", from: "UI", to: "界面", affected: 4 });
225
+ // 这次改动 updated_since 同步得到(包括 GET 列表)。
226
+ const since = await send(admin.token, "GET", `/api/requirements?network_id=${NET}&include_archived=1&updated_since=${encodeURIComponent(t0)}`);
227
+ expect(since.body.requirements.map((x: any) => x.name).sort()).toEqual(["archived", "both", "hidden", "visible"]);
228
+ });
229
+
230
+ test("改名成已存在的标签 = 合并,同一张卡上不出现两次", async () => {
231
+ const r = await op(carol.token, { op: "rename", from: "交互", to: "界面" });
232
+ expect(r.body.affected).toBe(2);
233
+ expect(cardTags("visible")).toEqual(["界面", "bug"]);
234
+ expect(cardTags("both")).toEqual(["界面", "TMWork"]);
235
+ });
236
+
237
+ test("合并:多个来源进一个新标签;目标没颜色就继承来源的;来源颜色行删掉", async () => {
238
+ expect((await op(admin.token, { op: "color", tag: "旧", color: "#16a34a" })).status).toBe(200);
239
+ const r = await op(admin.token, { op: "merge", from: ["bug", "旧", "secret", "不存在"], to: "杂项" });
240
+ expect(r.body).toEqual({ ok: true, op: "merge", affected: 3, reparented: 0 });
241
+ expect(cardTags("visible")).toEqual(["界面", "杂项"]);
242
+ expect(cardTags("hidden")).toEqual(["界面", "杂项"]);
243
+ expect(cardTags("archived")).toEqual(["界面", "杂项"]);
244
+ expect((await tagsOf(admin.token)).body.colors).toEqual({ 界面: "#2563eb", 杂项: "#16a34a" });
245
+ expect(db.get("SELECT COUNT(*) AS n FROM network_tags WHERE network_id = ?1 AND name = '旧'", NET).n).toBe(0);
246
+ });
247
+
248
+ test("合并进已有颜色的目标:目标颜色不变", async () => {
249
+ const r = await op(admin.token, { op: "merge", from: ["杂项"], to: "界面" });
250
+ expect(r.body.affected).toBe(3);
251
+ expect((await tagsOf(admin.token)).body.colors).toEqual({ 界面: "#2563eb" });
252
+ });
253
+
254
+ test("删除:从每张卡上拿掉(卡保留),颜色行删掉,审计带 affected", async () => {
255
+ const r = await op(admin.token, { op: "delete", tag: "界面" });
256
+ expect(r.body).toEqual({ ok: true, op: "delete", affected: 4, reparented: 0 });
257
+ expect(cardTags("visible")).toEqual([]);
258
+ expect(cardTags("both")).toEqual(["TMWork"]);
259
+ expect(db.get("SELECT COUNT(*) AS n FROM requirements WHERE network_id = ?1", NET).n).toBe(5);
260
+ expect(db.get("SELECT COUNT(*) AS n FROM network_tags WHERE network_id = ?1", NET).n).toBe(0);
261
+ const audit = db.get("SELECT detail FROM audit_log WHERE action = 'requirement_tag_delete' ORDER BY id DESC LIMIT 1");
262
+ expect(JSON.parse(audit.detail)).toEqual({ op: "delete", tag: "界面", affected: 4 });
263
+ expect((await tagsOf(admin.token)).body.tags).toEqual(["TMWork"]);
264
+ expect(cardTags("net2")).toEqual(["UI", "交互"]);
265
+ });
266
+ });
267
+
268
+ // ── 改父级(reparent) ──
269
+ // 客户端(0.297+)的「管理标签」里要能改父级;Hub 侧此前只缺这一个 op。
270
+ // 这里只验树:reparent 不给标签改名、不动任何卡片的 tags 数组。
271
+ describe("改父级 reparent", () => {
272
+ const createTag = (token: string, name: string, parent: string | null = null) =>
273
+ send(token, "POST", `/api/requirements/tags/create?network_id=${NET}`, { name, parent_id: parent });
274
+ const nodesOf = async (token: string) =>
275
+ (await send(token, "GET", `/api/requirements/tags?network_id=${NET}`)).body.nodes as Array<{ name: string; parent_id: string | null; depth: number; registered: boolean }>;
276
+ const nodeOf = async (token: string, name: string) => (await nodesOf(token)).find(node => node.name === name)!;
277
+
278
+ test("搬到另一个标签下面,再搬回顶层:父与深度都跟着变,卡片一张都不动", async () => {
279
+ expect((await createTag(admin.token, "RP根")).status).toBe(201);
280
+ expect((await createTag(admin.token, "RP枝")).status).toBe(201);
281
+ expect((await createTag(admin.token, "RP叶", "RP枝")).status).toBe(201);
282
+ const before = db.get("SELECT COUNT(*) AS n FROM requirements WHERE network_id = ?1", NET).n;
283
+
284
+ const moved = await op(admin.token, { op: "reparent", tag: "RP叶", parent: "RP根" });
285
+ expect(moved.status).toBe(200);
286
+ expect(moved.body).toMatchObject({ ok: true, op: "reparent", affected: 0, reparented: 1 });
287
+ expect(await nodeOf(admin.token, "RP叶")).toMatchObject({ parent_id: "RP根", depth: 2 });
288
+ // 原来是 RP枝 的子孙,搬走之后 RP枝 下面没有它了
289
+ expect((await nodesOf(admin.token)).filter(node => node.parent_id === "RP枝")).toEqual([]);
290
+
291
+ const back = await op(admin.token, { op: "reparent", tag: "RP叶", parent: null });
292
+ expect(back.status).toBe(200);
293
+ expect(await nodeOf(admin.token, "RP叶")).toMatchObject({ parent_id: null, depth: 1 });
294
+ // 只动树:卡片数与卡的标签都没变
295
+ expect(db.get("SELECT COUNT(*) AS n FROM requirements WHERE network_id = ?1", NET).n).toBe(before);
296
+ });
297
+
298
+ test("父是自己的子孙 = 环,拒绝(400 tag_parent_cycle),树一个字都不改", async () => {
299
+ expect((await createTag(admin.token, "RP环甲")).status).toBe(201);
300
+ expect((await createTag(admin.token, "RP环乙", "RP环甲")).status).toBe(201);
301
+ const r = await op(admin.token, { op: "reparent", tag: "RP环甲", parent: "RP环乙" });
302
+ expect(r.status).toBe(400);
303
+ expect(r.body.error).toBe("tag_parent_cycle");
304
+ expect(await nodeOf(admin.token, "RP环甲")).toMatchObject({ parent_id: null });
305
+ });
306
+
307
+ test("自己当自己的父:解析阶段就拒(400 tag_parent_cycle)", async () => {
308
+ const r = await op(admin.token, { op: "reparent", tag: "RP根", parent: "RP根" });
309
+ expect(r.status).toBe(400);
310
+ expect(r.body.error).toBe("tag_parent_cycle");
311
+ });
312
+
313
+ test("连子树一起搬:新父深度 + 子树高度 > 4 就拒(400 tag_depth_exceeded)", async () => {
314
+ expect((await createTag(admin.token, "RPD1")).status).toBe(201);
315
+ expect((await createTag(admin.token, "RPD2", "RPD1")).status).toBe(201);
316
+ expect((await createTag(admin.token, "RPD3", "RPD2")).status).toBe(201); // 3 层:1>2>3
317
+ expect((await createTag(admin.token, "RPX")).status).toBe(201);
318
+ expect((await createTag(admin.token, "RPY", "RPX")).status).toBe(201); // 2 层子树
319
+ // 把 2 层的 RPX(含 RPY)挂到第 3 层下面 → 最深 5 层 > 4
320
+ const r = await op(admin.token, { op: "reparent", tag: "RPX", parent: "RPD3" });
321
+ expect(r.status).toBe(400);
322
+ expect(r.body.error).toBe("tag_depth_exceeded");
323
+ expect(await nodeOf(admin.token, "RPX")).toMatchObject({ parent_id: null });
324
+ // 只搬叶子(高度 1)就正好 4 层,允许
325
+ const ok = await op(admin.token, { op: "reparent", tag: "RPY", parent: "RPD3" });
326
+ expect(ok.status).toBe(200);
327
+ expect(await nodeOf(admin.token, "RPY")).toMatchObject({ parent_id: "RPD3", depth: 4 });
328
+ });
329
+
330
+ test("父不存在 = 404,不静默升到根", async () => {
331
+ const r = await op(admin.token, { op: "reparent", tag: "RP根", parent: "不存在的父" });
332
+ expect(r.status).toBe(404);
333
+ expect(r.body.error).toBe("tag_parent_not_found");
334
+ expect(await nodeOf(admin.token, "RP根")).toMatchObject({ parent_id: null });
335
+ });
336
+
337
+ test("缺 parent 键 = 400(不能用「没传」把标签静默升到根);parent 为空串 = 顶层", async () => {
338
+ const missing = await op(admin.token, { op: "reparent", tag: "RP根" });
339
+ expect(missing.status).toBe(400);
340
+ expect(missing.body.error).toBe("invalid_tag_parent_id");
341
+ expect(await nodeOf(admin.token, "RP根")).toMatchObject({ parent_id: null });
342
+
343
+ expect((await op(admin.token, { op: "reparent", tag: "RP根", parent: "RPD1" })).status).toBe(200);
344
+ const root = await op(admin.token, { op: "reparent", tag: "RP根", parent: "" });
345
+ expect(root.status).toBe(200);
346
+ expect(await nodeOf(admin.token, "RP根")).toMatchObject({ parent_id: null });
347
+ });
348
+
349
+ test("只在卡片上出现过的老标签也能改父级:先登记成节点,再挂到父下面", async () => {
350
+ const inUse = (await nodesOf(admin.token)).find(node => node.registered === false);
351
+ if (!inUse) return; // 该网络里没有"未登记但在用"的标签时,这条不适用
352
+ const r = await op(admin.token, { op: "reparent", tag: inUse.name, parent: "RPD1" });
353
+ expect(r.status).toBe(200);
354
+ const after = await nodeOf(admin.token, inUse.name);
355
+ expect(after).toMatchObject({ parent_id: "RPD1", depth: 2, registered: true });
356
+ // 卡片上的标签字符串不变(改父级不是改名)
357
+ const stillUsed = db.all<{ tags_json: string }>("SELECT tags_json FROM requirements WHERE network_id = ?1 AND tags_json LIKE ?2", NET, `%${inUse.name}%`);
358
+ expect(stillUsed.length).toBeGreaterThan(0);
359
+ });
360
+
361
+ test("reparent 走同一把标签管理锁:节点令牌与 viewer 都拒(403),树不变", async () => {
362
+ const byNode = await op(nodeToken, { op: "reparent", tag: "RP根", parent: "RPD1" });
363
+ expect(byNode.status).toBe(403);
364
+ const byViewer = await op(vic.token, { op: "reparent", tag: "RP根", parent: "RPD1" });
365
+ expect(byViewer.status).toBe(403);
366
+ expect(await nodeOf(admin.token, "RP根")).toMatchObject({ parent_id: null });
367
+ });
368
+ });
369
+
370
+ describe("改父级 reparent —— 被拒绝时不留副作用", () => {
371
+ const nodes = async () => (await send(admin.token, "GET", `/api/requirements/tags?network_id=${NET}`)).body.nodes as Array<{ name: string; parent_id: string | null; registered: boolean }>;
372
+ test("只在卡片上用过的标签,reparent 到不存在的父:404 且**不会**被登记进树", async () => {
373
+ const before = (await nodes()).filter(node => !node.registered).map(node => node.name);
374
+ if (!before.length) return; // 该网络里没有"未登记但在用"的标签时,这条不适用
375
+ const name = before[0];
376
+ const r = await op(admin.token, { op: "reparent", tag: name, parent: "根本没有这个父" });
377
+ expect(r.status).toBe(404);
378
+ expect(r.body.error).toBe("tag_parent_not_found");
379
+ // 关键:事务返回错误码是**提交**语义,若先 INSERT 登记再报错,这里就会看到 registered=true
380
+ const after = (await nodes()).find(node => node.name === name);
381
+ expect(after?.registered ?? false).toBe(false);
382
+ });
383
+ });
384
+
385
+ // ── MCP 面(#2204 缺口 2)──
386
+ // 一个工具(action 分派)而不是 list + op 两个:tools/list 字节预算是硬约束,见 tools.ts 的注释。
387
+ describe("requirement_tags (MCP)", () => {
388
+ async function mcp(token: string, name: string, args: Record<string, unknown>) {
389
+ const r = await fetch(`${BASE}/mcp`, { method: "POST", headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json", Accept: "application/json, text/event-stream" },
390
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } }) });
391
+ const raw = await r.text(), line = raw.split("\n").find(x => x.startsWith("data: "));
392
+ const envelope = JSON.parse(line ? line.slice(6) : raw);
393
+ try { return JSON.parse(envelope.result.content[0].text); } catch { return { mcpError: envelope.error ?? envelope.result }; }
394
+ }
395
+ const nodes = async (token: string) => (await send(token, "GET", `/api/requirements/tags?network_id=${NET}`)).body.nodes as Array<{ name: string; parent_id: string | null; depth: number; registered: boolean }>;
396
+
397
+ test("action=list 返回标签树(含 parent/depth/registered);action=reparent 走同一条 REST 语义", async () => {
398
+ expect((await send(admin.token, "POST", `/api/requirements/tags/create?network_id=${NET}`, { name: "MCP父", parent_id: null })).status).toBe(201);
399
+ expect((await send(admin.token, "POST", `/api/requirements/tags/create?network_id=${NET}`, { name: "MCP子", parent_id: null })).status).toBe(201);
400
+
401
+ const listed = await mcp(admin.token, "requirement_tags", { action: "list" });
402
+ const rows = listed.nodes as Array<{ name: string; parent_id: string | null; depth: number; registered: boolean }>;
403
+ expect(rows.find(node => node.name === "MCP父")).toMatchObject({ parent_id: null, depth: 1, registered: true });
404
+ expect(rows.find(node => node.name === "MCP子")).toMatchObject({ parent_id: null, depth: 1 });
405
+
406
+ const moved = await mcp(admin.token, "requirement_tags", { action: "reparent", tag: "MCP子", parent: "MCP父" });
407
+ expect(moved).toMatchObject({ ok: true, op: "reparent", affected: 0, reparented: 1 });
408
+ expect((await nodes(admin.token)).find(node => node.name === "MCP子")).toMatchObject({ parent_id: "MCP父", depth: 2 });
409
+
410
+ // 与 REST 同一套错误码:不传 parent 键 ≠ 升到顶层
411
+ const missing = await mcp(admin.token, "requirement_tags", { action: "reparent", tag: "MCP子" });
412
+ expect(missing.error).toBe("invalid_tag_parent_id");
413
+ expect((await nodes(admin.token)).find(node => node.name === "MCP子")).toMatchObject({ parent_id: "MCP父" });
414
+ });
415
+
416
+ test("节点令牌:能 list,但写操作被拒(403 permission_denied),树不变", async () => {
417
+ const listed = await mcp(nodeToken, "requirement_tags", { action: "list" });
418
+ expect(Array.isArray(listed.nodes)).toBe(true);
419
+ const write = await mcp(nodeToken, "requirement_tags", { action: "reparent", tag: "MCP子", parent: null });
420
+ expect(write.status).toBe(403);
421
+ // 写操作先过「要人的令牌」这道闸(tags_write),再到 owner/admin 判定;节点令牌停在前一道。
422
+ expect(["user_token_required", "permission_denied"]).toContain(write.error);
423
+ expect((await nodes(admin.token)).find(node => node.name === "MCP子")).toMatchObject({ parent_id: "MCP父" });
424
+ });
425
+ });