@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,141 @@
1
+ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2
+ import { mkdtempSync, rmSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+
6
+ const PRIVATE_DB_DIR = mkdtempSync(join(tmpdir(), "anet-task-pagination-"));
7
+ process.env.COMMHUB_DB ||= join(PRIVATE_DB_DIR, "hub.db");
8
+
9
+ let db: typeof import("./db.js").db;
10
+ let register: typeof import("./auth.js").register;
11
+ let server: ReturnType<typeof Bun.serve>;
12
+ let base = "";
13
+ let tokenA = "";
14
+ let networkA = "";
15
+ let networkB = "";
16
+
17
+ function seedTask(
18
+ taskId: string,
19
+ networkId: string,
20
+ toName: string,
21
+ createdAt: string,
22
+ ): void {
23
+ db.run(
24
+ `INSERT INTO tasks
25
+ (task_id, from_name, to_name, priority, status, content, network_id, created_at)
26
+ VALUES (?1, 'sender', ?2, 'normal', 'delivered', ?1, ?3, ?4)`,
27
+ [taskId, toName, networkId, createdAt],
28
+ );
29
+ }
30
+
31
+ // 30s 而不是 bun 默认的 5s:这个 hook 跑 register()(KDF)+bootServer(),
32
+ // 本机空载基线 ~620ms,而 2026-08-17 与 2026-08-31 两次 CI 上它被 5s 上限打死
33
+ // (0 pass / 1 fail / Ran 1 test —— 见 #928、#1627)。5247ms 是**被截断的下界**,
34
+ // 不是测量值,所以余量按基线的 ~48x 取,而不是按那个数取。
35
+ beforeAll(async () => {
36
+ ({ db } = await import("./db.js"));
37
+ ({ register } = await import("./auth.js"));
38
+ const b = register(`page_b_${Date.now()}`, "PageTest-B-Strong!", undefined, "seed-b");
39
+ // The first registered user is the instance admin and may read all
40
+ // networks. Register the foreign fixture first so tokenA exercises the
41
+ // ordinary member-scoped path rather than the admin bypass.
42
+ const a = register(`page_a_${Date.now()}`, "PageTest-A-Strong!", undefined, "seed-a");
43
+ expect(a.ok).toBe(true);
44
+ expect(b.ok).toBe(true);
45
+ tokenA = a.token!;
46
+ networkA = a.network_id!;
47
+ networkB = b.network_id!;
48
+
49
+ seedTask("a-new", networkA, "agent-a", "2026-01-04 00:00:00");
50
+ seedTask("tie-z", networkA, "agent-a", "2026-01-05 00:00:00");
51
+ seedTask("tie-y", networkA, "agent-a", "2026-01-05 00:00:00");
52
+ seedTask("tie-x", networkA, "agent-a", "2026-01-05 00:00:00");
53
+ seedTask("a-cursor", networkA, "agent-a", "2026-01-03 00:00:00");
54
+ seedTask("a-old-2", networkA, "agent-a", "2026-01-02 00:00:00");
55
+ seedTask("a-old-1", networkA, "agent-b", "2026-01-01 00:00:00");
56
+ seedTask("b-old", networkB, "agent-a", "2026-01-02 12:00:00");
57
+
58
+ const mod = await import("./server.js");
59
+ server = mod.bootServer({ port: 0, hostname: "127.0.0.1" });
60
+ base = `http://127.0.0.1:${server.port}`;
61
+ }, 30_000);
62
+
63
+ afterAll(() => {
64
+ try { server?.stop(true); } catch {}
65
+ try { rmSync(PRIVATE_DB_DIR, { recursive: true, force: true }); } catch {}
66
+ });
67
+
68
+ async function list(query: string): Promise<{ response: Response; body: any }> {
69
+ const response = await fetch(`${base}/api/tasks?skip_stats=1&${query}`, {
70
+ headers: { Authorization: `Bearer ${tokenA}` },
71
+ });
72
+ return { response, body: await response.json() };
73
+ }
74
+
75
+ describe("GET /api/tasks cursor pagination", () => {
76
+ test("before is exclusive and remains network-scoped", async () => {
77
+ const { response, body } = await list("before=2026-01-03%2000%3A00%3A00&limit=20");
78
+ expect(response.status).toBe(200);
79
+ expect(body.tasks.map((row: any) => row.task_id)).toEqual(["a-old-2", "a-old-1"]);
80
+ expect(body.tasks.some((row: any) => row.task_id === "a-cursor")).toBe(false);
81
+ expect(body.tasks.some((row: any) => row.task_id === "b-old")).toBe(false);
82
+ });
83
+
84
+ test("ISO cursor normalizes to SQLite UTC and composes with to_name", async () => {
85
+ const { body } = await list("before=2026-01-03T00%3A00%3A00Z&to_name=agent-a&limit=20");
86
+ expect(body.tasks.map((row: any) => row.task_id)).toEqual(["a-old-2"]);
87
+ });
88
+
89
+ test("before_task_id preserves rows that share the cursor second", async () => {
90
+ const first = await list("limit=2");
91
+ expect(first.body.tasks.map((row: any) => row.task_id)).toEqual(["tie-z", "tie-y"]);
92
+ const cursor = first.body.tasks.at(-1);
93
+ const second = await list(
94
+ `before=${encodeURIComponent(cursor.created_at)}&before_task_id=${encodeURIComponent(cursor.task_id)}&limit=20`,
95
+ );
96
+ expect(second.response.status).toBe(200);
97
+ expect(second.body.tasks.map((row: any) => row.task_id)).toEqual([
98
+ "tie-x",
99
+ "a-new",
100
+ "a-cursor",
101
+ "a-old-2",
102
+ "a-old-1",
103
+ ]);
104
+ });
105
+
106
+ test("omitting before preserves the existing response shape and newest-first order", async () => {
107
+ const { body } = await list("limit=20");
108
+ expect(body.ok).toBe(true);
109
+ expect(body.count).toBe(7);
110
+ expect(body.tasks.map((row: any) => row.task_id)).toEqual([
111
+ "tie-z",
112
+ "tie-y",
113
+ "tie-x",
114
+ "a-new",
115
+ "a-cursor",
116
+ "a-old-2",
117
+ "a-old-1",
118
+ ]);
119
+ expect(body.stats).toBeUndefined();
120
+ });
121
+
122
+ test("empty, malformed, and rolled-over cursors fail closed", async () => {
123
+ for (const cursor of ["", "not-a-time", "2026-02-31 00:00:00"]) {
124
+ const { response, body } = await list(`before=${encodeURIComponent(cursor)}`);
125
+ expect(response.status).toBe(400);
126
+ expect(body).toEqual({ ok: false, error: "invalid_before" });
127
+ }
128
+ });
129
+
130
+ test("before_task_id requires a valid timestamp cursor and task id", async () => {
131
+ for (const query of [
132
+ "before_task_id=tie-y",
133
+ "before=2026-01-05%2000%3A00%3A00&before_task_id=",
134
+ `before=2026-01-05%2000%3A00%3A00&before_task_id=${"x".repeat(257)}`,
135
+ ]) {
136
+ const { response, body } = await list(query);
137
+ expect(response.status).toBe(400);
138
+ expect(body).toEqual({ ok: false, error: "invalid_before_task_id" });
139
+ }
140
+ });
141
+ });
@@ -0,0 +1,90 @@
1
+ // #2211 — the wired half: what the node reports must reach `/api/status` as one word.
2
+ //
3
+ // The pure derivation has its own tests (team-rules-status.test.ts). This file checks the
4
+ // three seams that can still be wrong after that module is correct:
5
+ // 1. the session row actually carries the reported columns (db.ts migration + tools.ts persist);
6
+ // 2. the projection compares against the *network's* current revision (not a global one);
7
+ // 3. a session that never reported stays byte-identical (no `team_rules` key at all).
8
+ import { describe, expect, test, beforeAll, afterAll } from "bun:test";
9
+ import "./require-explicit-test-db.js";
10
+ import { register } from "./auth.js";
11
+ import { db } from "./db.js";
12
+ import { ensureNetworkRules } from "./network-rules.js";
13
+
14
+ let BASE = "";
15
+ let server: any = null;
16
+ let token = "";
17
+ let netId = "";
18
+
19
+ async function getStatus(query = "") {
20
+ const res = await fetch(`${BASE}/api/status${query}`, { headers: { Authorization: `Bearer ${token}` } });
21
+ expect(res.status).toBe(200);
22
+ return await res.json();
23
+ }
24
+
25
+ function seedSession(resumeId: string, alias: string, cols: Record<string, unknown> = {}) {
26
+ const keys = ["resume_id", "alias", "network_id", ...Object.keys(cols)];
27
+ const values = [resumeId, alias, netId, ...Object.values(cols)];
28
+ db.run(
29
+ `INSERT INTO sessions (${keys.join(",")}) VALUES (${keys.map((_, i) => `?${i + 1}`).join(",")})`,
30
+ values,
31
+ );
32
+ }
33
+
34
+ beforeAll(async () => {
35
+ const suffix = `${Date.now()}_${Math.floor(Math.random() * 1000)}`;
36
+ const a = register(`trs_${suffix}`, "TrsPw123Aa!", undefined, "trs");
37
+ expect(a.ok).toBe(true);
38
+ token = a.token!;
39
+ netId = a.network_id!;
40
+ const { bootServer } = await import("./server.js");
41
+ server = bootServer({ port: 0, hostname: "127.0.0.1" });
42
+ BASE = `http://127.0.0.1:${server.port}`;
43
+ }, 30_000);
44
+
45
+ afterAll(() => { try { server?.stop?.(true); } catch {} });
46
+
47
+ describe("#2211 — team rules state in /api/status", () => {
48
+ test("a session that never reported has no team_rules key", async () => {
49
+ seedSession(`never-${Date.now()}`, `never-${Date.now()}`);
50
+ const body = await getStatus();
51
+ const row = body.sessions.find((s: any) => s.alias.startsWith("never-"));
52
+ expect(row).toBeTruthy();
53
+ expect("team_rules" in row).toBe(false);
54
+ });
55
+
56
+ test("reported revision behind the network's → outdated; equal → current", async () => {
57
+ ensureNetworkRules(db); // created lazily by the rules API; this test seeds it directly
58
+ const rev = Number((db.get<{ revision: number }>("SELECT revision FROM network_rules WHERE network_id = ?1", netId)?.revision) ?? 0) + 2;
59
+ db.run(
60
+ "INSERT INTO network_rules (network_id, content, revision, updated_at, updated_by_json) VALUES (?1, 'rules', ?2, datetime('now'), NULL) ON CONFLICT(network_id) DO UPDATE SET revision = ?2",
61
+ [netId, rev],
62
+ );
63
+ seedSession(`behind-${Date.now()}`, `behind-${Date.now()}`, { team_rules_revision: rev - 1, team_rules_status: "unchanged" });
64
+ seedSession(`equal-${Date.now()}`, `equal-${Date.now()}`, { team_rules_revision: rev, team_rules_status: "injected" });
65
+ const body = await getStatus();
66
+ const behind = body.sessions.find((s: any) => s.alias.startsWith("behind-"));
67
+ const equal = body.sessions.find((s: any) => s.alias.startsWith("equal-"));
68
+ expect(behind.team_rules.state).toBe("outdated");
69
+ expect(behind.team_rules.applied_revision).toBe(rev - 1);
70
+ expect(behind.team_rules.current_revision).toBe(rev);
71
+ expect(equal.team_rules.state).toBe("current");
72
+ });
73
+
74
+ test("an error report is failed, with its reason", async () => {
75
+ seedSession(`errored-${Date.now()}`, `errored-${Date.now()}`, {
76
+ team_rules_status: "error", team_rules_reason: "expected exactly one BEGIN",
77
+ });
78
+ const body = await getStatus();
79
+ const row = body.sessions.find((s: any) => s.alias.startsWith("errored-"));
80
+ expect(row.team_rules.state).toBe("failed");
81
+ expect(row.team_rules.reason).toBe("expected exactly one BEGIN");
82
+ });
83
+
84
+ test("the light projection keeps its exact shape (no team_rules, no extra bytes)", async () => {
85
+ const res = await fetch(`${BASE}/api/status?light=1`, { headers: { Authorization: `Bearer ${token}` } });
86
+ expect(res.status).toBe(200);
87
+ const body = await res.json();
88
+ for (const row of body.sessions) expect("team_rules" in row).toBe(false);
89
+ });
90
+ });
@@ -0,0 +1,59 @@
1
+ // #2211 — the four states, as decisions rather than as prose.
2
+ //
3
+ // The point of these cases is that "behind" and "failed" are different words:
4
+ // v1 injects at full start, so a node that simply has not restarted is `outdated`.
5
+ // Calling that `failed` would send someone to debug a node that is doing fine.
6
+ import { describe, expect, test } from "bun:test";
7
+ import { deriveTeamRulesView } from "./team-rules-status";
8
+
9
+ const report = (o: Record<string, unknown>) => o as any;
10
+
11
+ describe("deriveTeamRulesView (#2211)", () => {
12
+ test("a node that never attempted is omitted entirely (not reported as null state)", () => {
13
+ expect(deriveTeamRulesView(null, 3)).toBeNull();
14
+ expect(deriveTeamRulesView(undefined, 3)).toBeNull();
15
+ expect(deriveTeamRulesView(report({}), 3)).toBeNull();
16
+ });
17
+
18
+ test("applied revision equals the network's current revision → current", () => {
19
+ const v = deriveTeamRulesView(report({ revision: 3, status: "injected", at: "2026-10-24T12:00:00Z" }), 3)!;
20
+ expect(v).toMatchObject({ state: "current", applied_revision: 3, current_revision: 3 });
21
+ });
22
+
23
+ test("behind the current revision → outdated, with the reason kept for context", () => {
24
+ const v = deriveTeamRulesView(report({ revision: 2, status: "unchanged" }), 3)!;
25
+ expect(v.state).toBe("outdated");
26
+ expect(v.applied_revision).toBe(2);
27
+ expect(v.current_revision).toBe(3);
28
+ });
29
+
30
+ test("an error is failed even when it also happens to carry the current revision", () => {
31
+ const v = deriveTeamRulesView(report({ revision: 3, status: "error", reason: "expected exactly one BEGIN" }), 3)!;
32
+ expect(v.state).toBe("failed");
33
+ expect(v.reason).toBe("expected exactly one BEGIN");
34
+ });
35
+
36
+ test("skipped with no revision (disabled / hub unreachable) → never, reason preserved", () => {
37
+ const v = deriveTeamRulesView(report({ revision: null, status: "skipped", reason: "hub_timeout" }), 3)!;
38
+ expect(v).toMatchObject({ state: "never", applied_revision: null, reason: "hub_timeout" });
39
+ });
40
+
41
+ test("the network lost its rules but the node still carries a block → outdated", () => {
42
+ const v = deriveTeamRulesView(report({ revision: 4, status: "injected" }), null)!;
43
+ expect(v.state).toBe("outdated");
44
+ expect(v.current_revision).toBeNull();
45
+ });
46
+
47
+ test("a hub rollback (node ahead of the current revision) is not called current", () => {
48
+ const v = deriveTeamRulesView(report({ revision: 5, status: "injected" }), 3)!;
49
+ expect(v.state).toBe("outdated");
50
+ });
51
+
52
+ test("malformed input never throws and never fabricates a revision", () => {
53
+ const v = deriveTeamRulesView(report({ revision: "3" as any, status: 42 as any, reason: 7 as any }), 3);
54
+ expect(v).not.toBeNull();
55
+ expect(v!.state).toBe("never");
56
+ expect(v!.applied_revision).toBeNull();
57
+ expect(v!.reason).toBeNull();
58
+ });
59
+ });
@@ -0,0 +1,72 @@
1
+ // #2211 — turn "what the node last did" into one word an operator can act on.
2
+ //
3
+ // The node reports `team_rules: { revision, status, reason?, at }` on every status
4
+ // report (agent-node .156). The Hub knows the network's current revision. This module
5
+ // is the pure comparison between the two — no database, no HTTP, so the rules are
6
+ // testable before any wiring exists.
7
+ //
8
+ // The four states are deliberately about *the node being behind*, not about a failed
9
+ // push: v1 injects at full start, so a node that has not restarted since a rule change
10
+ // is `outdated`, not `failed`. Calling that "failed" would blame the wrong side.
11
+ //
12
+ // current — applied revision equals the network's current revision
13
+ // outdated — this node has not picked up the current revision yet (restart needed)
14
+ // failed — the last attempt ended in an error; `reason` says why
15
+ // never — this node has never attempted an injection (or the rules are empty and
16
+ // it has nothing to apply)
17
+ //
18
+ // Unknown input never throws: a malformed report degrades to `never` with the reason
19
+ // preserved, because a status line is not worth a 500.
20
+
21
+ export type TeamRulesState = "current" | "outdated" | "failed" | "never";
22
+
23
+ export type TeamRulesReportIn = {
24
+ revision?: number | null;
25
+ status?: string | null;
26
+ reason?: string | null;
27
+ at?: string | null;
28
+ };
29
+
30
+ export type TeamRulesView = {
31
+ state: TeamRulesState;
32
+ applied_revision: number | null;
33
+ current_revision: number | null;
34
+ status: string | null;
35
+ reason: string | null;
36
+ at: string | null;
37
+ };
38
+
39
+ /**
40
+ * @param report what the node last reported (null/undefined = it never reported)
41
+ * @param currentRevision the network's current `network_rules.revision` (null when no row)
42
+ */
43
+ export function deriveTeamRulesView(
44
+ report: TeamRulesReportIn | null | undefined,
45
+ currentRevision: number | null,
46
+ ): TeamRulesView | null {
47
+ if (!report || (report.revision == null && !report.status)) return null;
48
+
49
+ const applied = typeof report.revision === "number" && Number.isFinite(report.revision) ? report.revision : null;
50
+ const current = typeof currentRevision === "number" && Number.isFinite(currentRevision) ? currentRevision : null;
51
+ const status = typeof report.status === "string" ? report.status : null;
52
+ const reason = typeof report.reason === "string" && report.reason ? report.reason : null;
53
+ const at = typeof report.at === "string" && report.at ? report.at : null;
54
+
55
+ let state: TeamRulesState;
56
+ if (status === "error") {
57
+ state = "failed";
58
+ } else if (applied == null) {
59
+ // attempted but nothing was applied (disabled / skipped with no revision)
60
+ state = "never";
61
+ } else if (current == null) {
62
+ // the network has no rules row (revision absent) but the node carries a block
63
+ state = "outdated";
64
+ } else if (applied === current) {
65
+ state = "current";
66
+ } else {
67
+ // behind (usual case) or ahead after a Hub rollback — either way it does not match
68
+ state = "outdated";
69
+ }
70
+
71
+ return { state, applied_revision: applied, current_revision: current, status, reason, at };
72
+ }
@@ -0,0 +1,230 @@
1
+ // #478 —— tools/list 按调用者给(tool-audience.ts)。钉住:
2
+ // 1. 每个注册的工具都在 TOOL_AUDIENCE 里归了类(新工具忘了归类 → 红),表里也没有已经不存在的工具;
3
+ // 2. 兼容回放:对每种调用者(节点:正常 / 只读 / 受限 / enforce 开关;人:owner / member / viewer),把每个工具都真调一次 ——
4
+ // 今天调得通的(不是那几种「不看参数就拒」的错误),一定还在它的列表里(协议工具在 opt-in 的列表里);
5
+ // 列表里藏起来的,调用一定回那几种拒绝之一。tools/call 不受影响(只滤列表)。
6
+ // 3. 每种角色的 tools/list 字节数(打印 before / after),各有上限(#476 的总上限仍管「全部工具」)。
7
+ // 跑法:cd server && COMMHUB_DB=/tmp/x.db bun test src/tool-audience-http.test.ts(PG 在 tests/test2123-hub-postgres-ladder 里注册)
8
+ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
9
+ import { mkdtempSync, rmSync } from "fs";
10
+ import { join } from "path";
11
+ import { tmpdir } from "os";
12
+ import { register, createNetworkTokenForNode } from "./auth.js";
13
+ import { db } from "./db.js";
14
+ import { TOOL_AUDIENCE } from "./tool-audience.js";
15
+
16
+ const DIR = mkdtempSync(join(tmpdir(), "anet-tool-audience-"));
17
+ let BASE = "";
18
+ let hub: any = null;
19
+ const PW = "ToolAudiencePassw0rd!x";
20
+ let NET = "";
21
+ const T: Record<string, string> = {};
22
+
23
+ /** 处理函数里「不看参数就拒」的错误码(用户令牌调节点工具 / 节点令牌调人的工具 / #487 的拒绝)。 */
24
+ const REFUSALS = new Set(["network_token_required", "node_token_required", "caller_not_a_daemon", "user_token_required", "node_token_cannot_browse_files", "node_token_cannot_read_logs", "node_permission_denied"]);
25
+
26
+ async function rpc(token: string, method: string, params: unknown, headers: Record<string, string> = {}) {
27
+ const res = await fetch(`${BASE}/mcp`, { method: "POST", headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json", Accept: "application/json, text/event-stream", "MCP-Protocol-Version": "2025-03-26", ...headers }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }) });
28
+ const raw = await res.text();
29
+ const line = raw.split("\n").filter(x => x.startsWith("data:")).at(-1);
30
+ return { json: line ? JSON.parse(line.slice(5)) : JSON.parse(raw), bytes: 0 };
31
+ }
32
+ async function listTools(token: string, all = false): Promise<{ names: string[]; bytes: number; tools: any[] }> {
33
+ const { json } = await rpc(token, "tools/list", {}, all ? { "X-Anet-Tools": "all" } : {});
34
+ const tools = json.result.tools as any[];
35
+ return { names: tools.map(t => t.name), bytes: Buffer.byteLength(JSON.stringify({ tools }), "utf8"), tools };
36
+ }
37
+
38
+ // 参数:按 inputSchema 生成;名字认得的用真值;schema 有格式要求的给合法值(不给 → -32602,测试会让你补)。
39
+ const OVERRIDES: Record<string, Record<string, unknown>> = {
40
+ get_skill: { skill_id: "skill_probe" },
41
+ review_skill: { skill_id: "skill_probe" },
42
+ mark_tasks_runtime_submitted: { task_ids: ["task_probe"] },
43
+ mark_tasks_consumed: { task_ids: ["task_probe"] },
44
+ upsert_network_secret: { key: "PROBE_KEY" },
45
+ update_provider: { provider_id: "prov_probe" },
46
+ schedule_batch_interval: { schedule_ids: ["sched_probe"], every_seconds: 60 },
47
+ };
48
+ function fill(schema: any, key: string, ctx: Record<string, unknown>): unknown {
49
+ if (!schema) return "probe";
50
+ if (ctx[key] !== undefined) return ctx[key];
51
+ if (schema.enum) return schema.enum[0];
52
+ if (schema.anyOf) return fill(schema.anyOf.find((s: any) => s.type !== "null") ?? schema.anyOf[0], key, ctx);
53
+ const t = Array.isArray(schema.type) ? schema.type.find((x: string) => x !== "null") : schema.type;
54
+ if (t === "string") return schema.minLength && schema.minLength > 5 ? "p".repeat(schema.minLength) : "probe";
55
+ if (t === "integer" || t === "number") return schema.minimum ?? 1;
56
+ if (t === "boolean") return false;
57
+ if (t === "array") return [];
58
+ if (t === "object") { const o: Record<string, unknown> = {}; for (const k of schema.required ?? []) o[k] = fill(schema.properties?.[k], k, ctx); return o; }
59
+ return "probe";
60
+ }
61
+ let ALL_TOOLS: any[] = [];
62
+ const argsFor = (tool: any) => ({ ...(fill(tool.inputSchema, "", { network_id: NET, alias: "probe-victim", new_alias: "probe-victim", node_id: "node_ta_victim" }) as object), ...(OVERRIDES[tool.name] ?? {}) });
63
+ async function callOutcome(token: string, tool: any): Promise<{ refused: boolean; schema: boolean; code: string }> {
64
+ const { json } = await rpc(token, "tools/call", { name: tool.name, arguments: argsFor(tool) });
65
+ if (json.error) return { refused: false, schema: json.error.code === -32602, code: `rpc:${json.error.code}` };
66
+ const text = String(json.result?.content?.[0]?.text ?? "");
67
+ if (/^MCP error -32602/.test(text)) return { refused: false, schema: true, code: "schema" };
68
+ let body: any = null;
69
+ try { body = JSON.parse(text); } catch {}
70
+ const code = body && body.ok === false ? String(body.error) : "ok";
71
+ // 受限成员的闸(agent_access_restricted)跑在处理函数前面,看传的 network_id;对节点 / 协议工具,处理函数后面还有一道
72
+ // 不看参数的 network_token_required(用户令牌换哪个网络都过不去),所以这时它也算拒。对「两边都能用」的工具不算。
73
+ const masked = code === "agent_access_restricted" && (TOOL_AUDIENCE[tool.name] === "node" || TOOL_AUDIENCE[tool.name] === "protocol");
74
+ return { refused: REFUSALS.has(code) || masked, schema: false, code };
75
+ }
76
+
77
+ beforeAll(async () => {
78
+ process.env.COMMHUB_DB ||= join(DIR, "hub.db");
79
+ process.env.COMMHUB_UPLOADS_DIR = join(DIR, "uploads");
80
+ process.env.HOST = "127.0.0.1";
81
+ delete process.env.COMMHUB_NODE_PERMISSIONS;
82
+ const owner = register(`ta_owner_${Date.now()}`, PW, undefined, "Owner");
83
+ NET = owner.network_id!;
84
+ T.owner = owner.token!;
85
+ const mod: any = await import("./server.js");
86
+ hub = mod.bootServer({ port: 0, hostname: "127.0.0.1" });
87
+ BASE = `http://127.0.0.1:${hub.port}`;
88
+ const mk = async (k: string, role: string) => {
89
+ const username = `ta_${k}_${Date.now()}`;
90
+ await fetch(`${BASE}/api/admin/users`, { method: "POST", headers: { Authorization: `Bearer ${T.owner}`, "Content-Type": "application/json" }, body: JSON.stringify({ username, password: PW, network_id: NET, role }) });
91
+ T[k] = (await (await fetch(`${BASE}/api/auth/login`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ username, password: PW }) })).json()).token;
92
+ };
93
+ await mk("member", "member");
94
+ await mk("viewer", "viewer");
95
+ for (const mode of ["normal", "readonly", "restricted"]) {
96
+ T[`node_${mode}`] = createNetworkTokenForNode(owner.user!.user_id, NET, `ta-${mode}`, `node_ta_${mode}`).token!;
97
+ db.run("UPDATE nodes SET permission_mode = ?1 WHERE node_id = ?2", [mode, `node_ta_${mode}`]);
98
+ }
99
+ createNetworkTokenForNode(owner.user!.user_id, NET, "probe-victim", "node_ta_victim");
100
+ // 没有身份的调用者 = 不过滤:用 owner 的「全部」作为全集(owner 是用户令牌,协议工具对它不列;全集取并集)。
101
+ const a = await listTools(T.node_normal, true);
102
+ const b = await listTools(T.owner);
103
+ const byName = new Map([...a.tools, ...b.tools].map(t => [t.name, t]));
104
+ ALL_TOOLS = [...byName.values()];
105
+ }, 60_000);
106
+
107
+ afterAll(() => {
108
+ delete process.env.COMMHUB_NODE_PERMISSIONS;
109
+ try { hub?.stop?.(true); } catch {}
110
+ try { rmSync(DIR, { recursive: true, force: true }); } catch {}
111
+ });
112
+
113
+ describe("every tool is classified", () => {
114
+ test("registry == TOOL_AUDIENCE (no unclassified tool, no stale entry)", async () => {
115
+ const registered = ALL_TOOLS.map(t => t.name).sort();
116
+ expect(registered.length).toBeGreaterThan(70);
117
+ expect(registered.filter(n => !TOOL_AUDIENCE[n])).toEqual([]);
118
+ expect(Object.keys(TOOL_AUDIENCE).filter(n => !registered.includes(n))).toEqual([]);
119
+ });
120
+ });
121
+
122
+ describe("compat replay: nothing callable today disappears from the list", () => {
123
+ const cases: Array<[string, string, string | null]> = [
124
+ ["node (normal, log)", "node_normal", null], ["node (readonly)", "node_readonly", null], ["node (restricted)", "node_restricted", null],
125
+ ["node (normal, enforce)", "node_normal", "enforce"], ["owner", "owner", null], ["member", "member", null], ["viewer", "viewer", null],
126
+ ];
127
+ for (const [label, key, flag] of cases) {
128
+ test(label, async () => {
129
+ if (flag) process.env.COMMHUB_NODE_PERMISSIONS = flag; else delete process.env.COMMHUB_NODE_PERMISSIONS;
130
+ try {
131
+ const isNode = key.startsWith("node_");
132
+ const listed = new Set((await listTools(T[key], isNode)).names);
133
+ // 「调得通 ⇒ 列着」,等价于「藏起来的 ⇒ 一定是那几种拒绝」。
134
+ const lost: string[] = [], schema: string[] = [];
135
+ for (const tool of ALL_TOOLS) {
136
+ const out = await callOutcome(T[key], tool);
137
+ if (out.schema) schema.push(tool.name);
138
+ if (!out.refused && !listed.has(tool.name)) lost.push(`${tool.name}(${out.code})`);
139
+ }
140
+ expect(schema).toEqual([]); // 每个工具都真跑到了处理函数(否则判不出能不能用)
141
+ expect(lost).toEqual([]);
142
+ } finally { delete process.env.COMMHUB_NODE_PERMISSIONS; }
143
+ }, 120_000);
144
+ }
145
+ });
146
+
147
+ describe("what each caller sees", () => {
148
+ test("node: no human-only tools; protocol tools only with X-Anet-Tools: all; user: no node / protocol tools", async () => {
149
+ const node = new Set((await listTools(T.node_normal)).names);
150
+ const nodeAll = new Set((await listTools(T.node_normal, true)).names);
151
+ const user = new Set((await listTools(T.owner)).names);
152
+ for (const [name, a] of Object.entries(TOOL_AUDIENCE)) {
153
+ expect([name, node.has(name)]).toEqual([name, a === "both" || a === "node"]);
154
+ expect([name, nodeAll.has(name)]).toEqual([name, a !== "user"]);
155
+ expect([name, user.has(name)]).toEqual([name, a === "both" || a === "user"]);
156
+ }
157
+ // ?tools=all is the same switch for clients that cannot set headers
158
+ const viaQuery = await fetch(`${BASE}/mcp?tools=all`, { method: "POST", headers: { Authorization: `Bearer ${T.node_normal}`, "Content-Type": "application/json", Accept: "application/json, text/event-stream", "MCP-Protocol-Version": "2025-03-26" }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list", params: {} }) });
159
+ const raw = await viaQuery.text();
160
+ const parsed = JSON.parse(raw.split("\n").filter(x => x.startsWith("data:")).at(-1)!.slice(5));
161
+ expect(parsed.result.tools.length).toBe(nodeAll.size);
162
+ });
163
+
164
+ test("node modes: readonly / restricted drop broadcast + node writes + human-only; enforce drops human-only for normal nodes", async () => {
165
+ const ro = new Set((await listTools(T.node_readonly)).names);
166
+ for (const n of ["broadcast", "update_node_config", "create_node", "clone_node", "upsert_provider"]) expect([n, ro.has(n)]).toEqual([n, false]);
167
+ for (const n of ["send_task", "requirements_update", "report_status", "get_all_status"]) expect([n, ro.has(n)]).toEqual([n, true]); // 看参数才拒的照列
168
+ expect(new Set((await listTools(T.node_normal)).names).has("upsert_provider")).toBe(true); // log 模式:调得通,照列
169
+ process.env.COMMHUB_NODE_PERMISSIONS = "enforce";
170
+ try { expect(new Set((await listTools(T.node_normal)).names).has("upsert_provider")).toBe(false); } finally { delete process.env.COMMHUB_NODE_PERMISSIONS; }
171
+ });
172
+
173
+ test("a hidden tool still answers tools/call exactly as before (only the list changes)", async () => {
174
+ const p = await rpc(T.node_normal, "tools/call", { name: "projects_create", arguments: { network_id: NET, name: "示例项目" } });
175
+ expect(JSON.parse(p.json.result.content[0].text).error).toBe("user_token_required");
176
+ const r = await rpc(T.owner, "tools/call", { name: "report_status", arguments: argsFor(ALL_TOOLS.find(t => t.name === "report_status")) });
177
+ expect(JSON.parse(r.json.result.content[0].text).error).toBe("network_token_required");
178
+ const g = await rpc(T.node_normal, "tools/call", { name: "get_config_update", arguments: {} });
179
+ expect(JSON.parse(g.json.result.content[0].text).ok).toBe(true); // 协议工具默认不列,但照常能调
180
+ });
181
+ });
182
+
183
+ describe("bytes per role (#476 ceilings stay meaningful per role)", () => {
184
+ // 全部工具(= 改动前每个调用者拿到的)71–72 KB;改动后按角色。改数字时在 PR 里写为什么。
185
+ // 量出来(#478 合入时):全部 74 个工具 71,559 B;节点 52 个 57,632 B(−19%);人 56 个 54,780 B(−23%)。留 ~1.5 KB 余量。
186
+ // Board #625 adds 2 human tools + 2 hidden daemon protocol tools. Measured:
187
+ // all 78 / 73,969 B; user 58 / 56,615 B; node remains 52 / 58,320 B.
188
+ // Board #733 adds 7 node-only schedule_* tools (user list unchanged). Measured before → after on the same run:
189
+ // node 52 / 58,836 B → 59 / 61,607 B (+2,771 B, ~396 B per tool of which ~180 B is SDK per-tool overhead —
190
+ // $schema + execution — after trimming schemas to bare field names; values are validated server-side);
191
+ // all 78 / 74,485 B → 85 / 77,256 B; user 58 / 56,834 B → 58 / 56,834 B. main had 164 B node headroom left,
192
+ // so any new node tool needs this; ceilings keep the same ~400–750 B margin.
193
+ // Review follow-up: descriptions / schemas cut further → node 59 / 61,100 B, all 85 / 76,749 B (−507 B each),
194
+ // leaving ≥ 700 B node margin even with #2488 (+116 B) merged.
195
+ // Board #822 adds confirmed fork fields, not tools. Same-image main 102dd0f2 → candidate:
196
+ // all 87 / 77,646 B → 78,976 B (+1,330); node 61 / 61,986 B → 62,368 B (+382);
197
+ // user 58 / 56,950 B → 57,163 B (+213). start_node adds 213 B, report_status 169 B;
198
+ // hidden pull/ack schemas account for the remaining 948 B. Keep strict receipt validation
199
+ // and unchanged audiences; budget only this measured addition (~130/520 B node/all margin).
200
+ // Board #654 adds report_status adoption_candidates (node-only schema, no new tool).
201
+ // Same tree, field removed → restored: all 87 / 79,078 B → 79,591 B (+513);
202
+ // node 61 / 62,433 B → 62,946 B (+513); user 58 / 57,228 B unchanged
203
+ // (report_status is not on the user list). Budget only this measured addition
204
+ // (~154/509 B node/all margin).
205
+ // #906 plus Hub #938 clone_node (all 91 / 81,228 B; node 62 / 63,281 B;
206
+ // user 60 / 58,169 B). OpenCode V2 catalog adds 2 user tools and 2 protocol
207
+ // tools. Measured on this combined tree: all 95 / 85,069 B; node 62 / 63,281 B
208
+ // unchanged (protocol tools stay off the node list); user 62 / 59,409 B.
209
+ // Ceilings keep about 400 B and nothing else.
210
+ // #1894(2026-10-23):新增一个 `departments` MCP 工具(list/create/update/delete/
211
+ // assign_agent 合并成一个,尽量小)。实测 node 64,112 B / user 60,117 B,比原上限
212
+ // 分别高 412 / 279 B —— 这是有意的功能增长(组织架构可由 Agent 直接调),不是文案偷偷变长。
213
+ // 留约 400 B 余量;再要加工具时请先合并动作或砍描述,别连续抬上限。
214
+ // #2204(2026-10-25):标签管理给 MCP。为了**不抬上限**,做了两件事:
215
+ // ① 合并成一个工具 `requirement_tags`(action 分派 list/rename/merge/delete/color/reparent),
216
+ // 而不是 list + op 两个(照 #1894 `departments` 的先例);
217
+ // ② 砍掉一批冗长描述里重复的解释性从句(每条约 20–100 B,信息点全部保留)。
218
+ // 实测(含新工具):all 97 / 86,020 B;node 64 / 64,464 B;user 64 / 59,680 B —— 三个上限**一个都没动**。
219
+ // 下次再加工具,请先合并动作或砍描述,不要直接改这三个数。
220
+ const CEILINGS = { node: 64_500, user: 60_500, all: 86_500 } as const;
221
+ test("node / user / all", async () => {
222
+ const node = await listTools(T.node_normal);
223
+ const user = await listTools(T.owner);
224
+ const all = { bytes: Buffer.byteLength(JSON.stringify({ tools: ALL_TOOLS }), "utf8"), names: ALL_TOOLS.map(t => t.name) };
225
+ console.log(`tools/list bytes — all ${all.names.length} tools ${all.bytes} B; node ${node.names.length} tools ${node.bytes} B (−${Math.round(100 - node.bytes / all.bytes * 100)}%); user ${user.names.length} tools ${user.bytes} B (−${Math.round(100 - user.bytes / all.bytes * 100)}%)`);
226
+ expect(node.bytes).toBeLessThanOrEqual(CEILINGS.node);
227
+ expect(user.bytes).toBeLessThanOrEqual(CEILINGS.user);
228
+ expect(all.bytes).toBeLessThanOrEqual(CEILINGS.all);
229
+ });
230
+ });