@sleep2agi/commhub-server 0.9.0-preview.2 → 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 (412) 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 +374 -0
  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 +271 -0
  27. package/src/api-host-supervisors-runtime-readiness.test.ts +195 -0
  28. package/src/api-nodes-shape.test.ts +279 -0
  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 +611 -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 +379 -0
  57. package/src/create-node-validate.ts +423 -0
  58. package/src/create-node-workdir.test.ts +289 -0
  59. package/src/create-node.test.ts +354 -0
  60. package/src/create-node.ts +411 -0
  61. package/src/daemon-provider-snapshots.test.ts +421 -0
  62. package/src/daemon-provider-snapshots.ts +327 -0
  63. package/src/daemon-token-owner-http.test.ts +236 -0
  64. package/src/dashboard-slash-routing-http.test.ts +109 -0
  65. package/src/db-adapter-guard.test.ts +148 -0
  66. package/src/db-adapter-translate.test.ts +128 -0
  67. package/src/db-adapter.ts +377 -91
  68. package/src/db-timestamp.test.ts +38 -0
  69. package/src/db-timestamp.ts +15 -0
  70. package/src/db.ts +1501 -152
  71. package/src/delivered-without-push.test.ts +140 -0
  72. package/src/department-groups-http.test.ts +209 -0
  73. package/src/department-groups-sync-http.test.ts +328 -0
  74. package/src/department-groups.ts +434 -0
  75. package/src/department-heads-http.test.ts +330 -0
  76. package/src/department-heads.ts +226 -0
  77. package/src/departments-agent-count.test.ts +129 -0
  78. package/src/departments-http.test.ts +185 -0
  79. package/src/departments-mcp.test.ts +128 -0
  80. package/src/departments.ts +318 -0
  81. package/src/desktop-message-seam.test.ts +150 -0
  82. package/src/desktop-message.test.ts +368 -0
  83. package/src/dm-file-scope-http.test.ts +178 -0
  84. package/src/empty-node-sweeper.test.ts +104 -0
  85. package/src/empty-node-sweeper.ts +88 -0
  86. package/src/env-transport-gate-http.test.ts +177 -0
  87. package/src/env-transport-gate.ts +74 -0
  88. package/src/env-transport-policy.ts +21 -0
  89. package/src/event-loop-lag.test.ts +139 -0
  90. package/src/event-loop-lag.ts +150 -0
  91. package/src/ext-token-shared.test.ts +60 -0
  92. package/src/ext-validation-regression.test.ts +131 -0
  93. package/src/external-schedule-edits-http.test.ts +321 -0
  94. package/src/external-schedule-edits-timestamps.test.ts +64 -0
  95. package/src/external-schedule-edits.ts +327 -0
  96. package/src/file-download-authz-dev-open.test.ts +135 -0
  97. package/src/file-download-authz.test.ts +404 -0
  98. package/src/file-download-date-bucket.test.ts +436 -0
  99. package/src/file-network-scope-dev-open.test.ts +97 -0
  100. package/src/file-network-scope.test.ts +732 -0
  101. package/src/group-membership-events-http.test.ts +264 -0
  102. package/src/group-messages-http.test.ts +482 -0
  103. package/src/group-messages.ts +297 -0
  104. package/src/health-host-disk-2756.test.ts +49 -0
  105. package/src/health-redaction.test.ts +685 -0
  106. package/src/host-supervisor-identity-http.test.ts +152 -0
  107. package/src/host-supervisor-identity.ts +92 -0
  108. package/src/host-supervisors-daemon-version.test.ts +137 -0
  109. package/src/http-gzip.test.ts +94 -0
  110. package/src/http-gzip.ts +112 -0
  111. package/src/hub-catalog-read-http.test.ts +187 -0
  112. package/src/hub-provider-config.test.ts +139 -0
  113. package/src/hub-provider-config.ts +105 -0
  114. package/src/hub-timestamp.test.ts +38 -0
  115. package/src/hub-timestamp.ts +27 -0
  116. package/src/human-dm.ts +215 -0
  117. package/src/human-inbox.ts +42 -0
  118. package/src/inbox-caller.ts +49 -0
  119. package/src/inbox-count-sse.test.ts +310 -0
  120. package/src/inbox-count.ts +29 -0
  121. package/src/index.ts +15 -2172
  122. package/src/lifecycle-guard.ts +50 -0
  123. package/src/list-host-supervisors.test.ts +315 -0
  124. package/src/mcp-context-cost-http.test.ts +127 -0
  125. package/src/mcp-inflight.test.ts +92 -0
  126. package/src/mcp-inflight.ts +38 -0
  127. package/src/mcp-projects-events-http.test.ts +162 -0
  128. package/src/mcp-route-label-http.test.ts +120 -0
  129. package/src/mcp-write-network-resolution.test.ts +432 -0
  130. package/src/member-audit-network-id-http.test.ts +93 -0
  131. package/src/member-presence-http.test.ts +210 -0
  132. package/src/messages-ack-by-agent-http.test.ts +142 -0
  133. package/src/migrate-sqlite-to-pg.test.ts +47 -0
  134. package/src/migrate-sqlite-to-pg.ts +263 -0
  135. package/src/model-auth-notify-http.test.ts +181 -0
  136. package/src/model-auth-notify.ts +116 -0
  137. package/src/network-name-http.test.ts +75 -0
  138. package/src/network-rules-http.test.ts +169 -0
  139. package/src/network-rules.ts +129 -0
  140. package/src/network-scope.ts +276 -0
  141. package/src/network-token-membership-http.test.ts +139 -0
  142. package/src/node-alias-control.ts +12 -0
  143. package/src/node-attrs-validate.ts +88 -0
  144. package/src/node-attrs.test.ts +258 -0
  145. package/src/node-caller-identity-http.test.ts +1083 -0
  146. package/src/node-create-request-status-http.test.ts +105 -0
  147. package/src/node-daemon-bindings.test.ts +132 -0
  148. package/src/node-daemon-bindings.ts +135 -0
  149. package/src/node-failure-alert.test.ts +150 -0
  150. package/src/node-failure-alert.ts +177 -0
  151. package/src/node-files-transport.test.ts +344 -0
  152. package/src/node-health-codex-login.test.ts +120 -0
  153. package/src/node-health-dispatch-http.test.ts +279 -0
  154. package/src/node-health-guard.ts +105 -0
  155. package/src/node-health-passthrough.test.ts +115 -0
  156. package/src/node-health-store.ts +101 -0
  157. package/src/node-id-alias.test.ts +190 -0
  158. package/src/node-identity-conflict-http.test.ts +269 -0
  159. package/src/node-identity-conflict.ts +142 -0
  160. package/src/node-identity-mismatch.test.ts +74 -0
  161. package/src/node-in-flight-tasks.ts +31 -0
  162. package/src/node-lifecycle-controllable.test.ts +64 -0
  163. package/src/node-lifecycle-controllable.ts +53 -0
  164. package/src/node-lifecycle-read-http.test.ts +250 -0
  165. package/src/node-lifecycle-read.ts +124 -0
  166. package/src/node-logs-transport.test.ts +263 -0
  167. package/src/node-peer-allowlist.test.ts +79 -0
  168. package/src/node-permissions-http.test.ts +345 -0
  169. package/src/node-permissions.ts +393 -0
  170. package/src/node-request-retention.test.ts +281 -0
  171. package/src/node-request-retention.ts +120 -0
  172. package/src/node-secret-rest-http.test.ts +190 -0
  173. package/src/node-serviceability.test.ts +86 -0
  174. package/src/node-serviceability.ts +124 -0
  175. package/src/node-session-control-http.test.ts +310 -0
  176. package/src/node-session-control.ts +258 -0
  177. package/src/node-skills-transport.test.ts +209 -0
  178. package/src/node-token-identity.ts +35 -0
  179. package/src/node-token-ownership.ts +51 -0
  180. package/src/node-token-privilege-http.test.ts +158 -0
  181. package/src/not-found-api-http.test.ts +67 -0
  182. package/src/observer-avatar-http.test.ts +442 -0
  183. package/src/observer-push.test.ts +252 -0
  184. package/src/opencode-catalog-report-http.test.ts +139 -0
  185. package/src/opencode-v2-catalog.test.ts +268 -0
  186. package/src/opencode-v2-catalog.ts +352 -0
  187. package/src/package-version-consistency.test.ts +25 -0
  188. package/src/parent-source-marker.test.ts +50 -0
  189. package/src/password-network-tokens.ts +25 -0
  190. package/src/peer-reply-atomic.test.ts +455 -0
  191. package/src/peer-reply-capability.test.ts +70 -0
  192. package/src/pg-worker.ts +87 -0
  193. package/src/probe-validate.test.ts +221 -0
  194. package/src/probe-validate.ts +104 -0
  195. package/src/probe.test.ts +80 -0
  196. package/src/probe.ts +200 -0
  197. package/src/project-dir-warn-clear-http.test.ts +132 -0
  198. package/src/project-viewer-can-http.test.ts +116 -0
  199. package/src/push.test.ts +20 -10
  200. package/src/push.ts +466 -13
  201. package/src/redact-tokens.test.ts +65 -0
  202. package/src/redact-tokens.ts +40 -0
  203. package/src/rename.ts +38 -10
  204. package/src/reply-target-derivation.test.ts +96 -0
  205. package/src/report-status-handover-capabilities-http.test.ts +124 -0
  206. package/src/report-status-host-schema.test.ts +235 -0
  207. package/src/report-status-resume-id-handover.test.ts +184 -0
  208. package/src/report-status-secret-keys.test.ts +140 -0
  209. package/src/require-explicit-test-db.ts +9 -0
  210. package/src/requirement-due-reminders-http.test.ts +620 -0
  211. package/src/requirement-due-reminders.ts +416 -0
  212. package/src/requirement-events-http.test.ts +268 -0
  213. package/src/requirement-events.test.ts +45 -0
  214. package/src/requirement-events.ts +144 -0
  215. package/src/requirement-notify.ts +165 -0
  216. package/src/requirement-participant-notify-http.test.ts +309 -0
  217. package/src/requirement-tag-ops-http.test.ts +425 -0
  218. package/src/requirement-tag-tree-http.test.ts +275 -0
  219. package/src/requirement-tag-tree.ts +127 -0
  220. package/src/requirement-tags.ts +102 -0
  221. package/src/requirements-abandoned-http.test.ts +236 -0
  222. package/src/requirements-comment-http.test.ts +167 -0
  223. package/src/requirements-completed-at-migration.test.ts +70 -0
  224. package/src/requirements-errors-mcp-http.test.ts +164 -0
  225. package/src/requirements-errors.ts +158 -0
  226. package/src/requirements-etag-http.test.ts +91 -0
  227. package/src/requirements-http.test.ts +709 -0
  228. package/src/requirements-last-event-http.test.ts +349 -0
  229. package/src/requirements-list-mcp-slim-http.test.ts +155 -0
  230. package/src/requirements-list-slim-http.test.ts +324 -0
  231. package/src/requirements-mcp.test.ts +163 -0
  232. package/src/requirements-migrate.ts +283 -0
  233. package/src/requirements-owner-strict-mcp-http.test.ts +145 -0
  234. package/src/requirements-people-http.test.ts +114 -0
  235. package/src/requirements-people-mcp-http.test.ts +231 -0
  236. package/src/requirements-people.ts +196 -0
  237. package/src/requirements-priority-lowest.test.ts +114 -0
  238. package/src/requirements-projects-parent-http.test.ts +123 -0
  239. package/src/requirements-search-http.test.ts +182 -0
  240. package/src/requirements-search.test.ts +32 -0
  241. package/src/requirements-search.ts +145 -0
  242. package/src/requirements-seq-http.test.ts +193 -0
  243. package/src/requirements-seq-migration.test.ts +63 -0
  244. package/src/requirements-start-date.test.ts +125 -0
  245. package/src/requirements-stats-http.test.ts +357 -0
  246. package/src/requirements-stats.ts +195 -0
  247. package/src/requirements-status-participants-http.test.ts +222 -0
  248. package/src/requirements-upgrade-e2e.test.ts +126 -0
  249. package/src/requirements-upgrade-migration.test.ts +98 -0
  250. package/src/requirements.ts +2027 -0
  251. package/src/resolve-port.test.ts +57 -0
  252. package/src/resolve-port.ts +44 -0
  253. package/src/response-charset.test.ts +130 -0
  254. package/src/rest-alias-network-fallback-http.test.ts +123 -0
  255. package/src/rest-alias-network-fallback.test.ts +60 -0
  256. package/src/rest-alias-network-fallback.ts +65 -0
  257. package/src/rest-explicit-columns-http.test.ts +266 -0
  258. package/src/rest-identity.test.ts +130 -0
  259. package/src/rest-identity.ts +141 -0
  260. package/src/rest-projections.ts +72 -0
  261. package/src/rest-read-network-real-chain.test.ts +97 -0
  262. package/src/rest-write-network-resolution.test.ts +133 -0
  263. package/src/restart-readiness-http.test.ts +121 -0
  264. package/src/restricted-files.ts +76 -0
  265. package/src/retention-first-sweep-quiet.test.ts +31 -0
  266. package/src/retention.test.ts +100 -40
  267. package/src/retention.ts +423 -104
  268. package/src/route-callers-http.test.ts +120 -0
  269. package/src/route-timing.test.ts +211 -0
  270. package/src/route-timing.ts +262 -0
  271. package/src/rules-file-duplicate-alias.test.ts +234 -0
  272. package/src/rules-file-session-target.test.ts +207 -0
  273. package/src/rules-file-transport.test.ts +237 -0
  274. package/src/runtime-label.test.ts +22 -0
  275. package/src/runtime-label.ts +21 -0
  276. package/src/runtime-readiness.ts +90 -0
  277. package/src/schedule-agent-mcp-http.test.ts +391 -0
  278. package/src/schedule-agent.ts +192 -0
  279. package/src/schedule-starved.test.ts +92 -0
  280. package/src/schedule-starved.ts +114 -0
  281. package/src/scheduled-backoff-http.test.ts +193 -0
  282. package/src/scheduled-backoff.ts +64 -0
  283. package/src/scheduled-doorbell-nodeless-session.test.ts +134 -0
  284. package/src/scheduled-failure-backoff-2622.test.ts +145 -0
  285. package/src/scheduled-failure-code.test.ts +73 -0
  286. package/src/scheduled-failure-code.ts +105 -0
  287. package/src/scheduled-failures-http.test.ts +279 -0
  288. package/src/scheduled-failures.ts +377 -0
  289. package/src/scheduled-noprogress-backoff-2622.test.ts +133 -0
  290. package/src/scheduled-offline-backoff-probe.test.ts +56 -0
  291. package/src/scheduled-offline.test.ts +131 -0
  292. package/src/scheduled-offline.ts +66 -0
  293. package/src/scheduled-outcome-guidance-http.test.ts +139 -0
  294. package/src/scheduled-outcome-guidance.ts +9 -0
  295. package/src/scheduled-reply-unread-http.test.ts +212 -0
  296. package/src/scheduled-requirement-wake-http.test.ts +279 -0
  297. package/src/scheduled-requirement-wake.ts +125 -0
  298. package/src/scheduled-run-terminal.test.ts +268 -0
  299. package/src/scheduled-skip-blocking-task.test.ts +120 -0
  300. package/src/scheduled-skip-path-backoff-2622.test.ts +98 -0
  301. package/src/scheduled-stuck-http.test.ts +312 -0
  302. package/src/scheduled-stuck-notice-cap.test.ts +80 -0
  303. package/src/scheduled-stuck.ts +219 -0
  304. package/src/scheduled-tasks-http.test.ts +679 -0
  305. package/src/scheduled-tasks.ts +959 -0
  306. package/src/scheduled-work-outcome-http.test.ts +154 -0
  307. package/src/scheduled-work-outcome.ts +50 -0
  308. package/src/scoped-secrets.ts +139 -0
  309. package/src/send-dedup-request-id.test.ts +229 -0
  310. package/src/send-reply-agent-warning.test.ts +202 -0
  311. package/src/send-reply-alias-optional.test.ts +131 -0
  312. package/src/send-reply-attachments.test.ts +458 -0
  313. package/src/send_dedup.test.ts +54 -0
  314. package/src/send_dedup.ts +52 -6
  315. package/src/serve-error.test.ts +38 -0
  316. package/src/serve-error.ts +27 -0
  317. package/src/server.ts +5997 -0
  318. package/src/session-task-on-dispatch.ts +14 -0
  319. package/src/session-token-ownership-http.test.ts +122 -0
  320. package/src/shared/codex-inventory.ts +41 -0
  321. package/src/shared/daemon-provider-login.ts +31 -0
  322. package/src/shared/daemon-provider-snapshot.ts +52 -0
  323. package/src/shared/external-schedule-contract.ts +60 -0
  324. package/src/shared/node-name.test.ts +62 -0
  325. package/src/shared/node-name.ts +161 -0
  326. package/src/shared/probe-host-allowlist-drift.test.ts +54 -0
  327. package/src/shared/probe-host-allowlist.ts +128 -0
  328. package/src/shared/provider-application.ts +29 -0
  329. package/src/shared/provider-collection.ts +14 -0
  330. package/src/shared/provider-initialization.ts +8 -0
  331. package/src/shared/reserved-env-drift.test.ts +53 -0
  332. package/src/shared/reserved-env.test.ts +35 -0
  333. package/src/shared/reserved-env.ts +31 -0
  334. package/src/shared/scoped-secret-contract.ts +5 -0
  335. package/src/shared/task-content-limit-drift.test.ts +28 -0
  336. package/src/shared/task-content-limit.ts +25 -0
  337. package/src/side-thread-command-transport.test.ts +312 -0
  338. package/src/side-thread-command-transport.ts +318 -0
  339. package/src/side-thread-http-integration.test.ts +233 -0
  340. package/src/side-thread-http.ts +504 -0
  341. package/src/side-thread-production.test.ts +72 -0
  342. package/src/side-thread-production.ts +118 -0
  343. package/src/side-thread.test.ts +1067 -0
  344. package/src/side-thread.ts +2499 -0
  345. package/src/skillhub-http.test.ts +108 -0
  346. package/src/sqlite-close-checkpoint.test.ts +78 -0
  347. package/src/start-node.test.ts +264 -0
  348. package/src/status-alias-filter-http.test.ts +106 -0
  349. package/src/status-alias-resolver-http.test.ts +163 -0
  350. package/src/status-alias-resolver.ts +19 -0
  351. package/src/status-node-id-filter-http.test.ts +161 -0
  352. package/src/status-read-cache-http.test.ts +229 -0
  353. package/src/status-read-cache.ts +122 -0
  354. package/src/stop-delete-node.test.ts +1286 -0
  355. package/src/task-access-http.test.ts +402 -0
  356. package/src/task-access.ts +420 -0
  357. package/src/task-activity.ts +60 -0
  358. package/src/task-auth-origin-http.test.ts +93 -0
  359. package/src/task-auth-origin.test.ts +24 -0
  360. package/src/task-auth-origin.ts +7 -0
  361. package/src/task-consumption.test.ts +482 -0
  362. package/src/task-diagnostic-http.test.ts +149 -0
  363. package/src/task-diagnostic.test.ts +115 -0
  364. package/src/task-diagnostic.ts +118 -0
  365. package/src/task-expiry-notice-http.test.ts +287 -0
  366. package/src/task-expiry-notice.ts +315 -0
  367. package/src/task-idempotency-mcp.test.ts +142 -0
  368. package/src/task-idempotency.test.ts +76 -0
  369. package/src/task-idempotency.ts +81 -0
  370. package/src/task-late-replies.ts +54 -0
  371. package/src/task-late-reply-http.test.ts +152 -0
  372. package/src/task-lifecycle-watcher-busy.test.ts +114 -0
  373. package/src/task-lifecycle-watcher.test.ts +204 -0
  374. package/src/task-lifecycle-watcher.ts +109 -0
  375. package/src/task-network-resolution-http.test.ts +140 -0
  376. package/src/task-offline-delivery-2668.test.ts +119 -0
  377. package/src/task-offline-delivery.ts +81 -0
  378. package/src/task-orphan-http.test.ts +287 -0
  379. package/src/task-orphan.ts +119 -0
  380. package/src/task-queue-ahead-http.test.ts +309 -0
  381. package/src/task-queue-ahead-scale.test.ts +236 -0
  382. package/src/task-queue-ahead.ts +186 -0
  383. package/src/task-rejection-log-http.test.ts +160 -0
  384. package/src/task-rejection-log.ts +49 -0
  385. package/src/task-sender-http.test.ts +143 -0
  386. package/src/task-stale-open-http.test.ts +290 -0
  387. package/src/task-stale-open.ts +103 -0
  388. package/src/tasks-pagination-http.test.ts +141 -0
  389. package/src/team-rules-status-http.test.ts +90 -0
  390. package/src/team-rules-status.test.ts +59 -0
  391. package/src/team-rules-status.ts +72 -0
  392. package/src/tool-audience-http.test.ts +230 -0
  393. package/src/tool-audience.ts +120 -0
  394. package/src/tools-list-json-schema.test.ts +94 -0
  395. package/src/tools.ts +5815 -348
  396. package/src/update-provider.test.ts +234 -0
  397. package/src/upload-early-reject-guard.test.ts +155 -0
  398. package/src/uploads-http.test.ts +97 -15
  399. package/src/uploads.test.ts +66 -0
  400. package/src/uploads.ts +138 -5
  401. package/src/user-avatar-http.test.ts +74 -0
  402. package/src/user-avatar-image.ts +160 -0
  403. package/src/user-avatar-migration.test.ts +25 -0
  404. package/src/user-avatar-upload-http.test.ts +348 -0
  405. package/src/user-inbox-by-agent-http.test.ts +161 -0
  406. package/src/user-inbox-netid-notnull.test.ts +122 -0
  407. package/src/user-inbox-read-http.test.ts +223 -0
  408. package/src/user-inbox-schema.test.ts +54 -0
  409. package/src/vault.test.ts +200 -0
  410. package/src/vault.ts +156 -0
  411. package/src/version-stats.test.ts +66 -0
  412. package/src/version-stats.ts +109 -0
@@ -0,0 +1,88 @@
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
+ import { NETWORK_REST_COLUMNS } from "./rest-projections.js";
6
+
7
+ const PRIVATE_DB_DIR = mkdtempSync(join(tmpdir(), "anet-admin-networks-"));
8
+ process.env.COMMHUB_DB ||= join(PRIVATE_DB_DIR, "hub.db");
9
+
10
+ let server: ReturnType<typeof Bun.serve>;
11
+ let base = "";
12
+ let adminToken = "";
13
+ let memberToken = "";
14
+ let nodeToken = "";
15
+ let adminNetworkId = "";
16
+ let memberNetworkId = "";
17
+
18
+ async function listNetworks(token: string): Promise<any[]> {
19
+ const response = await fetch(`${base}/api/networks`, {
20
+ headers: { Authorization: `Bearer ${token}` },
21
+ });
22
+ expect(response.status).toBe(200);
23
+ const body = await response.json() as any;
24
+ expect(body.ok).toBe(true);
25
+ return body.networks;
26
+ }
27
+
28
+ // 30s 而不是 bun 默认的 5s:这个 hook 跑 register()(KDF)+bootServer(),
29
+ // 本机空载基线 ~620ms,而 2026-08-17 与 2026-08-31 两次 CI 上它被 5s 上限打死
30
+ // (0 pass / 1 fail / Ran 1 test —— 见 #928、#1627)。5247ms 是**被截断的下界**,
31
+ // 不是测量值,所以余量按基线的 ~48x 取,而不是按那个数取。
32
+ beforeAll(async () => {
33
+ const { db } = await import("./db.js");
34
+ const { createNetworkTokenForNode, register } = await import("./auth.js");
35
+
36
+ // The first registered user is the global Hub admin. The second user owns a
37
+ // separate network and is intentionally not a member of the admin's network.
38
+ const admin = register(`admin_networks_${Date.now()}`, "AdminNetworks-Strong-1!", undefined, "admin");
39
+ expect(admin.ok).toBe(true);
40
+ adminToken = admin.token!;
41
+ adminNetworkId = admin.network_id!;
42
+
43
+ const member = register(`member_networks_${Date.now()}`, "MemberNetworks-Strong-1!", undefined, "member");
44
+ expect(member.ok).toBe(true);
45
+ memberToken = member.token!;
46
+ memberNetworkId = member.network_id!;
47
+
48
+ const memberUserId = db.get<{ user_id: string }>(
49
+ "SELECT user_id FROM users WHERE username LIKE 'member_networks_%' ORDER BY created_at DESC LIMIT 1",
50
+ )!.user_id;
51
+ const minted = createNetworkTokenForNode(memberUserId, memberNetworkId, "admin-networks-node");
52
+ expect(minted.ok).toBe(true);
53
+ nodeToken = minted.token!;
54
+
55
+ const mod = await import("./server.js");
56
+ server = mod.bootServer({ port: 0, hostname: "127.0.0.1" });
57
+ base = `http://127.0.0.1:${server.port}`;
58
+ }, 30_000);
59
+
60
+ afterAll(() => {
61
+ try { server?.stop(true); } catch {}
62
+ try { rmSync(PRIVATE_DB_DIR, { recursive: true, force: true }); } catch {}
63
+ });
64
+
65
+ describe("GET /api/networks global-admin visibility (#94)", () => {
66
+ test("global admin utok sees every network without losing public shape", async () => {
67
+ const rows = await listNetworks(adminToken);
68
+ expect(new Set(rows.map((row) => row.network_id))).toEqual(new Set([adminNetworkId, memberNetworkId]));
69
+
70
+ const own = rows.find((row) => row.network_id === adminNetworkId);
71
+ const foreign = rows.find((row) => row.network_id === memberNetworkId);
72
+ expect(own.member_role).toBe("owner");
73
+ expect(foreign.member_role).toBe("admin");
74
+ expect(Object.keys(foreign).sort()).toEqual([...NETWORK_REST_COLUMNS, "member_role", "name"].sort());
75
+ });
76
+
77
+ test("ordinary utok remains limited to member networks", async () => {
78
+ const rows = await listNetworks(memberToken);
79
+ expect(rows.map((row) => row.network_id)).toEqual([memberNetworkId]);
80
+ expect(rows.some((row) => row.network_id === adminNetworkId)).toBe(false);
81
+ });
82
+
83
+ test("network token remains limited to its bound network", async () => {
84
+ const rows = await listNetworks(nodeToken);
85
+ expect(rows.map((row) => row.network_id)).toEqual([memberNetworkId]);
86
+ expect(rows.some((row) => row.network_id === adminNetworkId)).toBe(false);
87
+ });
88
+ });
@@ -0,0 +1,137 @@
1
+ import { afterAll, beforeAll, expect, test } from "bun:test";
2
+ import { mkdtempSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { tmpdir } from "node:os";
5
+
6
+ const dir = mkdtempSync(join(tmpdir(), "adoption-candidates-"));
7
+ process.env.COMMHUB_DB ||= join(dir, "hub.db");
8
+ process.env.COMMHUB_AUTH_TOKEN ||= "adoption-candidates-master-fixture";
9
+ const WORKDIR = "/home/example/adoption-candidate-workdir-654";
10
+ const SECRET = "ntok_should_not_surface";
11
+ let hub: { stop: (closeActiveConnections?: boolean) => void; port: number }, base: string;
12
+ let db: any, owner: any, member: any, nodeOwner: any, other: any, daemonToken: string;
13
+ const ids = { daemon: "n_cand_daemon", hand: "n_cand_hand", foreign: "n_cand_foreign" };
14
+
15
+ const get = async (path: string, token = owner.token) => {
16
+ const res = await fetch(base + path, { headers: { Authorization: `Bearer ${token}` } });
17
+ return { status: res.status, body: await res.json() as any, text: "" };
18
+ };
19
+ const raw = async (path: string, token = owner.token) => {
20
+ const res = await fetch(base + path, { headers: { Authorization: `Bearer ${token}` } });
21
+ const text = await res.text();
22
+ return { status: res.status, text, body: JSON.parse(text) };
23
+ };
24
+
25
+ function snapshot(candidates: unknown, adopt = true) {
26
+ return JSON.stringify({
27
+ role: "host_supervisor",
28
+ daemon_capabilities: { adopt_capable: adopt, adoption_candidates: candidates },
29
+ });
30
+ }
31
+
32
+ beforeAll(async () => {
33
+ ({ db } = await import("./db.js"));
34
+ const { register } = await import("./auth.js");
35
+ const suffix = Date.now();
36
+ owner = register(`cand_owner_${suffix}`, "CandFixture-Strong1!");
37
+ member = register(`cand_member_${suffix}`, "CandFixture-Strong1!");
38
+ nodeOwner = register(`cand_node_owner_${suffix}`, "CandFixture-Strong1!");
39
+ other = register(`cand_other_${suffix}`, "CandFixture-Strong1!");
40
+ expect(owner.ok && member.ok && nodeOwner.ok && other.ok).toBe(true);
41
+ for (const user of [owner, member, nodeOwner, other]) db.run("UPDATE users SET role='user' WHERE user_id=?1", [user.user.user_id]);
42
+ db.run("INSERT INTO network_members(network_id,user_id,role) VALUES(?1,?2,'member')", [owner.network_id, member.user.user_id]);
43
+ db.run("INSERT INTO network_members(network_id,user_id,role) VALUES(?1,?2,'member')", [owner.network_id, nodeOwner.user.user_id]);
44
+ const candidate = { node_id: ids.hand, alias: "hand-node", workdir: WORKDIR, runtime: "claude-agent-sdk", launch_hint: "tmux", token: SECRET, env: { API_KEY: SECRET } };
45
+ db.run("INSERT INTO nodes(node_id,node_name,alias,network_id,owner_user_id,hostname,config_snapshot) VALUES(?1,?2,?2,?3,?4,'fixture-host',?5)",
46
+ [ids.daemon, "cand-daemon", owner.network_id, owner.user.user_id, snapshot([candidate, { node_id: "n_missing", alias: "nope", workdir: "/tmp/nope", launch_hint: "bare" }])]);
47
+ db.run("INSERT INTO nodes(node_id,node_name,alias,network_id,owner_user_id,hostname,config_snapshot) VALUES(?1,?2,?2,?3,?4,'fixture-host','{}')",
48
+ [ids.hand, "hand-node", owner.network_id, nodeOwner.user.user_id]);
49
+ db.run("INSERT INTO nodes(node_id,node_name,alias,network_id,owner_user_id,hostname) VALUES(?1,?2,?2,?3,?4,'other-host')",
50
+ [ids.foreign, "foreign-node", other.network_id, other.user.user_id]);
51
+ db.run("INSERT INTO sessions(resume_id,alias,node_id,network_id,status,last_seen_at) VALUES('cand-daemon-session','cand-daemon',?1,?2,'idle',datetime('now'))",
52
+ [ids.daemon, owner.network_id]);
53
+ const { generateNetworkToken, hashToken } = await import("./db.js");
54
+ daemonToken = generateNetworkToken();
55
+ db.run("INSERT INTO api_tokens(token_id,user_id,network_id,scope,name,token_hash) VALUES('cand-daemon-token',?1,?2,'network','node:cand-daemon',?3)",
56
+ [owner.user.user_id, owner.network_id, hashToken(daemonToken)]);
57
+ const { bootServer } = await import("./server.js");
58
+ hub = bootServer({ port: 0, hostname: "127.0.0.1" });
59
+ base = `http://127.0.0.1:${hub.port}`;
60
+ }, 30_000);
61
+ afterAll(() => hub?.stop(true));
62
+
63
+ test("owner and node owner see the candidate; the report token stays out", async () => {
64
+ for (const token of [owner.token, nodeOwner.token]) {
65
+ const r = await raw(`/api/adoption-candidates?network_id=${owner.network_id}`, token);
66
+ expect(r.status).toBe(200);
67
+ expect(r.body.count).toBe(1);
68
+ expect(r.body.candidates).toEqual([{
69
+ node_id: ids.hand, alias: "hand-node", daemon_node_id: ids.daemon, daemon_alias: "cand-daemon",
70
+ hostname: "fixture-host", workdir: WORKDIR, runtime: "claude-agent-sdk", launch_hint: "tmux",
71
+ }]);
72
+ expect(r.text).not.toContain(SECRET);
73
+ expect(r.text).toContain(WORKDIR);
74
+ }
75
+ const supervisors = await raw(`/api/host-supervisors?network_id=${owner.network_id}`);
76
+ expect(supervisors.body.daemons.find((d: any) => d.daemon_node_id === ids.daemon).adoption_discovery).toBe(true);
77
+ expect(supervisors.text).not.toContain(WORKDIR);
78
+ expect(supervisors.text).not.toContain(SECRET);
79
+ const nodes = await raw(`/api/nodes?network_id=${owner.network_id}`);
80
+ expect(nodes.text).not.toContain("adoption_candidate");
81
+ expect(nodes.text).not.toContain(WORKDIR);
82
+ });
83
+
84
+ test("member, other network, daemon token, and query token do not receive the workdir", async () => {
85
+ const memberRes = await raw(`/api/adoption-candidates?network_id=${owner.network_id}`, member.token);
86
+ expect(memberRes.status).toBe(200);
87
+ expect(memberRes.body.candidates).toEqual([]);
88
+ expect(memberRes.text).not.toContain(WORKDIR);
89
+ const otherRes = await raw(`/api/adoption-candidates?network_id=${owner.network_id}`, other.token);
90
+ expect(otherRes.status).toBe(403);
91
+ expect(otherRes.text).not.toContain(WORKDIR);
92
+ expect((await get("/api/adoption-candidates", daemonToken)).status).toBe(403);
93
+ expect((await get("/api/adoption-candidates", process.env.COMMHUB_AUTH_TOKEN!)).status).toBe(403);
94
+ const queryOnly = await fetch(base + `/api/adoption-candidates?network_id=${owner.network_id}&token=${encodeURIComponent(owner.token)}`);
95
+ expect([401, 403]).toContain(queryOnly.status);
96
+ });
97
+
98
+ test("offline, hostname, alias, binding, and created-node filters drop the hint", async () => {
99
+ const path = `/api/adoption-candidates?network_id=${owner.network_id}`;
100
+ db.run("UPDATE sessions SET last_seen_at='2000-01-01 00:00:00' WHERE alias='cand-daemon'");
101
+ expect((await get(path)).body.candidates).toEqual([]);
102
+ db.run("UPDATE sessions SET last_seen_at=datetime('now') WHERE alias='cand-daemon'");
103
+ expect((await get(path)).body.count).toBe(1);
104
+
105
+ db.run("UPDATE nodes SET hostname='elsewhere' WHERE node_id=?1", [ids.hand]);
106
+ expect((await get(path)).body.candidates).toEqual([]);
107
+ db.run("UPDATE nodes SET hostname='fixture-host' WHERE node_id=?1", [ids.hand]);
108
+
109
+ db.run("UPDATE nodes SET config_snapshot=?1 WHERE node_id=?2", [snapshot([{ node_id: ids.hand, alias: "other-name", workdir: WORKDIR, launch_hint: "stopped" }]), ids.daemon]);
110
+ expect((await get(path)).body.candidates).toEqual([]);
111
+ db.run("UPDATE nodes SET config_snapshot=?1 WHERE node_id=?2", [snapshot([{ node_id: ids.hand, alias: "hand-node", workdir: WORKDIR, runtime: "claude-agent-sdk", launch_hint: "tmux", token: SECRET }]), ids.daemon]);
112
+ expect((await get(path)).body.count).toBe(1);
113
+
114
+ db.run(`INSERT INTO node_daemon_bindings(request_id,network_id,node_id,daemon_node_id,workdir,requested_by,status,created_at,updated_at)
115
+ VALUES('adopt_cand_pending',?1,?2,?3,?4,?5,'pending',1,1)`, [owner.network_id, ids.hand, ids.daemon, WORKDIR, owner.user.user_id]);
116
+ expect((await get(path)).body.candidates).toEqual([]);
117
+ db.run("UPDATE node_daemon_bindings SET status='revoked' WHERE request_id='adopt_cand_pending'");
118
+ expect((await get(path)).body.count).toBe(1);
119
+
120
+ db.run(`INSERT INTO node_create_requests(request_id,daemon_node_id,child_node_id,child_name,network_id,runtime,flags_json,env_keys,status,created_at,created_by_token)
121
+ VALUES('cr_cand_hand',?1,?2,'hand-node',?3,'claude-agent-sdk','{}','[]','succeeded',1,'private')`, [ids.daemon, ids.hand, owner.network_id]);
122
+ expect((await get(path)).body.candidates).toEqual([]);
123
+ db.run("DELETE FROM node_create_requests WHERE request_id='cr_cand_hand'");
124
+ expect((await get(path)).body.count).toBe(1);
125
+ });
126
+
127
+ test("discovery flag is absent unless the daemon actually reported a list", async () => {
128
+ const path = `/api/host-supervisors?network_id=${owner.network_id}`;
129
+ db.run("UPDATE nodes SET config_snapshot=?1 WHERE node_id=?2", [JSON.stringify({ role: "host_supervisor", daemon_capabilities: { adopt_capable: true } }), ids.daemon]);
130
+ expect((await get(path)).body.daemons[0].adoption_discovery).toBeUndefined();
131
+ expect((await get(path)).body.daemons[0].adopt_capable).toBe(true);
132
+ db.run("UPDATE nodes SET config_snapshot=?1 WHERE node_id=?2", [snapshot([], true), ids.daemon]);
133
+ expect((await get(path)).body.daemons[0].adoption_discovery).toBe(true);
134
+ expect((await get(`/api/adoption-candidates?network_id=${owner.network_id}`)).body.candidates).toEqual([]);
135
+ const limited = await get(path, member.token);
136
+ expect(limited.body.daemons.find((d: any) => d.daemon_node_id === ids.daemon).adoption_discovery).toBe(true);
137
+ });
@@ -0,0 +1,158 @@
1
+ // Board #654 — project daemon-reported hand-started adoption candidates.
2
+ //
3
+ // The daemon report is a hint, not authority. This module does not adopt,
4
+ // bind, signal, start, or stop. Co-presence / three-stage nodes are not
5
+ // part of the report contract: discovery on the daemon excludes them.
6
+ // `GET /api/nodes` managed/adoption and `/api/node-lifecycle-requests`
7
+ // stay records of requests that already exist; they are not this list.
8
+ import { z } from "zod/v4";
9
+ import { db } from "./db.js";
10
+ import { getUserNetworkRole } from "./auth.js";
11
+ import { parseDbTimestampMs } from "./db-timestamp.js";
12
+ import { addAgentNetworkScope, addHumanNetworkScope, type RestNetworkScope } from "./network-scope.js";
13
+
14
+ const HINTS = new Set(["bare", "tmux", "stopped", "unverified"]);
15
+ const ONLINE_MS = 5 * 60_000;
16
+ const MAX_PUBLIC = 64;
17
+
18
+ export interface AdoptionCandidateReport {
19
+ node_id: string;
20
+ alias: string;
21
+ workdir: string;
22
+ runtime: string | null;
23
+ launch_hint: "bare" | "tmux" | "stopped" | "unverified";
24
+ }
25
+
26
+ export function sanitizeAdoptionCandidate(raw: unknown): AdoptionCandidateReport | null {
27
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
28
+ const row = raw as Record<string, unknown>;
29
+ const { node_id, alias, workdir, launch_hint } = row;
30
+ if (typeof node_id !== "string" || node_id.length < 1 || node_id.length > 128 || /[\x00-\x1f\x7f]/.test(node_id)) return null;
31
+ if (typeof alias !== "string" || alias.length < 1 || alias.length > 128 || /[\x00-\x1f\x7f/\\]/.test(alias)
32
+ || alias === "." || alias === ".." || alias.startsWith("-")) return null;
33
+ if (typeof workdir !== "string" || !workdir.startsWith("/") || workdir.length > 1024 || /[\x00-\x1f]/.test(workdir)) return null;
34
+ if (typeof launch_hint !== "string" || !HINTS.has(launch_hint)) return null;
35
+ let runtime: string | null = null;
36
+ if (row.runtime != null) {
37
+ if (typeof row.runtime !== "string" || row.runtime.length < 1 || row.runtime.length > 64 || !/^[A-Za-z0-9._-]+$/.test(row.runtime)) return null;
38
+ runtime = row.runtime;
39
+ }
40
+ return { node_id, alias, workdir, runtime, launch_hint: launch_hint as AdoptionCandidateReport["launch_hint"] };
41
+ }
42
+
43
+ const adoptionCandidateItemSchema = z.object({
44
+ node_id: z.string().min(1).max(128),
45
+ alias: z.string().min(1).max(128),
46
+ workdir: z.string().regex(/^\/[^\u0000-\u001f]{0,1023}$/),
47
+ runtime: z.string().min(1).max(64).nullable().optional(),
48
+ launch_hint: z.enum(["bare", "tmux", "stopped", "unverified"]),
49
+ }).strip().catch(null);
50
+
51
+ /** Ingest path for report_status. One bad item becomes null; a bad list never fails the heartbeat.
52
+ * No transform: tools/list JSON Schema cannot represent one. Readers drop nulls. */
53
+ export const adoptionCandidatesReportSchema = z.array(adoptionCandidateItemSchema).max(32).optional().catch(undefined);
54
+
55
+ function snapshotValue(snapshot: unknown): Record<string, any> | null {
56
+ try {
57
+ const parsed = typeof snapshot === "string" ? JSON.parse(snapshot) : snapshot;
58
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
59
+ } catch { return null; }
60
+ }
61
+
62
+ export function snapshotReportsAdoptionDiscovery(snapshot: unknown): boolean {
63
+ const caps = snapshotValue(snapshot)?.daemon_capabilities;
64
+ return caps?.adopt_capable === true && Array.isArray(caps.adoption_candidates);
65
+ }
66
+
67
+ function reportedCandidates(snapshot: unknown): AdoptionCandidateReport[] {
68
+ const raw = snapshotValue(snapshot)?.daemon_capabilities?.adoption_candidates;
69
+ if (!Array.isArray(raw)) return [];
70
+ const out: AdoptionCandidateReport[] = [];
71
+ for (const item of raw) {
72
+ const clean = sanitizeAdoptionCandidate(item);
73
+ if (clean) out.push(clean);
74
+ if (out.length >= 32) break;
75
+ }
76
+ return out;
77
+ }
78
+
79
+ type NodeRow = {
80
+ node_id: string; alias: string; hostname: string | null; network_id: string;
81
+ owner_user_id?: string | null; config_snapshot?: string | null; last_seen_at?: string | null;
82
+ };
83
+
84
+ export function listAdoptionCandidates(
85
+ scope: RestNetworkScope,
86
+ viewer: { userId: string; isAdmin: boolean },
87
+ nowMs = Date.now(),
88
+ ): { ok: true; candidates: Array<AdoptionCandidateReport & { daemon_node_id: string; daemon_alias: string; hostname: string }>; count: number } {
89
+ const daemonParams: any[] = [];
90
+ let daemonSql = `SELECT n.node_id, n.alias, n.hostname, n.network_id, n.config_snapshot, s.last_seen_at
91
+ FROM nodes n
92
+ LEFT JOIN sessions s ON s.alias = n.alias AND (s.network_id = n.network_id OR s.network_id IS NULL)
93
+ WHERE EXISTS (
94
+ SELECT 1 FROM api_tokens t
95
+ WHERE t.network_id = n.network_id AND t.name = 'node:' || n.alias AND t.revoked_at IS NULL
96
+ )`;
97
+ daemonSql = addHumanNetworkScope(daemonSql, daemonParams, scope, "n.network_id");
98
+ const daemonRows = db.all<NodeRow>(daemonSql, ...daemonParams);
99
+ const daemons = new Map<string, NodeRow>();
100
+ for (const row of daemonRows) {
101
+ const prev = daemons.get(row.node_id);
102
+ if (!prev || parseDbTimestampMs(row.last_seen_at ?? "") > parseDbTimestampMs(prev.last_seen_at ?? "")) daemons.set(row.node_id, row);
103
+ }
104
+
105
+ const nodeParams: any[] = [];
106
+ let nodeSql = "SELECT n.node_id, n.alias, n.hostname, n.network_id, n.owner_user_id, n.config_snapshot FROM nodes n WHERE 1=1";
107
+ nodeSql = addAgentNetworkScope(nodeSql, nodeParams, scope, { network: "n.network_id", alias: "n.alias", nodeId: "n.node_id" });
108
+ const visible = new Map(db.all<NodeRow>(nodeSql, ...nodeParams).map((n) => [n.node_id, n]));
109
+
110
+ const managed = new Set<string>();
111
+ const bindingParams: any[] = [];
112
+ let bindingSql = `SELECT b.node_id FROM node_daemon_bindings b
113
+ JOIN nodes n ON n.node_id = b.node_id AND n.network_id = b.network_id
114
+ WHERE b.status IN ('pending','active')`;
115
+ bindingSql = addHumanNetworkScope(bindingSql, bindingParams, scope, "b.network_id");
116
+ for (const row of db.all<{ node_id: string }>(bindingSql, ...bindingParams)) managed.add(row.node_id);
117
+ const createdParams: any[] = [];
118
+ let createdSql = `SELECT COALESCE(c.child_node_id, CASE WHEN substr(c.request_id,1,3)='cr_' THEN 'node_' || substr(c.request_id,4) END) AS node_id
119
+ FROM node_create_requests c WHERE 1=1`;
120
+ createdSql = addHumanNetworkScope(createdSql, createdParams, scope, "c.network_id");
121
+ for (const row of db.all<{ node_id: string | null }>(createdSql, ...createdParams)) if (row.node_id) managed.add(row.node_id);
122
+
123
+ const roles = new Map<string, string | null>();
124
+ const maySee = (node: NodeRow) => {
125
+ if (viewer.isAdmin) return true;
126
+ if (node.owner_user_id && node.owner_user_id === viewer.userId) return true;
127
+ if (!roles.has(node.network_id)) roles.set(node.network_id, getUserNetworkRole(viewer.userId, node.network_id));
128
+ const role = roles.get(node.network_id);
129
+ return role === "owner" || role === "admin";
130
+ };
131
+
132
+ const candidates: Array<AdoptionCandidateReport & { daemon_node_id: string; daemon_alias: string; hostname: string }> = [];
133
+ const seen = new Set<string>();
134
+ for (const daemon of daemons.values()) {
135
+ const snap = snapshotValue(daemon.config_snapshot);
136
+ if (snap?.role !== "host_supervisor" || snap.daemon_capabilities?.adopt_capable !== true) continue;
137
+ if (!daemon.hostname) continue;
138
+ const seenAt = parseDbTimestampMs(daemon.last_seen_at ?? "");
139
+ if (!Number.isFinite(seenAt) || nowMs - seenAt > ONLINE_MS) continue;
140
+ for (const reported of reportedCandidates(daemon.config_snapshot)) {
141
+ if (candidates.length >= MAX_PUBLIC) break;
142
+ const node = visible.get(reported.node_id);
143
+ if (!node || node.network_id !== daemon.network_id || node.alias !== reported.alias) continue;
144
+ if (!node.hostname || node.hostname !== daemon.hostname) continue;
145
+ if (snapshotValue(node.config_snapshot)?.role === "host_supervisor") continue;
146
+ if (managed.has(node.node_id) || !maySee(node)) continue;
147
+ const key = `${daemon.node_id}\0${node.node_id}`;
148
+ if (seen.has(key)) continue;
149
+ seen.add(key);
150
+ candidates.push({
151
+ node_id: node.node_id, alias: node.alias, daemon_node_id: daemon.node_id, daemon_alias: daemon.alias,
152
+ hostname: daemon.hostname, workdir: reported.workdir, runtime: reported.runtime, launch_hint: reported.launch_hint,
153
+ });
154
+ }
155
+ }
156
+ candidates.sort((a, b) => a.alias.localeCompare(b.alias) || a.node_id.localeCompare(b.node_id) || a.daemon_node_id.localeCompare(b.daemon_node_id));
157
+ return { ok: true, candidates, count: candidates.length };
158
+ }
@@ -0,0 +1,210 @@
1
+ // visibleAgents() batched into one query. The old implementation (kept here verbatim as the
2
+ // reference) ran one nodes ∪ sessions lookup per node_id grant — ~300 queries per call for a
3
+ // restricted member with 300 grants, on every restricted /api/status poll. The new one must return
4
+ // IDENTICAL output (same members, same order) on randomized fixtures.
5
+
6
+ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
7
+ import { mkdtempSync, rmSync } from "node:fs";
8
+ import { tmpdir } from "node:os";
9
+ import { join } from "node:path";
10
+
11
+ const dir = mkdtempSync(join(tmpdir(), "anet-agent-access-batch-"));
12
+ process.env.COMMHUB_DB = join(dir, "hub.db");
13
+
14
+ let db: any;
15
+ let visibleAgents: (userId: string, networkId: string) => any;
16
+ let listAgentGrants: (networkId: string, userId: string) => any[];
17
+ let CHUNK = 0;
18
+
19
+ function visibleAgentsReference(userId: string, networkId: string) {
20
+ const aliases = new Set<string>();
21
+ const nodeIds = new Set<string>();
22
+ const messageAliases = new Set<string>();
23
+ const messageNodeIds = new Set<string>();
24
+ // Group grants (#2131) expanded exactly as agent-access.ts groupGrantNodes() does, appended after
25
+ // the direct grants — the order the old loop saw them in.
26
+ const groupNodes = db.all(
27
+ `SELECT m.node_id, g.can_message
28
+ FROM network_member_group_grants g
29
+ JOIN agent_groups ag ON ag.group_id = g.group_id AND ag.network_id = g.network_id
30
+ JOIN agent_group_members m ON m.group_id = g.group_id
31
+ JOIN nodes n ON n.node_id = m.node_id AND n.network_id = g.network_id
32
+ WHERE g.network_id = ?1 AND g.user_id = ?2`,
33
+ networkId, userId,
34
+ ).map((row: any) => ({ node_id: row.node_id, alias: null, can_message: row.can_message === 1 }));
35
+ for (const grant of [...listAgentGrants(networkId, userId), ...groupNodes]) {
36
+ const grantAliases: string[] = [];
37
+ if (grant.node_id) {
38
+ nodeIds.add(grant.node_id);
39
+ if (grant.can_message) messageNodeIds.add(grant.node_id);
40
+ for (const row of db.all(
41
+ `SELECT alias FROM nodes WHERE node_id = ?1 AND network_id = ?2
42
+ UNION SELECT alias FROM sessions WHERE node_id = ?1 AND network_id = ?2`,
43
+ grant.node_id, networkId,
44
+ )) {
45
+ if (row.alias) grantAliases.push(row.alias);
46
+ }
47
+ } else if (grant.alias) {
48
+ grantAliases.push(grant.alias);
49
+ }
50
+ for (const alias of grantAliases) {
51
+ aliases.add(alias);
52
+ if (grant.can_message) messageAliases.add(alias);
53
+ }
54
+ }
55
+ return { aliases: [...aliases], nodeIds: [...nodeIds], messageAliases: [...messageAliases], messageNodeIds: [...messageNodeIds] };
56
+ }
57
+
58
+ // Deterministic PRNG so a failure is reproducible from the printed seed.
59
+ function rng(seed: number) {
60
+ let s = seed >>> 0;
61
+ return () => { s = (s * 1664525 + 1013904223) >>> 0; return s / 2 ** 32; };
62
+ }
63
+
64
+ let seq = 0;
65
+ function seedFixture(seed: number, opts: { nodes: number; grants: number; groups?: number }) {
66
+ const r = rng(seed);
67
+ const pick = <T,>(xs: T[]) => xs[Math.floor(r() * xs.length)];
68
+ const tag = `s${seed}_${seq++}`;
69
+ db.exec("BEGIN");
70
+ const net = `net_${tag}`, other = `net_${tag}_other`, user = `u_${tag}`;
71
+ db.run(`INSERT INTO users (user_id, username, password_hash) VALUES (?1, ?1, 'x')`, [user]);
72
+ const nodeIds: string[] = [];
73
+ const legacyAliases: string[] = [];
74
+ for (let i = 0; i < opts.nodes; i++) {
75
+ const nodeId = `node_${tag}_${i}`;
76
+ nodeIds.push(nodeId);
77
+ const alias = `agent-${tag}-${i}`;
78
+ const shape = r();
79
+ // nodes row (sometimes missing, sometimes NULL alias)
80
+ if (shape > 0.1) db.run(`INSERT INTO nodes (node_id, node_name, alias, network_id) VALUES (?1, ?2, ?3, ?4)`, [nodeId, alias, shape > 0.15 ? alias : null, net]);
81
+ // sessions rows: same alias, a renamed alias (rename window), several, or none
82
+ const sessions = r() < 0.2 ? 0 : 1 + Math.floor(r() * 3);
83
+ for (let k = 0; k < sessions; k++) {
84
+ const sAlias = k === 0 && r() < 0.6 ? alias : `${alias}-renamed-${k}`;
85
+ db.run(`INSERT INTO sessions (resume_id, alias, node_id, status, network_id) VALUES (?1, ?2, ?3, 'idle', ?4)`, [`r_${tag}_${i}_${k}`, sAlias, nodeId, net]);
86
+ }
87
+ // same node_id in another network must never leak in
88
+ if (r() < 0.3) db.run(`INSERT INTO sessions (resume_id, alias, node_id, status, network_id) VALUES (?1, ?2, ?3, 'idle', ?4)`, [`r_${tag}_${i}_x`, `${alias}-elsewhere`, nodeId, other]);
89
+ }
90
+ for (let i = 0; i < Math.ceil(opts.nodes / 5); i++) {
91
+ const alias = `legacy-${tag}-${i}`;
92
+ legacyAliases.push(alias);
93
+ db.run(`INSERT INTO sessions (resume_id, alias, status, network_id) VALUES (?1, ?2, 'idle', ?3)`, [`rl_${tag}_${i}`, alias, net]);
94
+ }
95
+ const usedAliases = new Set<string>();
96
+ // distinct nodes in a shuffled order (the grant table has one row per node per member)
97
+ const order = nodeIds.map(n => [r(), n] as const).sort((a, b) => a[0] - b[0]).map(([, n]) => n);
98
+ for (let i = 0; i < opts.grants; i++) {
99
+ const byNode = r() < 0.8;
100
+ const can = r() < 0.5 ? 1 : 0;
101
+ if (byNode) {
102
+ const nodeId = r() < 0.05 ? `node_${tag}_ghost_${i}` : order.pop();
103
+ if (!nodeId) continue;
104
+ db.run(`INSERT INTO network_member_agent_grants (network_id, user_id, node_id, alias, can_message) VALUES (?1, ?2, ?3, NULL, ?4)`, [net, user, nodeId, can]);
105
+ } else {
106
+ const alias = pick(legacyAliases);
107
+ if (usedAliases.has(alias)) continue;
108
+ usedAliases.add(alias);
109
+ db.run(`INSERT INTO network_member_agent_grants (network_id, user_id, node_id, alias, can_message) VALUES (?1, ?2, NULL, ?3, ?4)`, [net, user, alias, can]);
110
+ }
111
+ }
112
+ // Groups (#2131): some granted, some not; members include nodes also granted directly (with a
113
+ // different can_message), ghost nodes with no nodes row, and a node that lives in another network.
114
+ const groups = opts.groups ?? 0;
115
+ for (let gi = 0; gi < groups; gi++) {
116
+ const groupId = `grp_${tag}_${gi}`;
117
+ const groupNet = r() < 0.1 ? other : net;
118
+ db.run(`INSERT INTO agent_groups (group_id, network_id, name) VALUES (?1, ?2, ?3)`, [groupId, groupNet, `group ${tag} ${gi}`]);
119
+ const size = 1 + Math.floor(r() * 8);
120
+ const members = new Set<string>();
121
+ for (let k = 0; k < size; k++) members.add(r() < 0.05 ? `node_${tag}_ghostmember_${gi}_${k}` : pick(nodeIds));
122
+ if (r() < 0.2) {
123
+ const foreign = `node_${tag}_foreign_${gi}`;
124
+ db.run(`INSERT INTO nodes (node_id, node_name, alias, network_id) VALUES (?1, ?1, ?2, ?3)`, [foreign, `foreign-${tag}-${gi}`, other]);
125
+ members.add(foreign);
126
+ }
127
+ for (const m of members) db.run(`INSERT INTO agent_group_members (group_id, node_id) VALUES (?1, ?2)`, [groupId, m]);
128
+ if (r() < 0.7) db.run(`INSERT INTO network_member_group_grants (network_id, user_id, group_id, can_message) VALUES (?1, ?2, ?3, ?4)`, [net, user, groupId, r() < 0.5 ? 1 : 0]);
129
+ }
130
+ db.exec("COMMIT");
131
+ return { net, user };
132
+ }
133
+
134
+ beforeAll(async () => {
135
+ ({ db } = await import("./db.js"));
136
+ ({ visibleAgents, listAgentGrants, VISIBLE_AGENTS_CHUNK: CHUNK } = await import("./agent-access.js") as any);
137
+ });
138
+
139
+ afterAll(() => {
140
+ try { rmSync(dir, { recursive: true, force: true }); } catch {}
141
+ });
142
+
143
+ describe("visibleAgents batched = reference, on randomized fixtures", () => {
144
+ test("200 random fixtures: identical output (members and order)", () => {
145
+ for (let seed = 1; seed <= 200; seed++) {
146
+ const { net, user } = seedFixture(seed, { nodes: 5 + (seed % 40), grants: seed % 7 === 0 ? 0 : 3 + (seed % 50), groups: seed % 3 === 0 ? 0 : 1 + (seed % 12) });
147
+ const got = visibleAgents(user, net);
148
+ const want = visibleAgentsReference(user, net);
149
+ if (JSON.stringify(got) !== JSON.stringify(want)) {
150
+ throw new Error(`seed ${seed} differs:\nnew ${JSON.stringify(got)}\nold ${JSON.stringify(want)}`);
151
+ }
152
+ }
153
+ }, 120_000);
154
+
155
+ test("the fixtures exercise every shape (rename window, NULL alias, ghost node, legacy alias, other network, groups)", () => {
156
+ const { net, user } = seedFixture(4242, { nodes: 60, grants: 80, groups: 15 });
157
+ const groupNodes = db.get<{ n: number }>("SELECT COUNT(*) AS n FROM network_member_group_grants WHERE network_id = ?1 AND user_id = ?2", net, user)!.n;
158
+ expect(groupNodes).toBeGreaterThan(0);
159
+ const got = visibleAgents(user, net);
160
+ expect(got.aliases.some((a: string) => a.includes("-renamed-"))).toBe(true);
161
+ expect(got.aliases.some((a: string) => a.startsWith("legacy-"))).toBe(true);
162
+ expect(got.aliases.some((a: string) => a.endsWith("-elsewhere"))).toBe(false);
163
+ expect(got.messageAliases.length).toBeLessThan(got.aliases.length);
164
+ expect(JSON.stringify(got)).toBe(JSON.stringify(visibleAgentsReference(user, net)));
165
+ });
166
+
167
+ test("groups only (no direct grants): identical output, group nodes visible", () => {
168
+ const { net, user } = seedFixture(9090, { nodes: 80, grants: 0, groups: 25 });
169
+ const got = visibleAgents(user, net);
170
+ expect(got.nodeIds.length).toBeGreaterThan(0);
171
+ expect(JSON.stringify(got)).toBe(JSON.stringify(visibleAgentsReference(user, net)));
172
+ });
173
+
174
+ test("no grants → all empty; unknown user → all empty", () => {
175
+ const { net } = seedFixture(7, { nodes: 10, grants: 0 });
176
+ expect(visibleAgents("nobody", net)).toEqual({ aliases: [], nodeIds: [], messageAliases: [], messageNodeIds: [] });
177
+ });
178
+
179
+ test("query-count guard: a fixed number of queries per call, not one per grant (#2133)", () => {
180
+ const { net, user } = seedFixture(301, { nodes: 400, grants: 420, groups: 30 });
181
+ const grants = listAgentGrants(net, user).length;
182
+ expect(grants).toBeGreaterThanOrEqual(300);
183
+ const calls = { all: 0, get: 0 };
184
+ const all = db.all.bind(db), get = db.get.bind(db);
185
+ db.all = (...a: any[]) => { calls.all++; return all(...a); };
186
+ db.get = (...a: any[]) => { calls.get++; return get(...a); };
187
+ try { visibleAgents(user, net); } finally { db.all = all; db.get = get; }
188
+ // direct grants + group grants + ceil(nodes / chunk) alias reads
189
+ expect(calls.all + calls.get).toBeLessThanOrEqual(2 + Math.ceil(grants / CHUNK));
190
+ expect(calls.all + calls.get).toBeLessThanOrEqual(3);
191
+ }, 60_000);
192
+
193
+ test("more granted nodes than one chunk: same output across the chunk boundary", () => {
194
+ const { net, user } = seedFixture(777, { nodes: CHUNK + 120, grants: CHUNK + 200 });
195
+ expect(listAgentGrants(net, user).filter((g: any) => g.node_id).length).toBeGreaterThan(CHUNK);
196
+ expect(JSON.stringify(visibleAgents(user, net))).toBe(JSON.stringify(visibleAgentsReference(user, net)));
197
+ }, 120_000);
198
+
199
+ test("timing at 300 grants (printed; new must be faster)", () => {
200
+ const { net, user } = seedFixture(300, { nodes: 400, grants: 420 });
201
+ const grants = listAgentGrants(net, user).length;
202
+ expect(grants).toBeGreaterThanOrEqual(300);
203
+ const time = (fn: () => unknown, n = 50) => { fn(); const t0 = performance.now(); for (let i = 0; i < n; i++) fn(); return (performance.now() - t0) / n; };
204
+ const oldMs = time(() => visibleAgentsReference(user, net));
205
+ const newMs = time(() => visibleAgents(user, net));
206
+ console.log(`visibleAgents @ ${grants} grants: old ${oldMs.toFixed(2)} ms/call, new ${newMs.toFixed(2)} ms/call (${(oldMs / newMs).toFixed(1)}x)`);
207
+ expect(JSON.stringify(visibleAgents(user, net))).toBe(JSON.stringify(visibleAgentsReference(user, net)));
208
+ expect(newMs).toBeLessThan(oldMs);
209
+ }, 120_000);
210
+ });