@sleep2agi/commhub-server 0.9.0-preview.22 → 0.9.0-preview.220

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 (407) hide show
  1. package/README.md +129 -9
  2. package/bin/commhub.ts +93 -9
  3. package/package.json +7 -7
  4. package/src/ack-create-request-transport.test.ts +182 -0
  5. package/src/ack-create-request.test.ts +50 -7
  6. package/src/admin-delete-network-http.test.ts +228 -0
  7. package/src/admin-networks-http.test.ts +88 -0
  8. package/src/adoption-candidates-http.test.ts +137 -0
  9. package/src/adoption-candidates.ts +158 -0
  10. package/src/agent-access-batch.test.ts +210 -0
  11. package/src/agent-access.ts +487 -0
  12. package/src/agent-acl-groups-http.test.ts +247 -0
  13. package/src/agent-acl-http.test.ts +659 -0
  14. package/src/agent-acl-slice3-http.test.ts +654 -0
  15. package/src/agent-department-http.test.ts +215 -0
  16. package/src/agent-groups-perf.test.ts +223 -0
  17. package/src/agent-notice.ts +48 -0
  18. package/src/agent-team-whoami-http.test.ts +98 -0
  19. package/src/agent-teams-http.test.ts +330 -0
  20. package/src/agent-teams.ts +244 -0
  21. package/src/alias-baseline-2571.test.ts +162 -0
  22. package/src/alias-baseline.ts +113 -0
  23. package/src/alias-filter.test.ts +72 -0
  24. package/src/alias-filter.ts +42 -0
  25. package/src/api-host-supervisors-can-create-nodes.test.ts +350 -0
  26. package/src/api-host-supervisors-fallback.test.ts +6 -7
  27. package/src/api-host-supervisors-runtime-readiness.test.ts +195 -0
  28. package/src/api-nodes-shape.test.ts +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 +52 -2
  35. package/src/avatar-validate.ts +35 -1
  36. package/src/backfill-node-ids-2664.test.ts +128 -0
  37. package/src/binding-generation-http.test.ts +121 -0
  38. package/src/blocked-exit-on-reply.test.ts +122 -0
  39. package/src/broadcast-fanout-2721.test.ts +149 -0
  40. package/src/broadcast-fanout.ts +117 -0
  41. package/src/chain-attempt-dedup.test.ts +447 -0
  42. package/src/clone-node.test.ts +248 -0
  43. package/src/clone-node.ts +289 -0
  44. package/src/codex-config-flags.ts +77 -0
  45. package/src/codex-fork-contract.ts +23 -0
  46. package/src/codex-fork-migration.test.ts +38 -0
  47. package/src/commhub-bin-args.test.ts +85 -0
  48. package/src/config-apply-validate.test.ts +188 -1
  49. package/src/config-apply-validate.ts +222 -3
  50. package/src/cors-origins.test.ts +40 -0
  51. package/src/create-node-blocked-gate.test.ts +356 -0
  52. package/src/create-node-network-id.test.ts +91 -0
  53. package/src/create-node-tool-schema.test.ts +49 -0
  54. package/src/create-node-unicode-name.test.ts +120 -0
  55. package/src/create-node-validate.test.ts +199 -7
  56. package/src/create-node-validate.ts +232 -15
  57. package/src/create-node-workdir.test.ts +289 -0
  58. package/src/create-node.ts +88 -23
  59. package/src/daemon-provider-snapshots.test.ts +421 -0
  60. package/src/daemon-provider-snapshots.ts +327 -0
  61. package/src/daemon-token-owner-http.test.ts +236 -0
  62. package/src/dashboard-slash-routing-http.test.ts +109 -0
  63. package/src/db-adapter-guard.test.ts +148 -0
  64. package/src/db-adapter-translate.test.ts +128 -0
  65. package/src/db-adapter.ts +377 -91
  66. package/src/db-timestamp.test.ts +38 -0
  67. package/src/db-timestamp.ts +15 -0
  68. package/src/db.ts +1296 -153
  69. package/src/delivered-without-push.test.ts +140 -0
  70. package/src/department-groups-http.test.ts +209 -0
  71. package/src/department-groups-sync-http.test.ts +328 -0
  72. package/src/department-groups.ts +434 -0
  73. package/src/department-heads-http.test.ts +350 -0
  74. package/src/department-heads.ts +226 -0
  75. package/src/departments-agent-count.test.ts +132 -0
  76. package/src/departments-http.test.ts +185 -0
  77. package/src/departments-mcp.test.ts +128 -0
  78. package/src/departments.ts +318 -0
  79. package/src/desktop-message-seam.test.ts +150 -0
  80. package/src/desktop-message.test.ts +368 -0
  81. package/src/dm-file-scope-http.test.ts +178 -0
  82. package/src/empty-node-sweeper.test.ts +104 -0
  83. package/src/empty-node-sweeper.ts +88 -0
  84. package/src/env-transport-gate-http.test.ts +240 -0
  85. package/src/env-transport-gate.ts +80 -0
  86. package/src/env-transport-policy.ts +56 -0
  87. package/src/etag-of.test.ts +57 -0
  88. package/src/event-loop-lag.test.ts +180 -0
  89. package/src/event-loop-lag.ts +201 -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-anon-readers.ts +59 -0
  104. package/src/health-host-disk-2756.test.ts +71 -0
  105. package/src/health-redaction.test.ts +1574 -2
  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 +266 -0
  112. package/src/hub-provider-config.test.ts +156 -0
  113. package/src/hub-provider-config.ts +124 -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 +6 -2
  122. package/src/license-state.test.ts +56 -0
  123. package/src/license-state.ts +48 -0
  124. package/src/list-host-supervisors.test.ts +15 -4
  125. package/src/mcp-context-cost-http.test.ts +127 -0
  126. package/src/mcp-inflight.test.ts +92 -0
  127. package/src/mcp-inflight.ts +38 -0
  128. package/src/mcp-projects-events-http.test.ts +165 -0
  129. package/src/mcp-route-label-http.test.ts +120 -0
  130. package/src/mcp-write-network-resolution.test.ts +435 -0
  131. package/src/member-audit-network-id-http.test.ts +93 -0
  132. package/src/member-presence-http.test.ts +210 -0
  133. package/src/messages-ack-by-agent-http.test.ts +142 -0
  134. package/src/migrate-sqlite-to-pg.test.ts +47 -0
  135. package/src/migrate-sqlite-to-pg.ts +263 -0
  136. package/src/model-auth-notify-http.test.ts +181 -0
  137. package/src/model-auth-notify.ts +116 -0
  138. package/src/network-name-http.test.ts +75 -0
  139. package/src/network-rules-http.test.ts +169 -0
  140. package/src/network-rules.ts +129 -0
  141. package/src/network-scope.ts +276 -0
  142. package/src/network-token-membership-http.test.ts +139 -0
  143. package/src/node-alias-control.ts +12 -0
  144. package/src/node-attrs-validate.ts +88 -0
  145. package/src/node-attrs.test.ts +258 -0
  146. package/src/node-caller-identity-http.test.ts +1091 -0
  147. package/src/node-create-request-status-http.test.ts +105 -0
  148. package/src/node-daemon-bindings.test.ts +132 -0
  149. package/src/node-daemon-bindings.ts +135 -0
  150. package/src/node-failure-alert.test.ts +150 -0
  151. package/src/node-failure-alert.ts +177 -0
  152. package/src/node-files-transport.test.ts +344 -0
  153. package/src/node-health-codex-login.test.ts +120 -0
  154. package/src/node-health-dispatch-http.test.ts +335 -0
  155. package/src/node-health-guard.ts +121 -0
  156. package/src/node-health-passthrough.test.ts +115 -0
  157. package/src/node-health-store.ts +101 -0
  158. package/src/node-id-alias.test.ts +190 -0
  159. package/src/node-identity-conflict-http.test.ts +269 -0
  160. package/src/node-identity-conflict.ts +142 -0
  161. package/src/node-identity-mismatch.test.ts +74 -0
  162. package/src/node-in-flight-tasks.ts +31 -0
  163. package/src/node-lifecycle-controllable.test.ts +64 -0
  164. package/src/node-lifecycle-controllable.ts +53 -0
  165. package/src/node-lifecycle-read-http.test.ts +250 -0
  166. package/src/node-lifecycle-read.ts +124 -0
  167. package/src/node-logs-transport.test.ts +263 -0
  168. package/src/node-peer-allowlist.test.ts +114 -0
  169. package/src/node-permissions-http.test.ts +728 -0
  170. package/src/node-permissions.ts +494 -0
  171. package/src/node-request-retention.test.ts +281 -0
  172. package/src/node-request-retention.ts +120 -0
  173. package/src/node-secret-rest-http.test.ts +190 -0
  174. package/src/node-serviceability.test.ts +86 -0
  175. package/src/node-serviceability.ts +124 -0
  176. package/src/node-session-control-http.test.ts +310 -0
  177. package/src/node-session-control.ts +258 -0
  178. package/src/node-skills-transport.test.ts +212 -0
  179. package/src/node-token-identity.ts +35 -0
  180. package/src/node-token-ownership.ts +51 -0
  181. package/src/node-token-privilege-http.test.ts +158 -0
  182. package/src/not-found-api-http.test.ts +67 -0
  183. package/src/observer-avatar-http.test.ts +102 -9
  184. package/src/observer-push.test.ts +76 -0
  185. package/src/opencode-catalog-report-http.test.ts +139 -0
  186. package/src/opencode-v2-catalog.test.ts +268 -0
  187. package/src/opencode-v2-catalog.ts +356 -0
  188. package/src/package-version-consistency.test.ts +25 -0
  189. package/src/parent-source-marker.test.ts +50 -0
  190. package/src/password-network-tokens.ts +25 -0
  191. package/src/peer-reply-atomic.test.ts +457 -0
  192. package/src/peer-reply-capability.test.ts +70 -0
  193. package/src/pg-worker.ts +87 -0
  194. package/src/poll-pacing.test.ts +74 -0
  195. package/src/poll-pacing.ts +123 -0
  196. package/src/project-dir-warn-clear-http.test.ts +132 -0
  197. package/src/project-viewer-can-http.test.ts +116 -0
  198. package/src/push.test.ts +20 -10
  199. package/src/push.ts +382 -9
  200. package/src/redact-tokens.test.ts +86 -0
  201. package/src/redact-tokens.ts +43 -0
  202. package/src/rejection-counters.test.ts +72 -0
  203. package/src/rejection-counters.ts +173 -0
  204. package/src/rename.ts +38 -10
  205. package/src/reply-target-derivation.test.ts +96 -0
  206. package/src/report-status-handover-capabilities-http.test.ts +124 -0
  207. package/src/report-status-host-schema.test.ts +235 -0
  208. package/src/report-status-resume-id-handover.test.ts +184 -0
  209. package/src/report-status-secret-keys.test.ts +140 -0
  210. package/src/require-explicit-test-db.ts +9 -0
  211. package/src/requirement-due-reminders-http.test.ts +620 -0
  212. package/src/requirement-due-reminders.ts +416 -0
  213. package/src/requirement-events-http.test.ts +295 -0
  214. package/src/requirement-events.test.ts +45 -0
  215. package/src/requirement-events.ts +144 -0
  216. package/src/requirement-notify.ts +165 -0
  217. package/src/requirement-participant-notify-http.test.ts +309 -0
  218. package/src/requirement-tag-ops-http.test.ts +425 -0
  219. package/src/requirement-tag-tree-http.test.ts +275 -0
  220. package/src/requirement-tag-tree.ts +127 -0
  221. package/src/requirement-tags.ts +102 -0
  222. package/src/requirements-abandoned-http.test.ts +236 -0
  223. package/src/requirements-comment-http.test.ts +167 -0
  224. package/src/requirements-completed-at-migration.test.ts +70 -0
  225. package/src/requirements-errors-mcp-http.test.ts +164 -0
  226. package/src/requirements-errors.ts +158 -0
  227. package/src/requirements-etag-http.test.ts +91 -0
  228. package/src/requirements-http.test.ts +709 -0
  229. package/src/requirements-last-event-http.test.ts +349 -0
  230. package/src/requirements-list-mcp-slim-http.test.ts +155 -0
  231. package/src/requirements-list-slim-http.test.ts +324 -0
  232. package/src/requirements-mcp.test.ts +163 -0
  233. package/src/requirements-migrate.ts +283 -0
  234. package/src/requirements-owner-strict-mcp-http.test.ts +145 -0
  235. package/src/requirements-people-http.test.ts +114 -0
  236. package/src/requirements-people-mcp-http.test.ts +231 -0
  237. package/src/requirements-people.ts +196 -0
  238. package/src/requirements-priority-lowest.test.ts +114 -0
  239. package/src/requirements-projects-network-echo.test.ts +57 -0
  240. package/src/requirements-projects-parent-http.test.ts +123 -0
  241. package/src/requirements-search-http.test.ts +182 -0
  242. package/src/requirements-search.test.ts +32 -0
  243. package/src/requirements-search.ts +145 -0
  244. package/src/requirements-seq-http.test.ts +193 -0
  245. package/src/requirements-seq-migration.test.ts +63 -0
  246. package/src/requirements-start-date.test.ts +125 -0
  247. package/src/requirements-stats-http.test.ts +357 -0
  248. package/src/requirements-stats.ts +195 -0
  249. package/src/requirements-status-participants-http.test.ts +222 -0
  250. package/src/requirements-upgrade-e2e.test.ts +126 -0
  251. package/src/requirements-upgrade-migration.test.ts +98 -0
  252. package/src/requirements.ts +2042 -0
  253. package/src/resolve-port.test.ts +57 -0
  254. package/src/resolve-port.ts +44 -0
  255. package/src/rest-alias-network-fallback-http.test.ts +123 -0
  256. package/src/rest-alias-network-fallback.test.ts +60 -0
  257. package/src/rest-alias-network-fallback.ts +65 -0
  258. package/src/rest-explicit-columns-http.test.ts +266 -0
  259. package/src/rest-identity.test.ts +130 -0
  260. package/src/rest-identity.ts +141 -0
  261. package/src/rest-projections.ts +72 -0
  262. package/src/rest-read-network-real-chain.test.ts +97 -0
  263. package/src/rest-write-network-resolution.test.ts +133 -0
  264. package/src/restart-readiness-http.test.ts +121 -0
  265. package/src/restricted-files.ts +76 -0
  266. package/src/retention-first-sweep-quiet.test.ts +31 -0
  267. package/src/retention.test.ts +100 -40
  268. package/src/retention.ts +423 -104
  269. package/src/route-callers-http.test.ts +120 -0
  270. package/src/route-timing.test.ts +218 -0
  271. package/src/route-timing.ts +262 -0
  272. package/src/rules-file-duplicate-alias.test.ts +234 -0
  273. package/src/rules-file-session-target.test.ts +207 -0
  274. package/src/rules-file-transport.test.ts +237 -0
  275. package/src/runtime-label.test.ts +22 -0
  276. package/src/runtime-label.ts +21 -0
  277. package/src/runtime-readiness.ts +90 -0
  278. package/src/schedule-agent-mcp-http.test.ts +432 -0
  279. package/src/schedule-agent.ts +252 -0
  280. package/src/schedule-starved.test.ts +92 -0
  281. package/src/schedule-starved.ts +114 -0
  282. package/src/scheduled-backoff-http.test.ts +193 -0
  283. package/src/scheduled-backoff.ts +64 -0
  284. package/src/scheduled-doorbell-nodeless-session.test.ts +134 -0
  285. package/src/scheduled-failure-backoff-2622.test.ts +145 -0
  286. package/src/scheduled-failure-code.test.ts +73 -0
  287. package/src/scheduled-failure-code.ts +105 -0
  288. package/src/scheduled-failures-http.test.ts +279 -0
  289. package/src/scheduled-failures.ts +425 -0
  290. package/src/scheduled-noprogress-backoff-2622.test.ts +163 -0
  291. package/src/scheduled-offline-backoff-probe.test.ts +56 -0
  292. package/src/scheduled-offline.test.ts +131 -0
  293. package/src/scheduled-offline.ts +66 -0
  294. package/src/scheduled-outcome-guidance-http.test.ts +139 -0
  295. package/src/scheduled-outcome-guidance.ts +9 -0
  296. package/src/scheduled-reply-unread-http.test.ts +212 -0
  297. package/src/scheduled-requirement-wake-http.test.ts +279 -0
  298. package/src/scheduled-requirement-wake.ts +125 -0
  299. package/src/scheduled-run-terminal.test.ts +268 -0
  300. package/src/scheduled-skip-blocking-task.test.ts +120 -0
  301. package/src/scheduled-skip-path-backoff-2622.test.ts +98 -0
  302. package/src/scheduled-stuck-http.test.ts +316 -0
  303. package/src/scheduled-stuck-notice-cap.test.ts +80 -0
  304. package/src/scheduled-stuck.ts +219 -0
  305. package/src/scheduled-tasks-http.test.ts +679 -0
  306. package/src/scheduled-tasks.ts +959 -0
  307. package/src/scheduled-work-outcome-http.test.ts +154 -0
  308. package/src/scheduled-work-outcome.ts +50 -0
  309. package/src/scoped-secrets.ts +141 -0
  310. package/src/send-dedup-request-id.test.ts +229 -0
  311. package/src/send-reply-agent-warning.test.ts +202 -0
  312. package/src/send-reply-alias-optional.test.ts +131 -0
  313. package/src/send-reply-attachments.test.ts +458 -0
  314. package/src/send_dedup.test.ts +54 -0
  315. package/src/send_dedup.ts +52 -6
  316. package/src/serve-error.test.ts +73 -0
  317. package/src/serve-error.ts +56 -0
  318. package/src/server.ts +4921 -344
  319. package/src/session-task-on-dispatch.ts +14 -0
  320. package/src/session-token-ownership-http.test.ts +122 -0
  321. package/src/shared/codex-inventory.ts +41 -0
  322. package/src/shared/daemon-provider-login.ts +31 -0
  323. package/src/shared/daemon-provider-snapshot.ts +52 -0
  324. package/src/shared/external-schedule-contract.ts +60 -0
  325. package/src/shared/node-name.test.ts +62 -0
  326. package/src/shared/node-name.ts +161 -0
  327. package/src/shared/probe-host-allowlist-drift.test.ts +45 -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 +10 -0
  332. package/src/shared/scoped-secret-contract.ts +5 -0
  333. package/src/shared/task-content-limit-drift.test.ts +28 -0
  334. package/src/shared/task-content-limit.ts +25 -0
  335. package/src/side-thread-command-transport.test.ts +312 -0
  336. package/src/side-thread-command-transport.ts +318 -0
  337. package/src/side-thread-http-integration.test.ts +233 -0
  338. package/src/side-thread-http.ts +504 -0
  339. package/src/side-thread-production.test.ts +72 -0
  340. package/src/side-thread-production.ts +118 -0
  341. package/src/side-thread.test.ts +1067 -0
  342. package/src/side-thread.ts +2499 -0
  343. package/src/skillhub-http.test.ts +142 -0
  344. package/src/sqlite-close-checkpoint.test.ts +78 -0
  345. package/src/start-node.test.ts +264 -0
  346. package/src/status-alias-filter-http.test.ts +106 -0
  347. package/src/status-alias-resolver-http.test.ts +163 -0
  348. package/src/status-alias-resolver.ts +19 -0
  349. package/src/status-node-id-filter-http.test.ts +161 -0
  350. package/src/status-read-cache-http.test.ts +229 -0
  351. package/src/status-read-cache.ts +129 -0
  352. package/src/stop-delete-node.test.ts +567 -1
  353. package/src/task-access-http.test.ts +402 -0
  354. package/src/task-access.ts +420 -0
  355. package/src/task-activity.ts +60 -0
  356. package/src/task-auth-origin-http.test.ts +93 -0
  357. package/src/task-auth-origin.test.ts +24 -0
  358. package/src/task-auth-origin.ts +7 -0
  359. package/src/task-consumption.test.ts +490 -0
  360. package/src/task-diagnostic-http.test.ts +149 -0
  361. package/src/task-diagnostic.test.ts +115 -0
  362. package/src/task-diagnostic.ts +118 -0
  363. package/src/task-expiry-notice-http.test.ts +287 -0
  364. package/src/task-expiry-notice.ts +315 -0
  365. package/src/task-idempotency-mcp.test.ts +142 -0
  366. package/src/task-idempotency.test.ts +76 -0
  367. package/src/task-idempotency.ts +81 -0
  368. package/src/task-late-replies.ts +54 -0
  369. package/src/task-late-reply-http.test.ts +227 -0
  370. package/src/task-lifecycle-watcher-busy.test.ts +114 -0
  371. package/src/task-lifecycle-watcher.test.ts +204 -0
  372. package/src/task-lifecycle-watcher.ts +109 -0
  373. package/src/task-network-resolution-http.test.ts +140 -0
  374. package/src/task-offline-delivery-2668.test.ts +119 -0
  375. package/src/task-offline-delivery.ts +81 -0
  376. package/src/task-orphan-http.test.ts +287 -0
  377. package/src/task-orphan.ts +119 -0
  378. package/src/task-queue-ahead-http.test.ts +309 -0
  379. package/src/task-queue-ahead-scale.test.ts +236 -0
  380. package/src/task-queue-ahead.ts +186 -0
  381. package/src/task-rejection-log-http.test.ts +160 -0
  382. package/src/task-rejection-log.ts +58 -0
  383. package/src/task-sender-http.test.ts +143 -0
  384. package/src/task-stale-open-http.test.ts +292 -0
  385. package/src/task-stale-open.ts +103 -0
  386. package/src/tasks-pagination-http.test.ts +141 -0
  387. package/src/team-rules-status-http.test.ts +90 -0
  388. package/src/team-rules-status.test.ts +59 -0
  389. package/src/team-rules-status.ts +72 -0
  390. package/src/tmux-allowlist.test.ts +48 -0
  391. package/src/tool-audience-http.test.ts +230 -0
  392. package/src/tool-audience.ts +127 -0
  393. package/src/tools-list-json-schema.test.ts +94 -0
  394. package/src/tools.ts +4320 -413
  395. package/src/upload-early-reject-guard.test.ts +155 -0
  396. package/src/uploads-http.test.ts +86 -7
  397. package/src/uploads.ts +103 -6
  398. package/src/user-avatar-http.test.ts +74 -0
  399. package/src/user-avatar-image.ts +160 -0
  400. package/src/user-avatar-migration.test.ts +25 -0
  401. package/src/user-avatar-upload-http.test.ts +348 -0
  402. package/src/user-inbox-by-agent-http.test.ts +161 -0
  403. package/src/user-inbox-netid-notnull.test.ts +122 -0
  404. package/src/user-inbox-read-http.test.ts +223 -0
  405. package/src/user-inbox-schema.test.ts +54 -0
  406. package/src/version-stats.test.ts +66 -0
  407. package/src/version-stats.ts +109 -0
@@ -0,0 +1,121 @@
1
+ // #1511 —— `/api/nodes` 要给客户端一份「能不能替你重启」的判断,而且要和在途任务一致。
2
+ //
3
+ // 客户端场景:保存密钥/env 之后,必须能立刻二选一告诉用户
4
+ // 「已安排重启」 vs 「需要你自己重启(命令:…)」
5
+ // 判据必须和 restart_node / stop_node 同一份,否则会出现「客户端说空闲、一点就被拒」。
6
+
7
+ import { describe, expect, test, beforeAll, afterAll } from "bun:test";
8
+ import { mkdtempSync, rmSync } from "fs";
9
+ import { join } from "path";
10
+ import { tmpdir } from "os";
11
+ import { register, createNetworkTokenForNode } from "./auth.js";
12
+ import { db } from "./db.js";
13
+
14
+ const DIR = mkdtempSync(join(tmpdir(), "anet-restart-readiness-"));
15
+ let BASE = "";
16
+ let hub: any = null;
17
+ const PW = "RestartReadinessPassw0rd!";
18
+ let NET = "";
19
+ let TOKEN = "";
20
+ let USER = "";
21
+
22
+ async function send(method: string, path: string, body?: unknown) {
23
+ const res = await fetch(`${BASE}${path}`, { method, headers: { Authorization: `Bearer ${TOKEN}`, "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });
24
+ const text = await res.text();
25
+ let json: any = null; try { json = JSON.parse(text); } catch {}
26
+ return { status: res.status, body: json };
27
+ }
28
+
29
+ let seq = 0;
30
+ function mkNode(prefix: "node" | "n", alias: string, opts: { role?: string; lifecycle?: string } = {}) {
31
+ const id = `${prefix}_rr_${seq++}_${Date.now()}`;
32
+ const snap = opts.role ? JSON.stringify({ role: opts.role }) : null;
33
+ db.run("INSERT INTO nodes (node_id, node_name, alias, runtime, network_id, lifecycle_state, config_snapshot, owner_user_id) VALUES (?1,?2,?2,'codex',?3,?4,?5,?6)",
34
+ [id, alias, NET, opts.lifecycle ?? "active", snap, USER]);
35
+ return id;
36
+ }
37
+ function mkTaskFor(alias: string, status: string) {
38
+ const taskId = `t_rr_${seq++}`;
39
+ db.run("INSERT INTO tasks (task_id, from_name, to_name, priority, status, content, created_at, network_id) VALUES (?1,'x',?2,'normal',?3,'c',datetime('now'),?4)", [taskId, alias, status, NET]);
40
+ db.run("INSERT INTO inbox (id, session_name, type, task_id, acked, content, created_at, network_id) VALUES (?1,?2,'task',?3,0,'c',datetime('now'),?4)", [`i_rr_${seq++}`, alias, taskId, NET]);
41
+ return taskId;
42
+ }
43
+
44
+ function mkCreateRequest(nodeId: string) {
45
+ db.run(`INSERT INTO node_create_requests
46
+ (request_id, network_id, daemon_node_id, child_name, runtime, flags_json, env_keys, status, created_at, created_by_token)
47
+ VALUES (?1,?2,'node_daemon_rr',?3,'codex','{}','[]','succeeded',?4,'t')`,
48
+ [`cr_${nodeId.slice(5)}`, NET, `child-${seq++}`, Date.now()]);
49
+ }
50
+
51
+ const rowOf = async (nodeId: string) => {
52
+ const r = await send("GET", `/api/nodes?network_id=${NET}&node_id=${nodeId}`);
53
+ expect(r.status).toBe(200);
54
+ return (r.body.nodes as any[])[0];
55
+ };
56
+
57
+ beforeAll(async () => {
58
+ process.env.COMMHUB_DB ||= join(DIR, "hub.db");
59
+ process.env.COMMHUB_UPLOADS_DIR = join(DIR, "uploads");
60
+ process.env.HOST = "127.0.0.1";
61
+ const a = register(`rr_owner_${Date.now()}`, PW, undefined, "Owner");
62
+ expect(a.ok).toBe(true);
63
+ TOKEN = a.token!; USER = a.user!.user_id; NET = a.network_id!;
64
+ const mod: any = await import("./server.js");
65
+ hub = mod.bootServer({ port: 0, hostname: "127.0.0.1" });
66
+ BASE = `http://127.0.0.1:${hub.port}`;
67
+ }, 30_000);
68
+
69
+ afterAll(() => {
70
+ try { hub?.stop?.(true); } catch {}
71
+ try { rmSync(DIR, { recursive: true, force: true }); } catch {}
72
+ });
73
+
74
+ describe("#1511 restart_readiness", () => {
75
+ test("没人管的节点 = manual,且 can_restart_now=false", async () => {
76
+ const id = mkNode("n", `solo-${seq}`);
77
+ const row = await rowOf(id);
78
+ expect(row.restart_readiness).toEqual({ path: "manual", in_flight: 0, can_restart_now: false });
79
+ });
80
+
81
+ test("created-daemon 的节点 = restart_node;在途任务让它变 false", async () => {
82
+ const id = mkNode("node", `supervised-${seq}`);
83
+ mkCreateRequest(id);
84
+ let row = await rowOf(id);
85
+ expect(row.restart_readiness.path).toBe("restart_node");
86
+ expect(row.restart_readiness.can_restart_now).toBe(true);
87
+
88
+ mkTaskFor(row.alias, "running");
89
+ row = await rowOf(id);
90
+ expect(row.restart_readiness.in_flight).toBe(1);
91
+ expect(row.restart_readiness.can_restart_now).toBe(false);
92
+ });
93
+
94
+ test("终态任务不算在途(与 stop_node 同一判据)", async () => {
95
+ const id = mkNode("node", `replied-${seq}`);
96
+ mkCreateRequest(id);
97
+ const row = await rowOf(id);
98
+ mkTaskFor(row.alias, "replied");
99
+ const after = await rowOf(id);
100
+ expect(after.restart_readiness.in_flight).toBe(0);
101
+ expect(after.restart_readiness.can_restart_now).toBe(true);
102
+ });
103
+
104
+ test("adopt 来的节点 = stop_then_start(restart_node 会被拒,但 daemon 仍能 Stop→Start)", async () => {
105
+ const id = mkNode("n", `adopted-${seq}`);
106
+ db.run("INSERT INTO node_daemon_bindings (request_id, network_id, node_id, daemon_node_id, workdir, requested_by, status, created_at, updated_at) VALUES (?1,?2,?3,'node_daemon_rr','/tmp','u','active',0,0)",
107
+ [`adopt_rr_${seq}`, NET, id]);
108
+ const row = await rowOf(id);
109
+ expect(row.restart_readiness).toEqual({ path: "stop_then_start", in_flight: 0, can_restart_now: true });
110
+ });
111
+
112
+ test("stopped 节点:在途计数不挡路(restart 是把 lifecycle 翻回 active 的出口)", async () => {
113
+ const id = mkNode("node", `stopped-${seq}`, { lifecycle: "stopped" });
114
+ mkCreateRequest(id);
115
+ const row = await rowOf(id);
116
+ mkTaskFor(row.alias, "running");
117
+ const after = await rowOf(id);
118
+ expect(after.restart_readiness.in_flight).toBe(1);
119
+ expect(after.restart_readiness.can_restart_now).toBe(true);
120
+ });
121
+ });
@@ -0,0 +1,76 @@
1
+ // 多用户 Agent 权限 —— 受限成员与上传文件。
2
+ // 文件按网络归属;受限成员(只看授权 Agent 的成员)在受限网络里不能凭 file_id 读网络里任意文件,
3
+ // 也不能把自己看不见的 file_id 塞进发给授权 Agent 的任务(那等于借 Agent 的网络令牌去读)。
4
+ import { existsSync, readFileSync } from "fs";
5
+ import { db } from "./db.js";
6
+ import { addAgentTimelineScope, addOwnTrafficScope, type RestNetworkScope } from "./network-scope.js";
7
+ import { FILE_ID_REGEX, indexEntryPath, validateIndexEntry } from "./uploads.js";
8
+
9
+ /**
10
+ * 受限成员能不能看见这个文件:只认**对方(授权 Agent / 给他发私信的人)放进来**的附件 ——
11
+ * user_inbox 里发给自己的私信附件;
12
+ * 授权 Agent 时间线上(#563,与 /api/tasks 同一判据 addAgentTimelineScope)**别人**发出的任务的
13
+ * attachments —— 时间线上看得见那条消息,就得看得见它带的图;发送方是受限成员时发送路径已校验过
14
+ * 他看得见这些文件,不受限的发送方本来就看得见全网文件;
15
+ * 时间线上任务的 reply_attachments(Agent 回复写进的);
16
+ * 授权 Agent 发给自己的 inbox 行的 attachments。
17
+ * 自己随任务带出去的 attachments **不算**:否则把任意 file_id 塞进自己的任务就能「解锁」别人的文件。
18
+ */
19
+ export function restrictedMemberSeesFile(userId: string, username: string, networkId: string, fileId: string): boolean {
20
+ if (!FILE_ID_REGEX.test(fileId)) return false;
21
+ const listed = (metaJson: string | null | undefined, key: "attachments" | "reply_attachments"): boolean => {
22
+ if (!metaJson) return false;
23
+ try {
24
+ const list = JSON.parse(metaJson)?.[key];
25
+ return Array.isArray(list) && list.some((a: any) => a && typeof a === "object" && a.file_id === fileId);
26
+ } catch { return false; }
27
+ };
28
+ // LIKE 只做预筛(file_id 只含 [A-Za-z0-9_-],`_` 转义后逐字匹配),真正的判定在 listed() 里按键解析。
29
+ const needle = `%"${fileId.replace(/_/g, "\\_")}"%`;
30
+ for (const row of db.all<{ meta_json: string | null }>(
31
+ "SELECT meta_json FROM user_inbox WHERE user_id = ?1 AND network_id = ?2 AND meta_json LIKE ?3 ESCAPE '\\' LIMIT 50",
32
+ userId, networkId, needle,
33
+ )) {
34
+ if (listed(row.meta_json, "attachments")) return true;
35
+ }
36
+ const scope: RestNetworkScope = { networkId, networkIds: null, agentRestriction: { userId, username, networkIds: [networkId] } };
37
+ const taskParams: unknown[] = [needle];
38
+ const taskSql = addAgentTimelineScope("SELECT from_name, to_name, meta_json FROM tasks WHERE meta_json LIKE ?1 ESCAPE '\\'", taskParams, scope, { from: "from_name", to: "to_name", fromNodeId: "from_node_id", toNodeId: "to_node_id" });
39
+ for (const row of db.all<{ from_name: string; to_name: string; meta_json: string | null }>(taskSql + " LIMIT 50", ...taskParams)) {
40
+ if (row.from_name !== username && listed(row.meta_json, "attachments")) return true;
41
+ if (listed(row.meta_json, "reply_attachments")) return true;
42
+ }
43
+ const inboxParams: unknown[] = [needle];
44
+ const inboxSql = addOwnTrafficScope("SELECT session_name, meta_json FROM inbox WHERE meta_json LIKE ?1 ESCAPE '\\'", inboxParams, scope, { from: "from_session", to: "session_name" });
45
+ for (const row of db.all<{ session_name: string; meta_json: string | null }>(inboxSql + " LIMIT 50", ...inboxParams)) {
46
+ if (row.session_name === username && listed(row.meta_json, "attachments")) return true;
47
+ }
48
+ return false;
49
+ }
50
+
51
+ /** 受限成员能不能用这个文件(下载 / 当附件转给 Agent):自己传的,或 restrictedMemberSeesFile。 */
52
+ export function restrictedMemberCanUseFile(userId: string, username: string, networkId: string, fileId: string): boolean {
53
+ if (!FILE_ID_REGEX.test(fileId)) return false;
54
+ const path = indexEntryPath(fileId);
55
+ if (!path || !existsSync(path)) return false;
56
+ let entry: any;
57
+ try { entry = JSON.parse(readFileSync(path, "utf8")); } catch { return false; }
58
+ if (!validateIndexEntry(entry) || entry.file_id !== fileId) return false;
59
+ if (entry.network_id !== networkId) return false;
60
+ if (entry.owner_id === userId) return true;
61
+ return restrictedMemberSeesFile(userId, username, networkId, fileId);
62
+ }
63
+
64
+ /**
65
+ * 受限成员发给 Agent 的任务 / 消息里的附件:每个 file_id 都必须是他自己能用的文件。
66
+ * 返回第一个不合格的 file_id(调用方回 403),全部合格返回 null。
67
+ */
68
+ export function restrictedMemberAttachmentsDenied(userId: string, username: string, networkId: string, raw: unknown): string | null {
69
+ if (!Array.isArray(raw)) return null;
70
+ for (const item of raw) {
71
+ const fileId = item && typeof item === "object" ? (item as { file_id?: unknown }).file_id : undefined;
72
+ if (fileId === undefined) continue;
73
+ if (typeof fileId !== "string" || !restrictedMemberCanUseFile(userId, username, networkId, fileId)) return String(fileId);
74
+ }
75
+ return null;
76
+ }
@@ -0,0 +1,31 @@
1
+ // #2614(第三轮)—— 首次 sweep 不是“等 N 秒”,而是“等循环安静”。
2
+ //
3
+ // 两次部署实测:60 秒后仍撞上风暴(max 1238ms);180 秒后撞得更狠(max 3919ms,风暴持续 5 分钟)。
4
+ // 这里钉住判据本身(纯函数),不看时钟、不看真实 hub。
5
+ import { describe, expect, test } from "bun:test";
6
+ import { firstSweepShouldWait, FIRST_SWEEP_QUIET_INFLIGHT } from "./retention.js";
7
+
8
+ const NOW = Date.parse("2026-10-27T12:00:00.000Z");
9
+ const iso = (s: number) => new Date(NOW - s * 1000).toISOString();
10
+
11
+ describe("firstSweepShouldWait (#2614)", () => {
12
+ test("waits while requests are queued", () => {
13
+ expect(firstSweepShouldWait({ now: NOW, inflight: FIRST_SWEEP_QUIET_INFLIGHT + 1, lastStallAtIso: null })).toBe(true);
14
+ });
15
+
16
+ test("waits while the loop stalled within the last minute", () => {
17
+ expect(firstSweepShouldWait({ now: NOW, inflight: 0, lastStallAtIso: iso(30) })).toBe(true);
18
+ });
19
+
20
+ test("runs once inflight is low and the last stall is old enough", () => {
21
+ expect(firstSweepShouldWait({ now: NOW, inflight: 3, lastStallAtIso: iso(120) })).toBe(false);
22
+ });
23
+
24
+ test("runs when there has never been a stall", () => {
25
+ expect(firstSweepShouldWait({ now: NOW, inflight: 0, lastStallAtIso: null })).toBe(false);
26
+ });
27
+
28
+ test("an unparseable stall timestamp does not block forever", () => {
29
+ expect(firstSweepShouldWait({ now: NOW, inflight: 0, lastStallAtIso: "not-a-date" })).toBe(false);
30
+ });
31
+ });
@@ -105,36 +105,36 @@ const STRICT_CFG: RetentionConfig = {
105
105
  };
106
106
 
107
107
  describe("sweepRetention — high-frequency telemetry", () => {
108
- test("deletes agent_telemetry older than telemetryDays, keeps fresh", () => {
108
+ test("deletes agent_telemetry older than telemetryDays, keeps fresh", async () => {
109
109
  insertTelemetry({ daysAgo: 0 }); // fresh
110
110
  insertTelemetry({ daysAgo: 1 }); // fresh
111
111
  insertTelemetry({ daysAgo: 6 }); // just within 7d
112
112
  insertTelemetry({ daysAgo: 8 }); // past 7d
113
113
  insertTelemetry({ daysAgo: 30 }); // way past
114
114
 
115
- const r = sweepRetention(STRICT_CFG);
115
+ const r = await sweepRetention(STRICT_CFG);
116
116
 
117
117
  expect(r.deletes.agent_telemetry).toBe(2);
118
118
  expect(count("agent_telemetry")).toBe(3);
119
119
  });
120
120
 
121
- test("is idempotent: second sweep is a no-op on the same horizon", () => {
121
+ test("is idempotent: second sweep is a no-op on the same horizon", async () => {
122
122
  insertTelemetry({ daysAgo: 0 });
123
123
  insertTelemetry({ daysAgo: 10 });
124
124
 
125
- const first = sweepRetention(STRICT_CFG);
126
- const second = sweepRetention(STRICT_CFG);
125
+ const first = await sweepRetention(STRICT_CFG);
126
+ const second = await sweepRetention(STRICT_CFG);
127
127
 
128
128
  expect(first.deletes.agent_telemetry).toBe(1);
129
129
  expect(second.deletes.agent_telemetry).toBe(0);
130
130
  expect(count("agent_telemetry")).toBe(1);
131
131
  });
132
132
 
133
- test("negative telemetryDays opts out of telemetry sweep", () => {
133
+ test("negative telemetryDays opts out of telemetry sweep", async () => {
134
134
  insertTelemetry({ daysAgo: 100 });
135
135
  insertTelemetry({ daysAgo: 200 });
136
136
 
137
- const r = sweepRetention({ ...STRICT_CFG, telemetryDays: -1 });
137
+ const r = await sweepRetention({ ...STRICT_CFG, telemetryDays: -1 });
138
138
 
139
139
  expect(r.deletes.agent_telemetry).toBe(0);
140
140
  expect(count("agent_telemetry")).toBe(2);
@@ -142,26 +142,26 @@ describe("sweepRetention — high-frequency telemetry", () => {
142
142
  });
143
143
 
144
144
  describe("sweepRetention — task_events / audit_log", () => {
145
- test("deletes task_events older than taskEventsDays", () => {
145
+ test("deletes task_events older than taskEventsDays", async () => {
146
146
  insertTaskEvent(0);
147
147
  insertTaskEvent(15);
148
148
  insertTaskEvent(31);
149
149
  insertTaskEvent(45);
150
150
 
151
- const r = sweepRetention(STRICT_CFG);
151
+ const r = await sweepRetention(STRICT_CFG);
152
152
 
153
153
  expect(r.deletes.task_events).toBe(2);
154
154
  expect(count("task_events")).toBe(2);
155
155
  });
156
156
 
157
- test("deletes audit_log older than auditLogDays (longer horizon)", () => {
157
+ test("deletes audit_log older than auditLogDays (longer horizon)", async () => {
158
158
  insertAudit(0);
159
159
  insertAudit(30); // young
160
160
  insertAudit(89); // just within 90d
161
161
  insertAudit(91); // past
162
162
  insertAudit(365); // way past
163
163
 
164
- const r = sweepRetention(STRICT_CFG);
164
+ const r = await sweepRetention(STRICT_CFG);
165
165
 
166
166
  expect(r.deletes.audit_log).toBe(2);
167
167
  expect(count("audit_log")).toBe(3);
@@ -169,33 +169,33 @@ describe("sweepRetention — task_events / audit_log", () => {
169
169
  });
170
170
 
171
171
  describe("sweepRetention — inbox (acked only)", () => {
172
- test("deletes acked inbox older than ackedInboxDays, never unacked", () => {
172
+ test("deletes acked inbox older than ackedInboxDays, never unacked", async () => {
173
173
  insertInbox({ acked: 1, daysAgo: 0 }); // acked fresh — keep
174
174
  insertInbox({ acked: 1, daysAgo: 30 }); // acked old — delete
175
175
  insertInbox({ acked: 0, daysAgo: 30 }); // unacked old — KEEP (could still be in-flight)
176
176
  insertInbox({ acked: 0, daysAgo: 365 });// unacked ancient — KEEP
177
177
 
178
- const r = sweepRetention(STRICT_CFG);
178
+ const r = await sweepRetention(STRICT_CFG);
179
179
 
180
180
  expect(r.deletes.inbox).toBe(1);
181
181
  expect(count("inbox")).toBe(3);
182
182
  });
183
183
 
184
- test("does not touch unacked rows even at extreme ages (operator concern)", () => {
184
+ test("does not touch unacked rows even at extreme ages (operator concern)", async () => {
185
185
  // Why this test exists: a misread DELETE that forgot the
186
186
  // `acked = 1` predicate would silently drop in-flight deliveries
187
187
  // for agents temporarily offline. That's a correctness bug, not a
188
188
  // retention bug — pin it.
189
189
  for (let i = 0; i < 10; i++) insertInbox({ acked: 0, daysAgo: 365 });
190
190
 
191
- sweepRetention(STRICT_CFG);
191
+ await sweepRetention(STRICT_CFG);
192
192
 
193
193
  expect(count("inbox")).toBe(10);
194
194
  });
195
195
  });
196
196
 
197
197
  describe("sweepRetention — tasks (terminal status only)", () => {
198
- test("deletes terminal-status tasks older than horizon (replied with no child also reaped)", () => {
198
+ test("deletes terminal-status tasks older than horizon (replied with no child also reaped)", async () => {
199
199
  insertTask({ status: "completed", daysAgo: 35 }); // delete (safe-terminal)
200
200
  insertTask({ status: "cancelled", daysAgo: 35 }); // delete (safe-terminal)
201
201
  insertTask({ status: "failed", daysAgo: 35 }); // delete (safe-terminal)
@@ -205,7 +205,7 @@ describe("sweepRetention — tasks (terminal status only)", () => {
205
205
  insertTask({ status: "delivered", daysAgo: 365 }); // active — KEEP
206
206
  insertTask({ status: "replied", daysAgo: 365 }); // replied + no children → delete (round-2 fix)
207
207
 
208
- const r = sweepRetention(STRICT_CFG);
208
+ const r = await sweepRetention(STRICT_CFG);
209
209
 
210
210
  expect(r.deletes.tasks).toBe(5);
211
211
  expect(count("tasks")).toBe(3);
@@ -217,20 +217,20 @@ describe("sweepRetention — tasks (terminal status only)", () => {
217
217
  // full retention window after completion. Sweeping by created_at
218
218
  // alone reaps it the instant it enters terminal state → operators
219
219
  // get zero post-terminal retention.
220
- test("60d-old created task completed today is KEPT (uses completed_at, not created_at)", () => {
220
+ test("60d-old created task completed today is KEPT (uses completed_at, not created_at)", async () => {
221
221
  insertTask({
222
222
  status: "completed",
223
223
  daysAgo: 60, // created 60 days ago (way past horizon)
224
224
  completedDaysAgo: 0, // completed today (within horizon)
225
225
  });
226
226
 
227
- const r = sweepRetention(STRICT_CFG);
227
+ const r = await sweepRetention(STRICT_CFG);
228
228
 
229
229
  expect(r.deletes.tasks).toBe(0);
230
230
  expect(count("tasks")).toBe(1);
231
231
  });
232
232
 
233
- test("legacy row with NULL completed_at falls back to created_at (back-compat)", () => {
233
+ test("legacy row with NULL completed_at falls back to created_at (back-compat)", async () => {
234
234
  // Old DB rows that pre-date the completed_at column. The COALESCE
235
235
  // gracefully falls back so we don't permanently leak legacy data.
236
236
  insertTask({
@@ -239,20 +239,20 @@ describe("sweepRetention — tasks (terminal status only)", () => {
239
239
  completedDaysAgo: null, // explicit NULL (legacy)
240
240
  });
241
241
 
242
- const r = sweepRetention(STRICT_CFG);
242
+ const r = await sweepRetention(STRICT_CFG);
243
243
 
244
244
  expect(r.deletes.tasks).toBe(1);
245
245
  expect(count("tasks")).toBe(0);
246
246
  });
247
247
 
248
- test("recently-completed but past-horizon-completion gets reaped", () => {
248
+ test("recently-completed but past-horizon-completion gets reaped", async () => {
249
249
  insertTask({
250
250
  status: "completed",
251
251
  daysAgo: 60,
252
252
  completedDaysAgo: 35, // completed 35d ago — past 30d horizon
253
253
  });
254
254
 
255
- const r = sweepRetention(STRICT_CFG);
255
+ const r = await sweepRetention(STRICT_CFG);
256
256
 
257
257
  expect(r.deletes.tasks).toBe(1);
258
258
  expect(count("tasks")).toBe(0);
@@ -267,7 +267,7 @@ describe("sweepRetention — tasks (terminal status only)", () => {
267
267
  //
268
268
  // These three tests pin the corrected behaviour.
269
269
 
270
- test("replied with active child task is KEPT (chain ancestor safety)", () => {
270
+ test("replied with active child task is KEPT (chain ancestor safety)", async () => {
271
271
  const parent = insertTask({
272
272
  status: "replied",
273
273
  daysAgo: 365,
@@ -281,34 +281,34 @@ describe("sweepRetention — tasks (terminal status only)", () => {
281
281
  [uuidv4(), parent]
282
282
  );
283
283
 
284
- const r = sweepRetention(STRICT_CFG);
284
+ const r = await sweepRetention(STRICT_CFG);
285
285
 
286
286
  expect(r.deletes.tasks).toBe(0);
287
287
  expect(count("tasks")).toBe(2);
288
288
  });
289
289
 
290
- test("replied with NO child references AND past horizon is DELETED", () => {
290
+ test("replied with NO child references AND past horizon is DELETED", async () => {
291
291
  insertTask({ status: "replied", daysAgo: 365, completedDaysAgo: 60 });
292
292
 
293
- const r = sweepRetention(STRICT_CFG);
293
+ const r = await sweepRetention(STRICT_CFG);
294
294
 
295
295
  expect(r.deletes.tasks).toBe(1);
296
296
  expect(count("tasks")).toBe(0);
297
297
  });
298
298
 
299
- test("replied with NO child references AND within horizon is KEPT", () => {
299
+ test("replied with NO child references AND within horizon is KEPT", async () => {
300
300
  // Just-completed replied with no children — needs to live for
301
301
  // the full retention window in case dashboard/audit wants to see
302
302
  // recent activity.
303
303
  insertTask({ status: "replied", daysAgo: 5, completedDaysAgo: 5 });
304
304
 
305
- const r = sweepRetention(STRICT_CFG);
305
+ const r = await sweepRetention(STRICT_CFG);
306
306
 
307
307
  expect(r.deletes.tasks).toBe(0);
308
308
  expect(count("tasks")).toBe(1);
309
309
  });
310
310
 
311
- test("replied with child that's been ITSELF swept stays sweepable next round", () => {
311
+ test("replied with child that's been ITSELF swept stays sweepable next round", async () => {
312
312
  // Two-round scenario: parent + terminal child. Round 1: child
313
313
  // (cancelled, past horizon) gets reaped → parent now has no
314
314
  // children. Round 2: parent (replied, past horizon, no children)
@@ -324,7 +324,7 @@ describe("sweepRetention — tasks (terminal status only)", () => {
324
324
  [uuidv4(), parent]
325
325
  );
326
326
 
327
- const r1 = sweepRetention(STRICT_CFG);
327
+ const r1 = await sweepRetention(STRICT_CFG);
328
328
  // Round 1: only the cancelled child can be reaped (parent still
329
329
  // has it as a referencing row at the time the DELETE NOT EXISTS
330
330
  // is evaluated). DELETE order in SQLite is single-statement, so
@@ -335,13 +335,13 @@ describe("sweepRetention — tasks (terminal status only)", () => {
335
335
 
336
336
  // Re-run: should converge with zero rows regardless of whether
337
337
  // round 1 took both or just the child.
338
- sweepRetention(STRICT_CFG);
338
+ await sweepRetention(STRICT_CFG);
339
339
  expect(count("tasks")).toBe(0);
340
340
  });
341
341
  });
342
342
 
343
343
  describe("sweepRetention — VACUUM hook", () => {
344
- test("returns wal_checkpoint pages-moved and incremental freed-pages", () => {
344
+ test("returns wal_checkpoint pages-moved and incremental freed-pages", async () => {
345
345
  // Just exercise the codepath — Bun's sqlite layer may or may not
346
346
  // return values the operator cares about depending on PRAGMA
347
347
  // settings. The point is that the call doesn't error and the
@@ -349,7 +349,7 @@ describe("sweepRetention — VACUUM hook", () => {
349
349
  insertTelemetry({ daysAgo: 100 });
350
350
  insertTelemetry({ daysAgo: 100 });
351
351
 
352
- const r = sweepRetention(STRICT_CFG);
352
+ const r = await sweepRetention(STRICT_CFG);
353
353
 
354
354
  expect(r.vacuum.errored).toBe(false);
355
355
  // walCheckpointPagesMoved may be 0 if there's nothing in the WAL.
@@ -361,7 +361,7 @@ describe("sweepRetention — VACUUM hook", () => {
361
361
  });
362
362
 
363
363
  describe("readRetentionConfig — env-var overrides", () => {
364
- test("falls back to defaults when env vars unset", () => {
364
+ test("falls back to defaults when env vars unset", async () => {
365
365
  delete process.env.COMMHUB_RETENTION_TELEMETRY_DAYS;
366
366
  delete process.env.COMMHUB_RETENTION_TASK_EVENTS_DAYS;
367
367
 
@@ -372,7 +372,7 @@ describe("readRetentionConfig — env-var overrides", () => {
372
372
  expect(cfg.auditLogDays).toBe(90);
373
373
  });
374
374
 
375
- test("env override wins", () => {
375
+ test("env override wins", async () => {
376
376
  process.env.COMMHUB_RETENTION_TELEMETRY_DAYS = "3";
377
377
  process.env.COMMHUB_RETENTION_AUDIT_DAYS = "180";
378
378
 
@@ -385,14 +385,14 @@ describe("readRetentionConfig — env-var overrides", () => {
385
385
  delete process.env.COMMHUB_RETENTION_AUDIT_DAYS;
386
386
  });
387
387
 
388
- test("non-finite env falls back silently (no operator footgun)", () => {
388
+ test("non-finite env falls back silently (no operator footgun)", async () => {
389
389
  process.env.COMMHUB_RETENTION_TELEMETRY_DAYS = "not-a-number";
390
390
  const cfg = readRetentionConfig();
391
391
  expect(cfg.telemetryDays).toBe(7);
392
392
  delete process.env.COMMHUB_RETENTION_TELEMETRY_DAYS;
393
393
  });
394
394
 
395
- test("negative env value passes through (operator opt-out)", () => {
395
+ test("negative env value passes through (operator opt-out)", async () => {
396
396
  process.env.COMMHUB_RETENTION_INBOX_ACKED_DAYS = "-1";
397
397
  const cfg = readRetentionConfig();
398
398
  expect(cfg.ackedInboxDays).toBe(-1);
@@ -412,7 +412,7 @@ describe("agent_telemetry index split (round 2/4 review ② — query plan)", ()
412
412
  // (EXPLAIN QUERY PLAN) lives below to prove the OR-disjunction can
413
413
  // now use an index UNION instead of full scan.
414
414
 
415
- test("split indexes exist; old combined is gone", () => {
415
+ test("split indexes exist; old combined is gone", async () => {
416
416
  const idx = db.all<{ name: string }>(
417
417
  "SELECT name FROM sqlite_master WHERE type = 'index' AND tbl_name = 'agent_telemetry' ORDER BY name"
418
418
  );
@@ -423,7 +423,7 @@ describe("agent_telemetry index split (round 2/4 review ② — query plan)", ()
423
423
  expect(names).not.toContain("idx_agent_telemetry_host_time");
424
424
  });
425
425
 
426
- test("EXPLAIN QUERY PLAN for server-health (hostname OR ip) uses split indexes via index UNION", () => {
426
+ test("EXPLAIN QUERY PLAN for server-health (hostname OR ip) uses split indexes via index UNION", async () => {
427
427
  // Mirror the actual query from index.ts /api/server-health/:host
428
428
  // (post-addNetworkScope, network_id pinned via direct equality —
429
429
  // NOT COALESCE; addNetworkScope appends `AND network_id = ?` and
@@ -448,3 +448,63 @@ describe("agent_telemetry index split (round 2/4 review ② — query plan)", ()
448
448
  expect(planText).not.toMatch(/^SCAN agent_telemetry$/m);
449
449
  });
450
450
  });
451
+
452
+ // ── #2614 —— 分批 sweep(每小时一次的 8–11 秒事件循环停顿)──
453
+ describe("sweepRetention — chunked deletes (#2614)", () => {
454
+ const withChunkRows = async (rows: number, fn: () => Promise<void>) => {
455
+ const prev = process.env.COMMHUB_RETENTION_CHUNK_ROWS;
456
+ process.env.COMMHUB_RETENTION_CHUNK_ROWS = String(rows);
457
+ try {
458
+ await fn();
459
+ } finally {
460
+ if (prev === undefined) delete process.env.COMMHUB_RETENTION_CHUNK_ROWS;
461
+ else process.env.COMMHUB_RETENTION_CHUNK_ROWS = prev;
462
+ }
463
+ };
464
+
465
+ test("deletes a large backlog in multiple batches, all rows gone", async () => {
466
+ // 生产现场:一次 DELETE 删完 → 10 秒静默。这里把批大小压到 50 行,
467
+ // 断言「确实分了多批」且「结果与一次删完等价」(不丢行)。
468
+ await withChunkRows(50, async () => {
469
+ for (let i = 0; i < 120; i++) insertTelemetry({ daysAgo: 30 });
470
+ const before = count("agent_telemetry");
471
+ const r = await sweepRetention(STRICT_CFG);
472
+
473
+ expect(r.deletes.agent_telemetry).toBe(120);
474
+ expect(r.batches).toBeGreaterThanOrEqual(3); // 50 + 50 + 20
475
+ expect(r.truncated).toEqual([]);
476
+ expect(count("agent_telemetry")).toBe(before - 120);
477
+ });
478
+ });
479
+
480
+ test("an exact multiple of the chunk size leaves nothing behind", async () => {
481
+ // 100 行、批大小 50 ⇒ 两批「刚好装满」。游标版在这里必须再多查一次才知道删干净了,
482
+ // 否则会留下恰好等于批大小的残留(这是分批删除最典型的 off-by-one)。
483
+ await withChunkRows(50, async () => {
484
+ for (let i = 0; i < 100; i++) insertTelemetry({ daysAgo: 40 });
485
+ const r = await sweepRetention(STRICT_CFG);
486
+ expect(r.deletes.agent_telemetry).toBe(100);
487
+ expect(r.batches).toBeGreaterThanOrEqual(2);
488
+ expect(count("agent_telemetry")).toBe(0);
489
+ });
490
+ });
491
+
492
+ test("task child-safety still holds under chunking (parent with a live child is kept)", async () => {
493
+ // 父任务(旧、replied)**有未终止的子任务** ⇒ 是链祖先,必须留下;
494
+ // 分批不能改变这个语义 —— 用具体行断言,不用总数(同文件其他用例会留残留)。
495
+ const parent = insertTask({ status: "replied", daysAgo: 90 });
496
+ const child = uuidv4();
497
+ db.run(
498
+ `INSERT INTO tasks (task_id, from_name, to_name, priority, status, content, requires_response, created_at, parent_task_id)
499
+ VALUES (?1, 'a', 'b', 'normal', 'running', 'child', 0, datetime('now', '-1 days'), ?2)`,
500
+ [child, parent],
501
+ );
502
+ await withChunkRows(50, async () => {
503
+ await sweepRetention(STRICT_CFG);
504
+ });
505
+ const parentRow = db.get<{ task_id: string }>("SELECT task_id FROM tasks WHERE task_id = ?1", parent);
506
+ const childRow = db.get<{ task_id: string }>("SELECT task_id FROM tasks WHERE task_id = ?1", child);
507
+ expect(parentRow?.task_id).toBe(parent);
508
+ expect(childRow?.task_id).toBe(child);
509
+ });
510
+ });